How to use Write method of cmd Package

Best K6 code snippet using cmd.Write

bash_completions.go

Source:bash_completions.go Github

copy

Full Screen

...14 BashCompCustom = "cobra_annotation_bash_completion_custom"15 BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"16 BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"17)18func writePreamble(buf io.StringWriter, name string) {19 WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))20 WriteStringAndCheck(buf, fmt.Sprintf(`21__%[1]s_debug()22{23 if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then24 echo "$*" >> "${BASH_COMP_DEBUG_FILE}"25 fi26}27# Homebrew on Macs have version 1.3 of bash-completion which doesn't include28# _init_completion. This is a very minimal version of that function.29__%[1]s_init_completion()30{31 COMPREPLY=()32 _get_comp_words_by_ref "$@" cur prev words cword33}34__%[1]s_index_of_word()35{36 local w word=$137 shift38 index=039 for w in "$@"; do40 [[ $w = "$word" ]] && return41 index=$((index+1))42 done43 index=-144}45__%[1]s_contains_word()46{47 local w word=$1; shift48 for w in "$@"; do49 [[ $w = "$word" ]] && return50 done51 return 152}53__%[1]s_handle_go_custom_completion()54{55 __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"56 local shellCompDirectiveError=%[3]d57 local shellCompDirectiveNoSpace=%[4]d58 local shellCompDirectiveNoFileComp=%[5]d59 local shellCompDirectiveFilterFileExt=%[6]d60 local shellCompDirectiveFilterDirs=%[7]d61 local out requestComp lastParam lastChar comp directive args62 # Prepare the command to request completions for the program.63 # Calling ${words[0]} instead of directly %[1]s allows to handle aliases64 args=("${words[@]:1}")65 requestComp="${words[0]} %[2]s ${args[*]}"66 lastParam=${words[$((${#words[@]}-1))]}67 lastChar=${lastParam:$((${#lastParam}-1)):1}68 __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"69 if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then70 # If the last parameter is complete (there is a space following it)71 # We add an extra empty parameter so we can indicate this to the go method.72 __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter"73 requestComp="${requestComp} \"\""74 fi75 __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"76 # Use eval to handle any environment variables and such77 out=$(eval "${requestComp}" 2>/dev/null)78 # Extract the directive integer at the very end of the output following a colon (:)79 directive=${out##*:}80 # Remove the directive81 out=${out%%:*}82 if [ "${directive}" = "${out}" ]; then83 # There is not directive specified84 directive=085 fi86 __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"87 __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"88 if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then89 # Error code. No completion.90 __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"91 return92 else93 if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then94 if [[ $(type -t compopt) = "builtin" ]]; then95 __%[1]s_debug "${FUNCNAME[0]}: activating no space"96 compopt -o nospace97 fi98 fi99 if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then100 if [[ $(type -t compopt) = "builtin" ]]; then101 __%[1]s_debug "${FUNCNAME[0]}: activating no file completion"102 compopt +o default103 fi104 fi105 fi106 if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then107 # File extension filtering108 local fullFilter filter filteringCmd109 # Do not use quotes around the $out variable or else newline110 # characters will be kept.111 for filter in ${out[*]}; do112 fullFilter+="$filter|"113 done114 filteringCmd="_filedir $fullFilter"115 __%[1]s_debug "File filtering command: $filteringCmd"116 $filteringCmd117 elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then118 # File completion for directories only119 local subDir120 # Use printf to strip any trailing newline121 subdir=$(printf "%%s" "${out[0]}")122 if [ -n "$subdir" ]; then123 __%[1]s_debug "Listing directories in $subdir"124 __%[1]s_handle_subdirs_in_dir_flag "$subdir"125 else126 __%[1]s_debug "Listing directories in ."127 _filedir -d128 fi129 else130 while IFS='' read -r comp; do131 COMPREPLY+=("$comp")132 done < <(compgen -W "${out[*]}" -- "$cur")133 fi134}135__%[1]s_handle_reply()136{137 __%[1]s_debug "${FUNCNAME[0]}"138 local comp139 case $cur in140 -*)141 if [[ $(type -t compopt) = "builtin" ]]; then142 compopt -o nospace143 fi144 local allflags145 if [ ${#must_have_one_flag[@]} -ne 0 ]; then146 allflags=("${must_have_one_flag[@]}")147 else148 allflags=("${flags[*]} ${two_word_flags[*]}")149 fi150 while IFS='' read -r comp; do151 COMPREPLY+=("$comp")152 done < <(compgen -W "${allflags[*]}" -- "$cur")153 if [[ $(type -t compopt) = "builtin" ]]; then154 [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace155 fi156 # complete after --flag=abc157 if [[ $cur == *=* ]]; then158 if [[ $(type -t compopt) = "builtin" ]]; then159 compopt +o nospace160 fi161 local index flag162 flag="${cur%%=*}"163 __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"164 COMPREPLY=()165 if [[ ${index} -ge 0 ]]; then166 PREFIX=""167 cur="${cur#*=}"168 ${flags_completion[${index}]}169 if [ -n "${ZSH_VERSION}" ]; then170 # zsh completion needs --flag= prefix171 eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"172 fi173 fi174 fi175 return 0;176 ;;177 esac178 # check if we are handling a flag with special work handling179 local index180 __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"181 if [[ ${index} -ge 0 ]]; then182 ${flags_completion[${index}]}183 return184 fi185 # we are parsing a flag and don't have a special handler, no completion186 if [[ ${cur} != "${words[cword]}" ]]; then187 return188 fi189 local completions190 completions=("${commands[@]}")191 if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then192 completions+=("${must_have_one_noun[@]}")193 elif [[ -n "${has_completion_function}" ]]; then194 # if a go completion function is provided, defer to that function195 __%[1]s_handle_go_custom_completion196 fi197 if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then198 completions+=("${must_have_one_flag[@]}")199 fi200 while IFS='' read -r comp; do201 COMPREPLY+=("$comp")202 done < <(compgen -W "${completions[*]}" -- "$cur")203 if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then204 while IFS='' read -r comp; do205 COMPREPLY+=("$comp")206 done < <(compgen -W "${noun_aliases[*]}" -- "$cur")207 fi208 if [[ ${#COMPREPLY[@]} -eq 0 ]]; then209 if declare -F __%[1]s_custom_func >/dev/null; then210 # try command name qualified custom func211 __%[1]s_custom_func212 else213 # otherwise fall back to unqualified for compatibility214 declare -F __custom_func >/dev/null && __custom_func215 fi216 fi217 # available in bash-completion >= 2, not always present on macOS218 if declare -F __ltrim_colon_completions >/dev/null; then219 __ltrim_colon_completions "$cur"220 fi221 # If there is only 1 completion and it is a flag with an = it will be completed222 # but we don't want a space after the =223 if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then224 compopt -o nospace225 fi226}227# The arguments should be in the form "ext1|ext2|extn"228__%[1]s_handle_filename_extension_flag()229{230 local ext="$1"231 _filedir "@(${ext})"232}233__%[1]s_handle_subdirs_in_dir_flag()234{235 local dir="$1"236 pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return237}238__%[1]s_handle_flag()239{240 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"241 # if a command required a flag, and we found it, unset must_have_one_flag()242 local flagname=${words[c]}243 local flagvalue244 # if the word contained an =245 if [[ ${words[c]} == *"="* ]]; then246 flagvalue=${flagname#*=} # take in as flagvalue after the =247 flagname=${flagname%%=*} # strip everything after the =248 flagname="${flagname}=" # but put the = back249 fi250 __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"251 if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then252 must_have_one_flag=()253 fi254 # if you set a flag which only applies to this command, don't show subcommands255 if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then256 commands=()257 fi258 # keep flag value with flagname as flaghash259 # flaghash variable is an associative array which is only supported in bash > 3.260 if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then261 if [ -n "${flagvalue}" ] ; then262 flaghash[${flagname}]=${flagvalue}263 elif [ -n "${words[ $((c+1)) ]}" ] ; then264 flaghash[${flagname}]=${words[ $((c+1)) ]}265 else266 flaghash[${flagname}]="true" # pad "true" for bool flag267 fi268 fi269 # skip the argument to a two word flag270 if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then271 __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"272 c=$((c+1))273 # if we are looking for a flags value, don't show commands274 if [[ $c -eq $cword ]]; then275 commands=()276 fi277 fi278 c=$((c+1))279}280__%[1]s_handle_noun()281{282 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"283 if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then284 must_have_one_noun=()285 elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then286 must_have_one_noun=()287 fi288 nouns+=("${words[c]}")289 c=$((c+1))290}291__%[1]s_handle_command()292{293 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"294 local next_command295 if [[ -n ${last_command} ]]; then296 next_command="_${last_command}_${words[c]//:/__}"297 else298 if [[ $c -eq 0 ]]; then299 next_command="_%[1]s_root_command"300 else301 next_command="_${words[c]//:/__}"302 fi303 fi304 c=$((c+1))305 __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"306 declare -F "$next_command" >/dev/null && $next_command307}308__%[1]s_handle_word()309{310 if [[ $c -ge $cword ]]; then311 __%[1]s_handle_reply312 return313 fi314 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"315 if [[ "${words[c]}" == -* ]]; then316 __%[1]s_handle_flag317 elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then318 __%[1]s_handle_command319 elif [[ $c -eq 0 ]]; then320 __%[1]s_handle_command321 elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then322 # aliashash variable is an associative array which is only supported in bash > 3.323 if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then324 words[c]=${aliashash[${words[c]}]}325 __%[1]s_handle_command326 else327 __%[1]s_handle_noun328 fi329 else330 __%[1]s_handle_noun331 fi332 __%[1]s_handle_word333}334`, name, ShellCompNoDescRequestCmd,335 ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,336 ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))337}338func writePostscript(buf io.StringWriter, name string) {339 name = strings.Replace(name, ":", "__", -1)340 WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))341 WriteStringAndCheck(buf, fmt.Sprintf(`{342 local cur prev words cword343 declare -A flaghash 2>/dev/null || :344 declare -A aliashash 2>/dev/null || :345 if declare -F _init_completion >/dev/null 2>&1; then346 _init_completion -s || return347 else348 __%[1]s_init_completion -n "=" || return349 fi350 local c=0351 local flags=()352 local two_word_flags=()353 local local_nonpersistent_flags=()354 local flags_with_completion=()355 local flags_completion=()356 local commands=("%[1]s")357 local must_have_one_flag=()358 local must_have_one_noun=()359 local has_completion_function360 local last_command361 local nouns=()362 __%[1]s_handle_word363}364`, name))365 WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then366 complete -o default -F __start_%s %s367else368 complete -o default -o nospace -F __start_%s %s369fi370`, name, name, name, name))371 WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n")372}373func writeCommands(buf io.StringWriter, cmd *Command) {374 WriteStringAndCheck(buf, " commands=()\n")375 for _, c := range cmd.Commands() {376 if !c.IsAvailableCommand() && c != cmd.helpCommand {377 continue378 }379 WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name()))380 writeCmdAliases(buf, c)381 }382 WriteStringAndCheck(buf, "\n")383}384func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) {385 for key, value := range annotations {386 switch key {387 case BashCompFilenameExt:388 WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))389 var ext string390 if len(value) > 0 {391 ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")392 } else {393 ext = "_filedir"394 }395 WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))396 case BashCompCustom:397 WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))398 if len(value) > 0 {399 handlers := strings.Join(value, "; ")400 WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers))401 } else {402 WriteStringAndCheck(buf, " flags_completion+=(:)\n")403 }404 case BashCompSubdirsInDir:405 WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))406 var ext string407 if len(value) == 1 {408 ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]409 } else {410 ext = "_filedir -d"411 }412 WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))413 }414 }415}416const cbn = "\")\n"417func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {418 name := flag.Shorthand419 format := " "420 if len(flag.NoOptDefVal) == 0 {421 format += "two_word_"422 }423 format += "flags+=(\"-%s" + cbn424 WriteStringAndCheck(buf, fmt.Sprintf(format, name))425 writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)426}427func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {428 name := flag.Name429 format := " flags+=(\"--%s"430 if len(flag.NoOptDefVal) == 0 {431 format += "="432 }433 format += cbn434 WriteStringAndCheck(buf, fmt.Sprintf(format, name))435 if len(flag.NoOptDefVal) == 0 {436 format = " two_word_flags+=(\"--%s" + cbn437 WriteStringAndCheck(buf, fmt.Sprintf(format, name))438 }439 writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)440}441func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {442 name := flag.Name443 format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn444 if len(flag.NoOptDefVal) == 0 {445 format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn446 }447 WriteStringAndCheck(buf, fmt.Sprintf(format, name))448 if len(flag.Shorthand) > 0 {449 WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))450 }451}452// Setup annotations for go completions for registered flags453func prepareCustomAnnotationsForFlags(cmd *Command) {454 for flag := range flagCompletionFunctions {455 // Make sure the completion script calls the __*_go_custom_completion function for456 // every registered flag. We need to do this here (and not when the flag was registered457 // for completion) so that we can know the root command name for the prefix458 // of __<prefix>_go_custom_completion459 if flag.Annotations == nil {460 flag.Annotations = map[string][]string{}461 }462 flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}463 }464}465func writeFlags(buf io.StringWriter, cmd *Command) {466 prepareCustomAnnotationsForFlags(cmd)467 WriteStringAndCheck(buf, ` flags=()468 two_word_flags=()469 local_nonpersistent_flags=()470 flags_with_completion=()471 flags_completion=()472`)473 localNonPersistentFlags := cmd.LocalNonPersistentFlags()474 cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {475 if nonCompletableFlag(flag) {476 return477 }478 writeFlag(buf, flag, cmd)479 if len(flag.Shorthand) > 0 {480 writeShortFlag(buf, flag, cmd)481 }482 // localNonPersistentFlags are used to stop the completion of subcommands when one is set483 // if TraverseChildren is true we should allow to complete subcommands484 if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren {485 writeLocalNonPersistentFlag(buf, flag)486 }487 })488 cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {489 if nonCompletableFlag(flag) {490 return491 }492 writeFlag(buf, flag, cmd)493 if len(flag.Shorthand) > 0 {494 writeShortFlag(buf, flag, cmd)495 }496 })497 WriteStringAndCheck(buf, "\n")498}499func writeRequiredFlag(buf io.StringWriter, cmd *Command) {500 WriteStringAndCheck(buf, " must_have_one_flag=()\n")501 flags := cmd.NonInheritedFlags()502 flags.VisitAll(func(flag *pflag.Flag) {503 if nonCompletableFlag(flag) {504 return505 }506 for key := range flag.Annotations {507 switch key {508 case BashCompOneRequiredFlag:509 format := " must_have_one_flag+=(\"--%s"510 if flag.Value.Type() != "bool" {511 format += "="512 }513 format += cbn514 WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))515 if len(flag.Shorthand) > 0 {516 WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))517 }518 }519 }520 })521}522func writeRequiredNouns(buf io.StringWriter, cmd *Command) {523 WriteStringAndCheck(buf, " must_have_one_noun=()\n")524 sort.Strings(cmd.ValidArgs)525 for _, value := range cmd.ValidArgs {526 // Remove any description that may be included following a tab character.527 // Descriptions are not supported by bash completion.528 value = strings.Split(value, "\t")[0]529 WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))530 }531 if cmd.ValidArgsFunction != nil {532 WriteStringAndCheck(buf, " has_completion_function=1\n")533 }534}535func writeCmdAliases(buf io.StringWriter, cmd *Command) {536 if len(cmd.Aliases) == 0 {537 return538 }539 sort.Strings(cmd.Aliases)540 WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))541 for _, value := range cmd.Aliases {542 WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value))543 WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))544 }545 WriteStringAndCheck(buf, ` fi`)546 WriteStringAndCheck(buf, "\n")547}548func writeArgAliases(buf io.StringWriter, cmd *Command) {549 WriteStringAndCheck(buf, " noun_aliases=()\n")550 sort.Strings(cmd.ArgAliases)551 for _, value := range cmd.ArgAliases {552 WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value))553 }554}555func gen(buf io.StringWriter, cmd *Command) {556 for _, c := range cmd.Commands() {557 if !c.IsAvailableCommand() && c != cmd.helpCommand {558 continue559 }560 gen(buf, c)561 }562 commandName := cmd.CommandPath()563 commandName = strings.Replace(commandName, " ", "_", -1)564 commandName = strings.Replace(commandName, ":", "__", -1)565 if cmd.Root() == cmd {566 WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))567 } else {568 WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName))569 }570 WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName))571 WriteStringAndCheck(buf, "\n")572 WriteStringAndCheck(buf, " command_aliases=()\n")573 WriteStringAndCheck(buf, "\n")574 writeCommands(buf, cmd)575 writeFlags(buf, cmd)576 writeRequiredFlag(buf, cmd)577 writeRequiredNouns(buf, cmd)578 writeArgAliases(buf, cmd)579 WriteStringAndCheck(buf, "}\n\n")580}581// GenBashCompletion generates bash completion file and writes to the passed writer.582func (c *Command) GenBashCompletion(w io.Writer) error {583 buf := new(bytes.Buffer)584 writePreamble(buf, c.Name())585 if len(c.BashCompletionFunction) > 0 {586 buf.WriteString(c.BashCompletionFunction + "\n")587 }588 gen(buf, c)589 writePostscript(buf, c.Name())590 _, err := buf.WriteTo(w)591 return err592}593func nonCompletableFlag(flag *pflag.Flag) bool {594 return flag.Hidden || len(flag.Deprecated) > 0595}596// GenBashCompletionFile generates bash completion file.597func (c *Command) GenBashCompletionFile(filename string) error {598 outFile, err := os.Create(filename)599 if err != nil {600 return err601 }602 defer outFile.Close()603 return c.GenBashCompletion(outFile)604}...

Full Screen

Full Screen

rest_docs.go

Source:rest_docs.go Github

copy

Full Screen

...25func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error {26 flags := cmd.NonInheritedFlags()27 flags.SetOutput(buf)28 if flags.HasAvailableFlags() {29 buf.WriteString("Options\n")30 buf.WriteString("~~~~~~~\n\n::\n\n")31 flags.PrintDefaults()32 buf.WriteString("\n")33 }34 parentFlags := cmd.InheritedFlags()35 parentFlags.SetOutput(buf)36 if parentFlags.HasAvailableFlags() {37 buf.WriteString("Options inherited from parent commands\n")38 buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")39 parentFlags.PrintDefaults()40 buf.WriteString("\n")41 }42 return nil43}44// linkHandler for default ReST hyperlink markup45func defaultLinkHandler(name, ref string) string {46 return fmt.Sprintf("`%s <%s.rst>`_", name, ref)47}48// GenReST creates reStructured Text output.49func GenReST(cmd *cobra.Command, w io.Writer) error {50 return GenReSTCustom(cmd, w, defaultLinkHandler)51}52// GenReSTCustom creates custom reStructured Text output.53func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error {54 cmd.InitDefaultHelpCmd()55 cmd.InitDefaultHelpFlag()56 buf := new(bytes.Buffer)57 name := cmd.CommandPath()58 short := cmd.Short59 long := cmd.Long60 if len(long) == 0 {61 long = short62 }63 ref := strings.Replace(name, " ", "_", -1)64 buf.WriteString(".. _" + ref + ":\n\n")65 buf.WriteString(name + "\n")66 buf.WriteString(strings.Repeat("-", len(name)) + "\n\n")67 buf.WriteString(short + "\n\n")68 buf.WriteString("Synopsis\n")69 buf.WriteString("~~~~~~~~\n\n")70 buf.WriteString("\n" + long + "\n\n")71 if cmd.Runnable() {72 buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine()))73 }74 if len(cmd.Example) > 0 {75 buf.WriteString("Examples\n")76 buf.WriteString("~~~~~~~~\n\n")77 buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " ")))78 }79 if err := printOptionsReST(buf, cmd, name); err != nil {80 return err81 }82 if hasSeeAlso(cmd) {83 buf.WriteString("SEE ALSO\n")84 buf.WriteString("~~~~~~~~\n\n")85 if cmd.HasParent() {86 parent := cmd.Parent()87 pname := parent.CommandPath()88 ref = strings.Replace(pname, " ", "_", -1)89 buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short))90 cmd.VisitParents(func(c *cobra.Command) {91 if c.DisableAutoGenTag {92 cmd.DisableAutoGenTag = c.DisableAutoGenTag93 }94 })95 }96 children := cmd.Commands()97 sort.Sort(byName(children))98 for _, child := range children {99 if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {100 continue101 }102 cname := name + " " + child.Name()103 ref = strings.Replace(cname, " ", "_", -1)104 buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short))105 }106 buf.WriteString("\n")107 }108 if !cmd.DisableAutoGenTag {109 buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n")110 }111 _, err := buf.WriteTo(w)112 return err113}114// GenReSTTree will generate a ReST page for this command and all115// descendants in the directory given.116// This function may not work correctly if your command names have `-` in them.117// If you have `cmd` with two subcmds, `sub` and `sub-third`,118// and `sub` has a subcommand called `third`, it is undefined which119// help output will be in the file `cmd-sub-third.1`.120func GenReSTTree(cmd *cobra.Command, dir string) error {121 emptyStr := func(s string) string { return "" }122 return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)123}124// GenReSTTreeCustom is the the same as GenReSTTree, but125// with custom filePrepender and linkHandler.126func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {127 for _, c := range cmd.Commands() {128 if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {129 continue130 }131 if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil {132 return err133 }134 }135 basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst"136 filename := filepath.Join(dir, basename)137 f, err := os.Create(filename)138 if err != nil {139 return err140 }141 defer f.Close()142 if _, err := io.WriteString(f, filePrepender(filename)); err != nil {143 return err144 }145 if err := GenReSTCustom(cmd, f, linkHandler); err != nil {146 return err147 }148 return nil149}150// adapted from: https://github.com/kr/text/blob/main/indent.go151func indentString(s, p string) string {152 var res []byte153 b := []byte(s)154 prefix := []byte(p)155 bol := true156 for _, c := range b {...

Full Screen

Full Screen

md_docs.go

Source:md_docs.go Github

copy

Full Screen

...25func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {26 flags := cmd.NonInheritedFlags()27 flags.SetOutput(buf)28 if flags.HasAvailableFlags() {29 buf.WriteString("### Options\n\n```\n")30 flags.PrintDefaults()31 buf.WriteString("```\n\n")32 }33 parentFlags := cmd.InheritedFlags()34 parentFlags.SetOutput(buf)35 if parentFlags.HasAvailableFlags() {36 buf.WriteString("### Options inherited from parent commands\n\n```\n")37 parentFlags.PrintDefaults()38 buf.WriteString("```\n\n")39 }40 return nil41}42// GenMarkdown creates markdown output.43func GenMarkdown(cmd *cobra.Command, w io.Writer) error {44 return GenMarkdownCustom(cmd, w, func(s string) string { return s })45}46// GenMarkdownCustom creates custom markdown output.47func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {48 cmd.InitDefaultHelpCmd()49 cmd.InitDefaultHelpFlag()50 buf := new(bytes.Buffer)51 name := cmd.CommandPath()52 buf.WriteString("## " + name + "\n\n")53 buf.WriteString(cmd.Short + "\n\n")54 if len(cmd.Long) > 0 {55 buf.WriteString("### Synopsis\n\n")56 buf.WriteString(cmd.Long + "\n\n")57 }58 if cmd.Runnable() {59 buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))60 }61 if len(cmd.Example) > 0 {62 buf.WriteString("### Examples\n\n")63 buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))64 }65 if err := printOptions(buf, cmd, name); err != nil {66 return err67 }68 if hasSeeAlso(cmd) {69 buf.WriteString("### SEE ALSO\n\n")70 if cmd.HasParent() {71 parent := cmd.Parent()72 pname := parent.CommandPath()73 link := pname + ".md"74 link = strings.Replace(link, " ", "_", -1)75 buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))76 cmd.VisitParents(func(c *cobra.Command) {77 if c.DisableAutoGenTag {78 cmd.DisableAutoGenTag = c.DisableAutoGenTag79 }80 })81 }82 children := cmd.Commands()83 sort.Sort(byName(children))84 for _, child := range children {85 if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {86 continue87 }88 cname := name + " " + child.Name()89 link := cname + ".md"90 link = strings.Replace(link, " ", "_", -1)91 buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))92 }93 buf.WriteString("\n")94 }95 if !cmd.DisableAutoGenTag {96 buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")97 }98 _, err := buf.WriteTo(w)99 return err100}101// GenMarkdownTree will generate a markdown page for this command and all102// descendants in the directory given. The header may be nil.103// This function may not work correctly if your command names have `-` in them.104// If you have `cmd` with two subcmds, `sub` and `sub-third`,105// and `sub` has a subcommand called `third`, it is undefined which106// help output will be in the file `cmd-sub-third.1`.107func GenMarkdownTree(cmd *cobra.Command, dir string) error {108 identity := func(s string) string { return s }109 emptyStr := func(s string) string { return "" }110 return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)111}112// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but113// with custom filePrepender and linkHandler.114func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {115 for _, c := range cmd.Commands() {116 if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {117 continue118 }119 if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {120 return err121 }122 }123 basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"124 filename := filepath.Join(dir, basename)125 f, err := os.Create(filename)126 if err != nil {127 return err128 }129 defer f.Close()130 if _, err := io.WriteString(f, filePrepender(filename)); err != nil {131 return err132 }133 if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {134 return err135 }136 return nil137}...

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ping", "google.com")4 stdin, _ := cmd.StdinPipe()5 stdout, _ := cmd.StdoutPipe()6 stderr, _ := cmd.StderrPipe()7 cmd.Start()8 stdin.Write([]byte("Hello, how are you?"))9 stdin.Close()10 bytesErr, _ := ioutil.ReadAll(stderr)11 bytesOut, _ := ioutil.ReadAll(stdout)12 fmt.Println(string(bytesErr))13 fmt.Println(string(bytesOut))14 cmd.Wait()15}16import (17func main() {18 cmd := exec.Command("ping", "google.com")19 stdin, _ := cmd.StdinPipe()20 stdout, _ := cmd.StdoutPipe()21 stderr, _ := cmd.StderrPipe()22 cmd.Run()23 stdin.Write([]byte("Hello, how are you?"))24 stdin.Close()25 bytesErr, _ := ioutil.ReadAll(stderr)26 bytesOut, _ := ioutil.ReadAll(stdout)27 fmt.Println(string(bytesErr))28 fmt.Println(string(bytesOut))29}30import (31func main() {32 cmd := exec.Command("ping", "google.com")33 stdin, _ := cmd.StdinPipe()34 stdout, _ := cmd.StdoutPipe()35 stderr, _ := cmd.StderrPipe()36 output, _ := cmd.CombinedOutput()37 stdin.Write([]byte("Hello, how are you?"))38 stdin.Close()39 bytesErr, _ := ioutil.ReadAll(stderr)40 bytesOut, _ := ioutil.ReadAll(stdout)41 fmt.Println(string(bytesErr))42 fmt.Println(string(bytesOut))43 fmt.Println(string(output))44}45import (46func main() {47 cmd := exec.Command("ping", "google.com")48 stdin, _ := cmd.StdinPipe()49 stdout, _ := cmd.StdoutPipe()50 stderr, _ := cmd.StderrPipe()51 output, _ := cmd.Output()52 stdin.Write([]byte("Hello, how are you?"))53 stdin.Close()54 bytesErr, _ := ioutil.ReadAll(stderr)55 bytesOut, _ := ioutil.ReadAll(stdout)56 fmt.Println(string(bytesErr))57 fmt.Println(string(bytesOut))

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ls", "-l")4 err := cmd.Run()5 if err != nil {6 fmt.Println(err)7 }8}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import "os/exec"2func main(){3 cmd := exec.Command("echo", "Hello World!")4 cmd.Run()5}6import "os/exec"7func main(){8 cmd := exec.Command("echo", "Hello World!")9 output, _ := cmd.Output()10 fmt.Println(string(output))11}12import "os/exec"13func main(){14 cmd := exec.Command("echo", "Hello World!")15 output, _ := cmd.CombinedOutput()16 fmt.Println(string(output))17}18import "os/exec"19func main(){20 cmd := exec.Command("echo", "Hello World!")21 cmd.Start()22}23import "os/exec"24func main(){25 cmd := exec.Command("echo", "Hello World!")26 cmd.Start()27 cmd.Wait()28}29import "os/exec"30func main(){31 cmd := exec.Command("echo", "Hello World!")32 stdout, _ := cmd.StdoutPipe()33 cmd.Start()34 output, _ := ioutil.ReadAll(stdout)35 fmt.Println(string(output))36}37import "os/exec"38func main(){39 cmd := exec.Command("echo", "Hello World!")40 stderr, _ := cmd.StderrPipe()41 cmd.Start()42 output, _ := ioutil.ReadAll(stderr)43 fmt.Println(string(output))44}45import "os/exec"46func main(){47 cmd := exec.Command("echo", "Hello World!")48 stdin, _ := cmd.StdinPipe()49 cmd.Start()50 stdin.Write([]byte("Hello World!"))51 stdin.Close()52}53import "os/exec"

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("bash", "-c", "echo \"Hello\"")4 stdin, err := cmd.StdinPipe()5 if err != nil {6 fmt.Println(err)7 }8 defer stdin.Close()9 scanner := bufio.NewScanner(stdin)10 cmd.Start()11 for scanner.Scan() {12 fmt.Println(scanner.Text())13 }14 cmd.Wait()15}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ls", "-l")4 out, err := cmd.Output()5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(out))9}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1func main() {2 file, err := os.Create("test.txt")3 if err != nil {4 fmt.Println(err)5 }6 defer file.Close()7 fmt.Fprintln(file, "Hello, World!")8}9func main() {10 file, err := os.Create("test.txt")11 if err != nil {12 fmt.Println(err)13 }14 defer file.Close()15 fmt.Fprintln(file, "Hello, World!")16 file, err = os.Create("test2.txt")17 if err != nil {18 fmt.Println(err)19 }20 defer file.Close()21 fmt.Fprintln(file, "Hello, World!")22}23func main() {24 file, err := os.Create("test.txt")25 if err != nil {26 fmt.Println(err)27 }28 defer file.Close()29 fmt.Fprintln(file, "Hello, World!")30 file, err = os.Create("test2.txt")31 if err != nil {32 fmt.Println(err)33 }34 defer file.Close()35 fmt.Fprintln(file, "Hello, World!")36 file, err = os.Create("test3.txt")37 if err != nil {38 fmt.Println(err)39 }40 defer file.Close()41 fmt.Fprintln(file, "Hello, World!")42}43func main() {

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("cat")4 pipe, _ := cmd.StdinPipe()5 pipe.Write([]byte("Hello world!"))6 pipe.Close()7 cmd.Run()8}9import (10func main() {11 cmd := exec.Command("cat")12 pipe, _ := cmd.StdoutPipe()13 cmd.Start()14 output := make([]byte, 100)15 pipe.Read(output)16 pipe.Close()17 cmd.Wait()18 fmt.Println(string(output))19}20import (21func main() {22 cmd := exec.Command("cat")23 pipe, _ := cmd.StdoutPipe()24 cmd.Start()25 output := make([]byte, 100)26 io.Copy(pipe, output)27 pipe.Close()28 cmd.Wait()29 fmt.Println(string(output))30}31import (32func main() {33 cmd := exec.Command("cat")34 pipe, _ := cmd.StdoutPipe()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful