From 73395bce44f6560e2c6b5c3b453592d17c14cb54 Mon Sep 17 00:00:00 2001 From: Bartek Kryza Date: Tue, 7 Feb 2017 16:15:05 +0100 Subject: [PATCH] [Bash] Bash generator improvements (#4730) * Removed trailing spaces * Fixed autocomplete support for bash-completion < 1.4 * Added mime type autocomplete for Zsh * Fixed Bash url autocompletion * Fixed Zsh space after operation arguments and added trim to descriptions * Added generation of Dockerfile for packaging Bash rest clients * updated test samples for Bash client generator --- .../codegen/languages/BashClientCodegen.java | 61 +++---- .../main/resources/bash/Dockerfile.mustache | 69 ++++++++ .../src/main/resources/bash/README.md | 4 +- .../src/main/resources/bash/README.mustache | 19 ++- .../resources/bash/bash-completion.mustache | 81 +++++----- .../src/main/resources/bash/client.mustache | 69 ++++---- .../resources/bash/zsh-completion.mustache | 73 ++++++--- samples/client/petstore/bash/README.md | 19 ++- samples/client/petstore/bash/_petstore-cli | 149 +++++++++++------- samples/client/petstore/bash/petstore-cli | 107 +++++++------ .../bash/petstore-cli.bash-completion | 79 +++++----- 11 files changed, 456 insertions(+), 274 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/bash/Dockerfile.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java index 9e082c3b8300..49cd83528662 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java @@ -64,7 +64,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { } /** - * Configures a friendly name for the generator. This will be used by + * Configures a friendly name for the generator. This will be used by * the generator to select the library with the -l flag. * * @return the friendly name for the generator @@ -74,9 +74,9 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { } /** - * Returns human-friendly help for the generator. Provide the consumer with + * Returns human-friendly help for the generator. Provide the consumer with * help tips, parameters here - * + * * @return A string value for the help message */ public String getHelp() { @@ -128,7 +128,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { "(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')")); cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, "Name of environment variable where username and password " - + + + "can be defined (e.g. PETSTORE_CREDS='username:password')")); cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, "Name of environment variable where API key " @@ -206,7 +206,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { Boolean.parseBoolean( additionalProperties.get(PROCESS_MARKDOWN).toString())); } - + if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) { setGenerateBashCompletion( Boolean.parseBoolean( @@ -225,7 +225,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("x-codegen-script-name", scriptName); if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) { - setHostEnvironmentVariable( + setHostEnvironmentVariable( additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME).toString()); additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable); } @@ -237,11 +237,11 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { } if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) { - setApiKeyAuthEnvironmentVariable( + setApiKeyAuthEnvironmentVariable( additionalProperties.get(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable); } - + supportingFiles.add(new SupportingFile( "client.mustache", "", scriptName)); supportingFiles.add(new SupportingFile( @@ -250,6 +250,8 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { "zsh-completion.mustache", "", "_"+scriptName)); supportingFiles.add(new SupportingFile( "README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile( + "Dockerfile.mustache", "", "Dockerfile")); } public void setCurlOptions(String curlOptions) { @@ -263,11 +265,11 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { public void setScriptName(String scriptName) { this.scriptName = scriptName; } - + public void setGenerateBashCompletion(boolean generateBashCompletion) { this.generateBashCompletion = generateBashCompletion; } - + public void setGenerateZshCompletion(boolean generateZshCompletion) { this.generateZshCompletion = generateZshCompletion; } @@ -275,13 +277,13 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { public void setHostEnvironmentVariable(String hostEnvironmentVariable) { this.hostEnvironmentVariable = hostEnvironmentVariable; } - - public void setBasicAuthEnvironmentVariable(String + + public void setBasicAuthEnvironmentVariable(String basicAuthEnvironmentVariable) { this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable; } - public void setApiKeyAuthEnvironmentVariable(String + public void setApiKeyAuthEnvironmentVariable(String apiKeyAuthEnvironmentVariable) { this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable; } @@ -300,7 +302,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { } /** - * Location to write model files. You can use the modelPackage() as defined + * Location to write model files. You can use the modelPackage() as defined * when the class is instantiated. */ public String modelFileFolder() { @@ -308,7 +310,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { } /** - * Location to write api files. You can use the apiPackage() as defined when + * Location to write api files. You can use the apiPackage() as defined when * the class is instantiated. */ @Override @@ -402,10 +404,10 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { p.vendorExtensions.put("x-codegen-collection-min-items", sparam.getMinItems()); } - - if( (collectionFormat.equals("multi")) + + if( (collectionFormat.equals("multi")) && (param.getIn().equals("query")) ) { - + /** * 'multi' is only supported for query parameters */ @@ -445,15 +447,20 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { return input; } + /** + * Trim the input text always. + */ + String result = input.trim(); + /** * remove standalone '\' * * replace " with \" * outter unescape to retain the original multi-byte characters */ - String result = escapeUnsafeCharacters( + result = escapeUnsafeCharacters( StringEscapeUtils.unescapeJava( - StringEscapeUtils.escapeJava(input).replace("\\/", "/")) + StringEscapeUtils.escapeJava(result).replace("\\/", "/")) .replace("\\", "\\\\") .replace("\"", "\\\"")); @@ -481,28 +488,28 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { /** * Convert all markdown section 1 level headers with bold - */ + */ result = result.replaceAll("(?m)^\\#\\s+(.+)$", "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" +"$1\\$\\(tput sgr0\\)"); /** * Convert all markdown section 2 level headers with bold - */ + */ result = result.replaceAll("(?m)^\\#\\#\\s+(.+)$", "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" +"$1\\$\\(tput sgr0\\)"); /** * Convert all markdown section 3 level headers with bold - */ + */ result = result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$", "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" +"$1\\$\\(tput sgr0\\)"); /** * Convert all markdown code blocks into --- delimited sections - */ + */ result = result.replaceAll("(?m)\\s*```.*$", "\n---"); @@ -555,7 +562,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { * for help */ if(op.vendorExtensions.containsKey("x-bash-codegen-description")) { - String bash_description + String bash_description = (String)op.vendorExtensions.get("x-bash-codegen-description"); op.vendorExtensions.put("x-bash-codegen-description", @@ -633,7 +640,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { swagger.setBasePath(""); } - if(swagger.getInfo() != null + if(swagger.getInfo() != null && swagger.getInfo().getVendorExtensions()!=null) { String bash_codegen_app_description = (String)swagger.getInfo().getVendorExtensions() @@ -641,7 +648,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { if(bash_codegen_app_description != null) { - bash_codegen_app_description + bash_codegen_app_description = escapeText(bash_codegen_app_description); additionalProperties.put("x-bash-codegen-app-description", diff --git a/modules/swagger-codegen/src/main/resources/bash/Dockerfile.mustache b/modules/swagger-codegen/src/main/resources/bash/Dockerfile.mustache new file mode 100644 index 000000000000..9af7d224f6f4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/Dockerfile.mustache @@ -0,0 +1,69 @@ +FROM ubuntu:16.10 + +RUN apt-get update -y && apt-get full-upgrade -y +RUN apt-get install -y bash-completion zsh curl cowsay git vim bsdmainutils + +ADD {{scriptName}} /usr/bin/{{scriptName}} +ADD _{{scriptName}} /usr/local/share/zsh/site-functions/_{{scriptName}} +ADD {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}} + + +# +# Install oh-my-zsh +# +RUN sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" || true + +# +# Enable bash completion +# +RUN echo '\n\ +. /etc/bash_completion\n\ +source /etc/bash-completion.d/{{scriptName}}\n\ +' >> ~/.bashrc + +# +# Setup prompt +# +RUN echo 'export PS1="[{{appName}}] \$ "' >> ~/.bashrc +RUN echo 'export PROMPT="[{{appName}}] \$ "' >> ~/.zshrc + +# +# Setup a welcome message with basic instruction +# +RUN echo 'cat << EOF\n\ +\n\ +This Docker provides preconfigured environment for running the command\n\ +line REST client for $(tput setaf 6){{appName}}$(tput sgr0).\n\ +\n\ +For convenience, you can export the following environment variables:\n\ +\n\ +{{#x-codegen-host-env}}$(tput setaf 3){{x-codegen-host-env}}$(tput sgr0) - server URL, e.g. https://example.com:8080\n\{{/x-codegen-host-env}} +{{#hasAuthMethods}} +{{#authMethods}} +{{#isBasic}} +{{#x-codegen-basicauth-env}}$(tput setaf 3){{x-codegen-basicauth-env}}$(tput sgr0) - basic authentication credentials, e.g.: "username:password"\n\{{/x-codegen-basicauth-env}} +{{/isBasic}} +{{#isApiKey}} +{{#x-codegen-apikey-env}}$(tput setaf 3){{x-codegen-apikey-env}}$(tput sgr0) - access token, e.g. "ASDASHJDG63456asdASSD"\n\{{/x-codegen-apikey-env}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} +\n\ +$(tput setaf 7)Basic usage:$(tput sgr0)\n\ +\n\ +$(tput setaf 3)Print the list of operations available on the service$(tput sgr0)\n\ +$ {{scriptName}} -h\n\ +\n\ +$(tput setaf 3)Print the service description$(tput sgr0)\n\ +$ {{scriptName}} --about\n\ +\n\ +$(tput setaf 3)Print detailed information about specific operation$(tput sgr0)\n\ +$ {{scriptName}} -h\n\ +\n\ +By default you are logged into Zsh with full autocompletion for your REST API,\n\ +but you can switch to Bash, where basic autocompletion is also supported.\n\ +\n\ +EOF\n\ +' | tee -a ~/.bashrc ~/.zshrc + +ENTRYPOINT ["zsh"] diff --git a/modules/swagger-codegen/src/main/resources/bash/README.md b/modules/swagger-codegen/src/main/resources/bash/README.md index 9528032e8faf..da35f04ae675 100644 --- a/modules/swagger-codegen/src/main/resources/bash/README.md +++ b/modules/swagger-codegen/src/main/resources/bash/README.md @@ -1,7 +1,7 @@ # Bash script generator for Swagger Codegen ## Overview -This is a Bash client script codegen. +This is a Bash client script codegen. The codegen creates a standalone, single-file Bash script client to quickly test and access Swagger annotated REST services. The generated script uses underneath [cURL](https://curl.haxx.se) to make actual REST calls. @@ -204,7 +204,7 @@ and add the following to the `~/.bashrc`: if [ -f $(brew --prefix)/etc/bash_completion ]; then . $(brew --prefix)/etc/bash_completion fi -``` +``` ### Zsh In Zsh, the generated `_{{scriptName}}` file (e.g. _petstore-cli) must be copied to one of the folders under `$fpath` variable. diff --git a/modules/swagger-codegen/src/main/resources/bash/README.mustache b/modules/swagger-codegen/src/main/resources/bash/README.mustache index d60bb0f201d2..bbb85fb225be 100644 --- a/modules/swagger-codegen/src/main/resources/bash/README.mustache +++ b/modules/swagger-codegen/src/main/resources/bash/README.mustache @@ -20,7 +20,7 @@ $ ./{{scriptName}} --about # Print detailed information about specific operation $ ./{{scriptName}} -h -# Make GET request +# Make GET request ./{{scriptName}} --host http://: --accept xml = : # Make GET request using arbitrary curl options (must be passed before ) to an SSL service using username:password @@ -42,6 +42,20 @@ $ {{scriptName}} --host http://: --dry-run ``` +## Docker image +You can easily create a Docker image containing a preconfigured environment +for using the REST Bash client including working autocompletion and short +welcome message with basic instructions, using the generated Dockerfile: + +```shell +docker build -t my-rest-client . +docker run -it my-rest-client +``` + +By default you will be logged into a Zsh environment which has much more +advanced auto completion, but you can switch to Bash, where basic autocompletion +is also available. + ## Shell completion ### Bash @@ -68,8 +82,7 @@ and add the following to the `~/.bashrc`: if [ -f $(brew --prefix)/etc/bash_completion ]; then . $(brew --prefix)/etc/bash_completion fi -``` +``` ### Zsh In Zsh, the generated `_{{scriptName}}` Zsh completion file must be copied to one of the folders under `$FPATH` variable. - diff --git a/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache b/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache index c184a82456d3..83b907259ad2 100644 --- a/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache +++ b/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache @@ -4,17 +4,17 @@ # ! # ! Note: # ! -# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING -# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) # ! FROM SWAGGER SPECIFICATION IN JSON. # ! # ! Generated on: {{generatedDate}} -# ! +# ! # ! # ! System wide installation: # ! # ! $ sudo cp {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}} -# ! +# ! # ! # ! User home installation (add this line to .bash_profile): # ! @@ -45,13 +45,16 @@ mime_type_abbreviations["bmp"]="image/bmp" mime_type_abbreviations["tiff"]="image/tiff" - -__osx_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref cur prev words cword -} - +# +# Check if this is OSX, if so defined custom init_completion +# +if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion() + { + COMPREPLY=() + _get_comp_words_by_ref cur prev words cword + } +fi _{{scriptName}}() { @@ -60,11 +63,6 @@ _{{scriptName}}() local words local cword - #words="${COMP_WORDS}" - #cword="${COMP_CWORD}" - #prev="${COMP_WORDS[COMP_CWORD-1]}" - #cur="${COMP_WORDS[COMP_CWORD]}" - # The reference of currently selected REST operation local operation="" @@ -92,8 +90,8 @@ _{{scriptName}}() {{/operation}} {{/operations}} {{/apis}} -{{/apiInfo}} - +{{/apiInfo}} + # An associative array of possible values for enum parameters declare -A operation_parameters_enum_values {{#apiInfo}} @@ -123,16 +121,15 @@ _{{scriptName}}() {{/operation}} {{/operations}} {{/apis}} -{{/apiInfo}} +{{/apiInfo}} # - # Check if the _init_completion function is available, which is - # available since bash-completion 1.4 + # Check if this is OSX and use special __osx_init_completion function # - if declare -F _init_completions >/dev/null 2>&1; then - _init_completion -s || return - else + if [[ `uname` =~ "Darwin" ]]; then __osx_init_completion || return + else + _init_completion -s || return fi @@ -235,23 +232,26 @@ _{{scriptName}}() fi # - # Complete the server address based on ~/.ssh/known_hosts + # Complete the server address based on ~/.ssh/known_hosts # and ~/.ssh/config # - # \todo Fix - cur matches only '//' when $prev is ':' - # - if [[ "$cur" == "http://" || "$cur" == "https://" ]]; then + local prefix=${COMP_WORDS[COMP_CWORD-2]} + local colon=${COMP_WORDS[COMP_CWORD-1]} + if [[ "$colon" == ":" && ( $prefix == "https" || $prefix == "http" ) ]]; then COMPREPLY=() - local comp_ssh_hosts=`cat ~/.ssh/known_hosts | \ - cut -f 1 -d ' ' | \ - sed -e s/,.*//g | \ - grep -v ^# | \ - uniq | \ - grep -v "\[" ; - cat ~/.ssh/config | \ - grep "^Host " | \ - awk '{print $2}'` - COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur)) + local comp_ssh_hosts=`[[ -f ~/.ssh/known_hosts ]] && \ + ( cat ~/.ssh/known_hosts | \ + grep '^[a-zA-Z0-9]' | \ + cut -f 1 -d ' ' | \ + sed -e s/,.*//g | \ + grep -v ^# | \ + uniq | \ + grep -v "\[" ) ; + [[ -f ~/.ssh/config ]] && \ + ( cat ~/.ssh/config | \ + grep "^Host " | \ + awk '{print $2}' )` + COMPREPLY=( $( compgen -P '//' -W '${comp_ssh_hosts}' -- "${cur:2}") ) return fi @@ -270,12 +270,13 @@ _{{scriptName}}() # if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then # If operation has not been yet selected, suggest the list of operations - # otherwise suggest arguments of this operation as declared in the + # otherwise suggest arguments of this operation as declared in the # Swagger specification if [[ -z $operation ]]; then COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) ) else COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) ) + compopt -o nospace fi return fi @@ -283,4 +284,4 @@ _{{scriptName}}() } && complete -F _{{scriptName}} {{scriptName}} -# ex: ts=4 sw=4 et filetype=sh \ No newline at end of file +# ex: ts=4 sw=4 et filetype=sh diff --git a/modules/swagger-codegen/src/main/resources/bash/client.mustache b/modules/swagger-codegen/src/main/resources/bash/client.mustache index 934fddcbe8c4..e1e3aad1cfd1 100644 --- a/modules/swagger-codegen/src/main/resources/bash/client.mustache +++ b/modules/swagger-codegen/src/main/resources/bash/client.mustache @@ -4,8 +4,8 @@ # ! # ! Note: # ! -# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING -# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) # ! FROM SWAGGER SPECIFICATION IN JSON. # ! # ! Generated on: {{generatedDate}} @@ -13,7 +13,7 @@ # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # -# This is a Bash client for {{appName}}. +# This is a Bash client for {{appName}}. # # LICENSE: # {{licenseUrl}} @@ -41,9 +41,9 @@ if ! ( (("${BASH_VERSION:0:1}" == "4")) && (("${BASH_VERSION:2:1}" >= "3")) ) \ fi ############################################################################### -# +# # Global variables -# +# ############################################################################### ## @@ -116,13 +116,13 @@ operation_parameters_collection_type["{{operationId}}:::{{baseName}}"]={{#isCont ## -# Map for body parameters passed after operation as +# Map for body parameters passed after operation as # PARAMETER==STRING_VALUE or PARAMETER:=NUMERIC_VALUE # These will be mapped to top level json keys ( { "PARAMETER": "VALUE" }) declare -A body_parameters -## -# These arguments will be directly passed to cURL +## +# These arguments will be directly passed to cURL curl_arguments="{{x-codegen-curl-options}}" ## @@ -138,7 +138,7 @@ basic_auth_credential="{{#x-codegen-basicauth-env}}${{x-codegen-basicauth-env}}{ apikey_auth_credential="{{#x-codegen-apikey-env}}${{x-codegen-apikey-env}}{{/x-codegen-apikey-env}}" ## -# If true, the script will only output the actual cURL command that would be +# If true, the script will only output the actual cURL command that would be # used print_curl=false @@ -279,7 +279,7 @@ header_arguments_to_curl() { # # Converts an associative array into a simple JSON with keys as top # level object attributes -# +# # \todo Add convertion of more complex attributes using paths # ############################################################################## @@ -346,7 +346,7 @@ validate_request_parameters() { # Check if the number of provided values is not more than maximum # if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ - && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then if [[ "$force" = false ]]; then echo "Error: Too many values provided for '${qparam}' parameter" exit 1 @@ -465,7 +465,7 @@ build_request_path() { # Check if the number of provided values is not more than maximum # if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ - && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then if [[ "$force" = false ]]; then echo "Error: Too many values provided for '${qparam}' parameter" exit 1 @@ -550,9 +550,9 @@ build_request_path() { if [[ $count -lt $query_parameter_count-1 && -n "${parameter_value}" ]]; then query_request_part+="&" fi - + count+=1 - + done @@ -567,9 +567,9 @@ build_request_path() { ############################################################################### -# +# # Print main help message -# +# ############################################################################### print_help() { cat <$(tput sgr0)] [-ac|--accept $(tput setaf 2)$(tput sgr0)] [-ct,--content-type $(tput setaf 2)$(tput sgr0)] - [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] + [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] - $(tput setaf 6)$(tput sgr0) - endpoint of the REST service without basepath {{#x-codegen-host-env}} Can also be specified in {{x-codegen-host-env}} environment variable.{{/x-codegen-host-env}} - $(tput setaf 1)$(tput sgr0) - any valid cURL options can be passed before $(tput setaf 3)$(tput sgr0) - - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: - (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, rdf, jpg, png, gif, bmp, tiff) - $(tput setaf 4)$(tput sgr0) - HTTP headers can be passed in the form $(tput setaf 3)HEADER$(tput sgr0):$(tput setaf 4)VALUE$(tput sgr0) - - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following + - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following forms: * $(tput setaf 3)KEY$(tput sgr0)=$(tput setaf 4)VALUE$(tput sgr0) - path or query parameters - - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build - using the following arguments: - * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build + using the following arguments: + * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": "$(tput setaf 4)VALUE$(tput sgr0)", ... }' - * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": $(tput setaf 4)VALUE$(tput sgr0), ... }' EOF @@ -607,7 +607,7 @@ EOF {{#authMethods}} {{#isBasic}} echo -e " - $(tput setaf 4)Basic AUTH$(tput sgr0) - add '-u :' before $(tput setaf 3)$(tput sgr0)" - {{#x-codegen-basicauth-env}}echo -e " or export $(tput setaf 1){{x-codegen-basicauth-env}}=':'$(tput sgr0)"{{/x-codegen-basicauth-env}} + {{#x-codegen-basicauth-env}}echo -e " or export $(tput setaf 1){{x-codegen-basicauth-env}}=':'$(tput sgr0)"{{/x-codegen-basicauth-env}} {{/isBasic}} {{#isApiKey}} {{#isKeyInHeader}} @@ -616,7 +616,7 @@ EOF {{#isKeyInQuery}} echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1){{keyParamName}}=$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" {{/isKeyInQuery}} - {{#x-codegen-apikey-env}}echo -e " or export $(tput setaf 1){{x-codegen-apikey-env}}=''$(tput sgr0)"{{/x-codegen-apikey-env}} + {{#x-codegen-apikey-env}}echo -e " or export $(tput setaf 1){{x-codegen-apikey-env}}=''$(tput sgr0)"{{/x-codegen-apikey-env}} {{/isApiKey}} {{#isOAuth}} echo -e " - $(tput setaf 5)OAuth2 (flow: {{flow}})$(tput sgr0)" @@ -834,7 +834,7 @@ call_{{operationId}}() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -908,7 +908,7 @@ call_{{operationId}}() { ############################################################################## # -# Main +# Main # ############################################################################## @@ -920,7 +920,7 @@ type column >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'bsdmainutils' # # Process command line -# +# # Pass all arguemnts before 'operation' to cURL except the ones we override # take_user=false @@ -973,7 +973,7 @@ case $key in ;; -u|--user) take_user=true - ;; + ;; --host) take_host=true ;; @@ -985,10 +985,10 @@ case $key in ;; -ct|--content-type) take_contenttype_header=true - ;; + ;; --dry-run) print_curl=true - ;; + ;; {{#apiInfo}} {{#apis}} {{#operations}} @@ -1001,7 +1001,7 @@ case $key in {{/apis}} {{/apiInfo}} *==*) - # Parse body arguments and convert them into top level + # Parse body arguments and convert them into top level # JSON properties passed in the body content as strings if [[ "$operation" ]]; then IFS='==' read body_key sep body_value <<< "$key" @@ -1009,7 +1009,7 @@ case $key in fi ;; *:=*) - # Parse body arguments and convert them into top level + # Parse body arguments and convert them into top level # JSON properties passed in the body content without qoutes if [[ "$operation" ]]; then IFS=':=' read body_key sep body_value <<< "$key" @@ -1109,4 +1109,3 @@ case $operation in print_help exit 1 esac - diff --git a/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache b/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache index 78caea2bc217..064b9a01fe0b 100644 --- a/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache +++ b/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache @@ -4,11 +4,11 @@ # ! # ! Note: # ! -# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING -# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) # ! FROM SWAGGER SPECIFICATION IN JSON. # ! -# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl +# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl # ! # ! Generated on: {{generatedDate}} # ! @@ -24,6 +24,43 @@ local curcontext="$curcontext" state line ret=1 typeset -A opt_args +typeset -A mime_type_abbreviations +# text/* +mime_type_abbreviations[text]="text/plain" +mime_type_abbreviations[html]="text/html" +mime_type_abbreviations[md]="text/x-markdown" +mime_type_abbreviations[csv]="text/csv" +mime_type_abbreviations[css]="text/css" +mime_type_abbreviations[rtf]="text/rtf" +# application/* +mime_type_abbreviations[json]="application/json" +mime_type_abbreviations[xml]="application/xml" +mime_type_abbreviations[yaml]="application/yaml" +mime_type_abbreviations[js]="application/javascript" +mime_type_abbreviations[bin]="application/octet-stream" +mime_type_abbreviations[rdf]="application/rdf+xml" +# image/* +mime_type_abbreviations[jpg]="image/jpeg" +mime_type_abbreviations[png]="image/png" +mime_type_abbreviations[gif]="image/gif" +mime_type_abbreviations[bmp]="image/bmp" +mime_type_abbreviations[tiff]="image/tiff" + +# +# Generate zsh completion string list for abbreviated mime types +# +get_mime_type_completions() { + typeset -a result + result=() + for k in "${(@k)mime_type_abbreviations}"; do + value=$mime_type_abbreviations[${k}] + #echo $value + result+=( "${k}[${value}]" ) + #echo $result + done + echo "$result" +} + # # cURL crypto engines completion function # @@ -236,21 +273,21 @@ arg_output=(\ ) _arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \ - {-M,--manual}'[print manual]' \ - '*'{-K,--config}'[use other config file to read arguments from]:config file:_files' \ + {-M,--manual}'[Print manual]' \ + '*'{-K,--config}'[Use other config file to read arguments from]:config file:_files' \ '--libcurl[output libcurl code for the operation to file]:output file:_files' \ - {-m,--max-time}'[limit total time of operation]:seconds' \ - {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ - {-S,--show-error}'[show errors in silent mode]' \ - '--stderr[redirect stderr to specified file]:output file:_files' \ - '-q[do not read settings from .curlrc (must be first option)]' \ + {-m,--max-time}'[Limit total time of operation]:seconds' \ + {-s,--silent}'[Silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[Show errors in silent mode]' \ + '--stderr[Redirect stderr to specified file]:output file:_files' \ + '-q[Do not read settings from .curlrc (must be first option)]' \ {-h,--help}'[Print help and list of operations]' \ {-V,--version}'[Print service API version]' \ '--about[Print the information about service]' \ '--host[Specify the host URL]':URL:_urls \ '--dry-run[Print out the cURL command without executing it]' \ - {-ac,--accept}'[Set the 'Accept' header in the request]' \ - {-ct,--content-type}'[Set the 'Content-type' header in request]' \ + {-ac,--accept}'[Set the Accept header in the request]: :{_values "Accept mime type" $(get_mime_type_completions)}' \ + {-ct,--content-type}'[Set the Content-type header in request]: :{_values "Content mime type" $(get_mime_type_completions)}' \ '1: :->ops' \ '*:: :->args' \ && ret=0 @@ -282,12 +319,12 @@ case $state in {{operationId}}) local -a _op_arguments _op_arguments=( - {{#pathParams}}"{{baseName}}=:{{{description}}}" -{{/pathParams}} {{#queryParams}}{{#isBoolean}}"{{baseName}}=true:{{description}}" - "{{baseName}}=false:{{description}}"{{/isBoolean}}{{^isBoolean}}"{{baseName}}=:{{description}}"{{/isBoolean}} -{{/queryParams}} {{#headerParams}}"{{baseName}}\::{{{description}}}" + {{#pathParams}}"{{baseName}}=:[PATH] {{description}}" +{{/pathParams}} {{#queryParams}}{{#isBoolean}}"{{baseName}}=true:[QUERY] {{description}}" + "{{baseName}}=false:[QUERY] {{description}}"{{/isBoolean}}{{^isBoolean}}"{{baseName}}=:[QUERY] {{description}}"{{/isBoolean}} +{{/queryParams}} {{#headerParams}}"{{baseName}}\::[HEADER] {{description}}" {{/headerParams}}) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; {{/operation}} {{/operations}} @@ -298,4 +335,4 @@ case $state in esac -return ret \ No newline at end of file +return ret diff --git a/samples/client/petstore/bash/README.md b/samples/client/petstore/bash/README.md index ba13931cd246..619928a40264 100644 --- a/samples/client/petstore/bash/README.md +++ b/samples/client/petstore/bash/README.md @@ -20,7 +20,7 @@ $ ./petstore-cli --about # Print detailed information about specific operation $ ./petstore-cli -h -# Make GET request +# Make GET request ./petstore-cli --host http://: --accept xml = : # Make GET request using arbitrary curl options (must be passed before ) to an SSL service using username:password @@ -42,6 +42,20 @@ $ petstore-cli --host http://: --dry-run ``` +## Docker image +You can easily create a Docker image containing a preconfigured environment +for using the REST Bash client including working autocompletion and short +welcome message with basic instructions, using the generated Dockerfile: + +```shell +docker build -t my-rest-client . +docker run -it my-rest-client +``` + +By default you will be logged into a Zsh environment which has much more +advanced auto completion, but you can switch to Bash, where basic autocompletion +is also available. + ## Shell completion ### Bash @@ -68,8 +82,7 @@ and add the following to the `~/.bashrc`: if [ -f $(brew --prefix)/etc/bash_completion ]; then . $(brew --prefix)/etc/bash_completion fi -``` +``` ### Zsh In Zsh, the generated `_petstore-cli` Zsh completion file must be copied to one of the folders under `$FPATH` variable. - diff --git a/samples/client/petstore/bash/_petstore-cli b/samples/client/petstore/bash/_petstore-cli index 6ff898e15c6e..a1a2a44dcb9a 100644 --- a/samples/client/petstore/bash/_petstore-cli +++ b/samples/client/petstore/bash/_petstore-cli @@ -4,13 +4,13 @@ # ! # ! Note: # ! -# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING -# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) # ! FROM SWAGGER SPECIFICATION IN JSON. # ! -# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl +# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl # ! -# ! Generated on: 2017-01-12T00:07:27.471+01:00 +# ! Generated on: 2017-02-06T21:48:13.013+01:00 # ! # ! # ! Installation: @@ -24,6 +24,43 @@ local curcontext="$curcontext" state line ret=1 typeset -A opt_args +typeset -A mime_type_abbreviations +# text/* +mime_type_abbreviations[text]="text/plain" +mime_type_abbreviations[html]="text/html" +mime_type_abbreviations[md]="text/x-markdown" +mime_type_abbreviations[csv]="text/csv" +mime_type_abbreviations[css]="text/css" +mime_type_abbreviations[rtf]="text/rtf" +# application/* +mime_type_abbreviations[json]="application/json" +mime_type_abbreviations[xml]="application/xml" +mime_type_abbreviations[yaml]="application/yaml" +mime_type_abbreviations[js]="application/javascript" +mime_type_abbreviations[bin]="application/octet-stream" +mime_type_abbreviations[rdf]="application/rdf+xml" +# image/* +mime_type_abbreviations[jpg]="image/jpeg" +mime_type_abbreviations[png]="image/png" +mime_type_abbreviations[gif]="image/gif" +mime_type_abbreviations[bmp]="image/bmp" +mime_type_abbreviations[tiff]="image/tiff" + +# +# Generate zsh completion string list for abbreviated mime types +# +get_mime_type_completions() { + typeset -a result + result=() + for k in "${(@k)mime_type_abbreviations}"; do + value=$mime_type_abbreviations[${k}] + #echo $value + result+=( "${k}[${value}]" ) + #echo $result + done + echo "$result" +} + # # cURL crypto engines completion function # @@ -236,21 +273,21 @@ arg_output=(\ ) _arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \ - {-M,--manual}'[print manual]' \ - '*'{-K,--config}'[use other config file to read arguments from]:config file:_files' \ + {-M,--manual}'[Print manual]' \ + '*'{-K,--config}'[Use other config file to read arguments from]:config file:_files' \ '--libcurl[output libcurl code for the operation to file]:output file:_files' \ - {-m,--max-time}'[limit total time of operation]:seconds' \ - {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ - {-S,--show-error}'[show errors in silent mode]' \ - '--stderr[redirect stderr to specified file]:output file:_files' \ - '-q[do not read settings from .curlrc (must be first option)]' \ + {-m,--max-time}'[Limit total time of operation]:seconds' \ + {-s,--silent}'[Silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[Show errors in silent mode]' \ + '--stderr[Redirect stderr to specified file]:output file:_files' \ + '-q[Do not read settings from .curlrc (must be first option)]' \ {-h,--help}'[Print help and list of operations]' \ {-V,--version}'[Print service API version]' \ '--about[Print the information about service]' \ '--host[Specify the host URL]':URL:_urls \ '--dry-run[Print out the cURL command without executing it]' \ - {-ac,--accept}'[Set the 'Accept' header in the request]' \ - {-ct,--content-type}'[Set the 'Content-type' header in request]' \ + {-ac,--accept}'[Set the Accept header in the request]: :{_values "Accept mime type" $(get_mime_type_completions)}' \ + {-ct,--content-type}'[Set the Content-type header in request]: :{_values "Content mime type" $(get_mime_type_completions)}' \ '1: :->ops' \ '*:: :->args' \ && ret=0 @@ -293,162 +330,162 @@ case $state in local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; testEndpointParameters) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; testEnumParameters) local -a _op_arguments _op_arguments=( - "enum_query_string_array=:Query parameter enum test (string array)" -"enum_query_string=:Query parameter enum test (string)" -"enum_query_integer=:Query parameter enum test (double)" - "enum_header_string_array\::Header parameter enum test (string array)" -"enum_header_string\::Header parameter enum test (string)" + "enum_query_string_array=:[QUERY] Query parameter enum test (string array)" +"enum_query_string=:[QUERY] Query parameter enum test (string)" +"enum_query_integer=:[QUERY] Query parameter enum test (double)" + "enum_header_string_array\::[HEADER] Header parameter enum test (string array)" +"enum_header_string\::[HEADER] Header parameter enum test (string)" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; addPet) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; deletePet) local -a _op_arguments _op_arguments=( - "petId=:Pet id to delete" - "api_key\::" + "petId=:[PATH] Pet id to delete" + "api_key\::[HEADER] " ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; findPetsByStatus) local -a _op_arguments _op_arguments=( - "status=:Status values that need to be considered for filter" + "status=:[QUERY] Status values that need to be considered for filter" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; findPetsByTags) local -a _op_arguments _op_arguments=( - "tags=:Tags to filter by" + "tags=:[QUERY] Tags to filter by" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; getPetById) local -a _op_arguments _op_arguments=( - "petId=:ID of pet to return" + "petId=:[PATH] ID of pet to return" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; updatePet) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; updatePetWithForm) local -a _op_arguments _op_arguments=( - "petId=:ID of pet that needs to be updated" + "petId=:[PATH] ID of pet that needs to be updated" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; uploadFile) local -a _op_arguments _op_arguments=( - "petId=:ID of pet to update" + "petId=:[PATH] ID of pet to update" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; deleteOrder) local -a _op_arguments _op_arguments=( - "orderId=:ID of the order that needs to be deleted" + "orderId=:[PATH] ID of the order that needs to be deleted" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; getInventory) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; getOrderById) local -a _op_arguments _op_arguments=( - "orderId=:ID of pet that needs to be fetched" + "orderId=:[PATH] ID of pet that needs to be fetched" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; placeOrder) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; createUser) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; createUsersWithArrayInput) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; createUsersWithListInput) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; deleteUser) local -a _op_arguments _op_arguments=( - "username=:The name that needs to be deleted" + "username=:[PATH] The name that needs to be deleted" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; getUserByName) local -a _op_arguments _op_arguments=( - "username=:The name that needs to be fetched. Use user1 for testing." + "username=:[PATH] The name that needs to be fetched. Use user1 for testing." ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; loginUser) local -a _op_arguments _op_arguments=( - "username=:The user name for login" -"password=:The password for login in clear text" + "username=:[QUERY] The user name for login" +"password=:[QUERY] The password for login in clear text" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; logoutUser) local -a _op_arguments _op_arguments=( ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; updateUser) local -a _op_arguments _op_arguments=( - "username=:name that need to be deleted" + "username=:[PATH] name that need to be deleted" ) - _describe -t actions 'operations' _op_arguments && ret=0 + _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; esac ;; esac -return ret \ No newline at end of file +return ret diff --git a/samples/client/petstore/bash/petstore-cli b/samples/client/petstore/bash/petstore-cli index cff2a4cf5f8c..6b3270270ce5 100755 --- a/samples/client/petstore/bash/petstore-cli +++ b/samples/client/petstore/bash/petstore-cli @@ -4,16 +4,16 @@ # ! # ! Note: # ! -# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING -# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) # ! FROM SWAGGER SPECIFICATION IN JSON. # ! -# ! Generated on: 2017-01-12T00:07:27.471+01:00 +# ! Generated on: 2017-02-06T21:48:13.013+01:00 # ! # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # -# This is a Bash client for Swagger Petstore. +# This is a Bash client for Swagger Petstore. # # LICENSE: # http://www.apache.org/licenses/LICENSE-2.0.html @@ -25,11 +25,25 @@ # http://swagger.io # +############################################################################### +# +# Make sure Bash is at least in version 4.3 +# +############################################################################### +if ! ( (("${BASH_VERSION:0:1}" == "4")) && (("${BASH_VERSION:2:1}" >= "3")) ) \ + && ! (("${BASH_VERSION:0:1}" >= "5")); then + echo "" + echo "Sorry - your Bash version is ${BASH_VERSION}" + echo "" + echo "You need at least Bash 4.3 to run this script." + echo "" + exit 1 +fi ############################################################################### -# +# # Global variables -# +# ############################################################################### ## @@ -213,13 +227,13 @@ operation_parameters_collection_type["updateUser:::body"]="" ## -# Map for body parameters passed after operation as +# Map for body parameters passed after operation as # PARAMETER==STRING_VALUE or PARAMETER:=NUMERIC_VALUE # These will be mapped to top level json keys ( { "PARAMETER": "VALUE" }) declare -A body_parameters -## -# These arguments will be directly passed to cURL +## +# These arguments will be directly passed to cURL curl_arguments="" ## @@ -235,7 +249,7 @@ basic_auth_credential="$PETSTORE_BASIC_AUTH" apikey_auth_credential="$PETSTORE_API_KEY" ## -# If true, the script will only output the actual cURL command that would be +# If true, the script will only output the actual cURL command that would be # used print_curl=false @@ -360,7 +374,7 @@ header_arguments_to_curl() { # # Converts an associative array into a simple JSON with keys as top # level object attributes -# +# # \todo Add convertion of more complex attributes using paths # ############################################################################## @@ -427,7 +441,7 @@ validate_request_parameters() { # Check if the number of provided values is not more than maximum # if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ - && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then if [[ "$force" = false ]]; then echo "Error: Too many values provided for '${qparam}' parameter" exit 1 @@ -546,7 +560,7 @@ build_request_path() { # Check if the number of provided values is not more than maximum # if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ - && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then if [[ "$force" = false ]]; then echo "Error: Too many values provided for '${qparam}' parameter" exit 1 @@ -631,9 +645,9 @@ build_request_path() { if [[ $count -lt $query_parameter_count-1 && -n "${parameter_value}" ]]; then query_request_part+="&" fi - + count+=1 - + done @@ -648,9 +662,9 @@ build_request_path() { ############################################################################### -# +# # Print main help message -# +# ############################################################################### print_help() { cat <$(tput sgr0)] [-ac|--accept $(tput setaf 2)$(tput sgr0)] [-ct,--content-type $(tput setaf 2)$(tput sgr0)] - [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] + [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] - $(tput setaf 6)$(tput sgr0) - endpoint of the REST service without basepath Can also be specified in PETSTORE_HOST environment variable. - $(tput setaf 1)$(tput sgr0) - any valid cURL options can be passed before $(tput setaf 3)$(tput sgr0) - - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: - (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, rdf, jpg, png, gif, bmp, tiff) - $(tput setaf 4)$(tput sgr0) - HTTP headers can be passed in the form $(tput setaf 3)HEADER$(tput sgr0):$(tput setaf 4)VALUE$(tput sgr0) - - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following + - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following forms: * $(tput setaf 3)KEY$(tput sgr0)=$(tput setaf 4)VALUE$(tput sgr0) - path or query parameters - - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build - using the following arguments: - * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build + using the following arguments: + * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": "$(tput setaf 4)VALUE$(tput sgr0)", ... }' - * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": $(tput setaf 4)VALUE$(tput sgr0), ... }' EOF echo -e "$(tput bold)$(tput setaf 7)Authentication methods$(tput sgr0)" echo -e "" echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1)api_key:$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" - echo -e " or export $(tput setaf 1)PETSTORE_API_KEY=''$(tput sgr0)" + echo -e " or export $(tput setaf 1)PETSTORE_API_KEY=''$(tput sgr0)" echo -e " - $(tput setaf 4)Basic AUTH$(tput sgr0) - add '-u :' before $(tput setaf 3)$(tput sgr0)" - echo -e " or export $(tput setaf 1)PETSTORE_BASIC_AUTH=':'$(tput sgr0)" + echo -e " or export $(tput setaf 1)PETSTORE_BASIC_AUTH=':'$(tput sgr0)" echo -e " - $(tput setaf 5)OAuth2 (flow: implicit)$(tput sgr0)" echo -e " Authorization URL: " echo -e " * http://petstore.swagger.io/api/oauth/dialog" @@ -2015,7 +2029,7 @@ call_testClientModel() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2150,7 +2164,7 @@ call_addPet() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2345,7 +2359,7 @@ call_updatePet() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2571,7 +2585,7 @@ call_placeOrder() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2635,7 +2649,7 @@ call_createUser() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2699,7 +2713,7 @@ call_createUsersWithArrayInput() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2763,7 +2777,7 @@ call_createUsersWithListInput() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2951,7 +2965,7 @@ call_updateUser() { local body_json_curl="" # - # Check if the user provided 'Content-type' headers in the + # Check if the user provided 'Content-type' headers in the # command line. If not try to set them based on the Swagger specification # if values produces and consumes are defined unambigously # @@ -2992,19 +3006,11 @@ call_updateUser() { ############################################################################## # -# Main +# Main # ############################################################################## -# Make sure Bash is at least in version 4.3 -if [[ ${BASH_VERSION:0:1} < 4 && ${BASH_VERSION:2:1} < 3 ]]; then - echo "Sorry - your Bash version is ${BASH_VERSION}" - echo "" - echo "You need at least Bash 4.3 to run this script." - exit 1 -fi - # Check dependencies type curl >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'cURL' installed."; exit 1; } type sed >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'sed' installed."; exit 1; } @@ -3012,7 +3018,7 @@ type column >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'bsdmainutils' # # Process command line -# +# # Pass all arguemnts before 'operation' to cURL except the ones we override # take_user=false @@ -3065,7 +3071,7 @@ case $key in ;; -u|--user) take_user=true - ;; + ;; --host) take_host=true ;; @@ -3077,10 +3083,10 @@ case $key in ;; -ct|--content-type) take_contenttype_header=true - ;; + ;; --dry-run) print_curl=true - ;; + ;; testClientModel) operation="testClientModel" ;; @@ -3151,7 +3157,7 @@ case $key in operation="updateUser" ;; *==*) - # Parse body arguments and convert them into top level + # Parse body arguments and convert them into top level # JSON properties passed in the body content as strings if [[ "$operation" ]]; then IFS='==' read body_key sep body_value <<< "$key" @@ -3159,7 +3165,7 @@ case $key in fi ;; *:=*) - # Parse body arguments and convert them into top level + # Parse body arguments and convert them into top level # JSON properties passed in the body content without qoutes if [[ "$operation" ]]; then IFS=':=' read body_key sep body_value <<< "$key" @@ -3309,4 +3315,3 @@ case $operation in print_help exit 1 esac - diff --git a/samples/client/petstore/bash/petstore-cli.bash-completion b/samples/client/petstore/bash/petstore-cli.bash-completion index cdb743c60b21..f8b11cde5b26 100644 --- a/samples/client/petstore/bash/petstore-cli.bash-completion +++ b/samples/client/petstore/bash/petstore-cli.bash-completion @@ -4,17 +4,17 @@ # ! # ! Note: # ! -# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING -# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) # ! FROM SWAGGER SPECIFICATION IN JSON. # ! -# ! Generated on: 2017-01-12T00:07:27.471+01:00 -# ! +# ! Generated on: 2017-02-06T21:48:13.013+01:00 +# ! # ! # ! System wide installation: # ! # ! $ sudo cp petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli -# ! +# ! # ! # ! User home installation (add this line to .bash_profile): # ! @@ -45,13 +45,16 @@ mime_type_abbreviations["bmp"]="image/bmp" mime_type_abbreviations["tiff"]="image/tiff" - -__osx_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref cur prev words cword -} - +# +# Check if this is OSX, if so defined custom init_completion +# +if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion() + { + COMPREPLY=() + _get_comp_words_by_ref cur prev words cword + } +fi _petstore-cli() { @@ -60,11 +63,6 @@ _petstore-cli() local words local cword - #words="${COMP_WORDS}" - #cword="${COMP_CWORD}" - #prev="${COMP_WORDS[COMP_CWORD-1]}" - #cur="${COMP_WORDS[COMP_CWORD]}" - # The reference of currently selected REST operation local operation="" @@ -121,18 +119,17 @@ _petstore-cli() operation_parameters["loginUser"]="username= password= " operation_parameters["logoutUser"]="" operation_parameters["updateUser"]="username= " - + # An associative array of possible values for enum parameters declare -A operation_parameters_enum_values # - # Check if the _init_completion function is available, which is - # available since bash-completion 1.4 + # Check if this is OSX and use special __osx_init_completion function # - if declare -F _init_completions >/dev/null 2>&1; then - _init_completion -s || return - else + if [[ `uname` =~ "Darwin" ]]; then __osx_init_completion || return + else + _init_completion -s || return fi @@ -235,23 +232,26 @@ _petstore-cli() fi # - # Complete the server address based on ~/.ssh/known_hosts + # Complete the server address based on ~/.ssh/known_hosts # and ~/.ssh/config # - # \todo Fix - cur matches only '//' when $prev is ':' - # - if [[ "$cur" == "http://" || "$cur" == "https://" ]]; then + local prefix=${COMP_WORDS[COMP_CWORD-2]} + local colon=${COMP_WORDS[COMP_CWORD-1]} + if [[ "$colon" == ":" && ( $prefix == "https" || $prefix == "http" ) ]]; then COMPREPLY=() - local comp_ssh_hosts=`cat ~/.ssh/known_hosts | \ - cut -f 1 -d ' ' | \ - sed -e s/,.*//g | \ - grep -v ^# | \ - uniq | \ - grep -v "\[" ; - cat ~/.ssh/config | \ - grep "^Host " | \ - awk '{print $2}'` - COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur)) + local comp_ssh_hosts=`[[ -f ~/.ssh/known_hosts ]] && \ + ( cat ~/.ssh/known_hosts | \ + grep '^[a-zA-Z0-9]' | \ + cut -f 1 -d ' ' | \ + sed -e s/,.*//g | \ + grep -v ^# | \ + uniq | \ + grep -v "\[" ) ; + [[ -f ~/.ssh/config ]] && \ + ( cat ~/.ssh/config | \ + grep "^Host " | \ + awk '{print $2}' )` + COMPREPLY=( $( compgen -P '//' -W '${comp_ssh_hosts}' -- "${cur:2}") ) return fi @@ -270,12 +270,13 @@ _petstore-cli() # if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then # If operation has not been yet selected, suggest the list of operations - # otherwise suggest arguments of this operation as declared in the + # otherwise suggest arguments of this operation as declared in the # Swagger specification if [[ -z $operation ]]; then COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) ) else COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) ) + compopt -o nospace fi return fi @@ -283,4 +284,4 @@ _petstore-cli() } && complete -F _petstore-cli petstore-cli -# ex: ts=4 sw=4 et filetype=sh \ No newline at end of file +# ex: ts=4 sw=4 et filetype=sh