Skip to content

Commit

Permalink
Merge pull request #7 from menuka94/master
Browse files Browse the repository at this point in the history
[3.0.0] Import Export CLI - PR 4
  • Loading branch information
tharindu1st authored Dec 7, 2017
2 parents 0495f3d + 1d19537 commit 64d27ea
Show file tree
Hide file tree
Showing 42 changed files with 1,039 additions and 1,123 deletions.
10 changes: 9 additions & 1 deletion import-export-cli/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,12 @@ Follow the following steps to make a contribution to this tool.
* Execute `glide install` inside `product-apim-tooling/import-export-cli` to download all dependencies
* Make changes to the code
* Commit to your fork
* Send a pull request to [wso2/product-apim-tooling](https://github.com/wso2/product-apim-tooling)
* Send a pull request to [wso2/product-apim-tooling](https://github.com/wso2/product-apim-tooling)


## Tips
* This command line tool is created on top of [Cobra](https://github.com/spf13/cobra)
* Cobra's [README](https://github.com/spf13/cobra/blob/master/README.md) provides detailed information on developing command line tools.
* For example: To add a new command named `apps` (so that the command would be `apimcli apps`) the following cobra command needs to be executed

`cobra add apps`
42 changes: 25 additions & 17 deletions import-export-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Command Line tool for importing and exporting APIs between different API Environ

## Getting Started

### Building from source
- ### Setting up the development environment
1. Install [Go 1.8.x](https://golang.org/dl)
2. Setup `$GOROOT` and `$GOPATH` correctly : [Tutorial](https://www.goinggo.net/2016/05/installing-go-and-your-workspace.html)
Expand All @@ -16,35 +17,48 @@ Command Line tool for importing and exporting APIs between different API Environ
- ### Building
`cd` into `product-apim-tooling/import-export-cli`

Execute `./build.sh -t apimcli.go -v 1.0.0 -f` to build for all platforms.
Execute `./build.sh -t apimcli.go -v 1.0.0 -f` to build for all platforms. (Can only be built in Mac or Linux)

Created packages will be available at `build/target` directory

- ### Running
Extract the compressed archive generated to a desired location.

Then execute `import-export-cli/apimcli` to start the application.
Then execute `./apimcli` to start the application. (Being inside `product-apim-tooling/import-export-cli`)

Execute `import-export-cli/apimcli --help` for further instructions.
Execute `./apimcli --help` for further instructions.

NOTE: To execute the tool from anywhere, append the location of the executable (apimcli) to your $PATH variable.

***

- ### Adding Environments
Add environments by either manually editing `import-export-cli/bin/main_config.yaml` or using the command
`apimcli set` command.
Add environments by either manually adding details to `$HOME/.wso2apimcli/main_config.yaml` or using the command
`apimcli add-env` command.

Type `apimcli set --help` for detailed instructions
Type `apimcli add-env --help` for detailed instructions

### Command Autocompletion (For Bash Only)
Copy the file `apimcli_bash_completion.sh` to `/etc/bash_completion.d/` and source it with
`source /etc/bash_completion.d/apimcli_bash_completion.sh` to enable bash auto-completion.

<hr/>
<br/>
***

## Usage
```bash
apimcli [command]
```

#### Global Flags
```bash
--verbose
Enable verbose logs (Provides more information on execution)
--insecure, -k
Allow connections to SSL sites without certs
--help, -h
Display information and example usage of a command
```

### Commands
* #### export-api
```bash
Expand All @@ -63,9 +77,7 @@ Command Line tool for importing and exporting APIs between different API Environ
apimcli export-api -n TestAPI -v 1.0.1 -e staging -p 123456
```


* #### import-api

```bash
Flags:
Required:
Expand All @@ -81,6 +93,7 @@ Command Line tool for importing and exporting APIs between different API Environ
apimcli import-api -f production/TestAPI_3.1.0.zip -e dev -p 123456
apimcli import-api -f TestAPI_1.2.1.zip -e dev
```

* #### list apis
```bash
Flags:
Expand Down Expand Up @@ -119,6 +132,7 @@ Command Line tool for importing and exporting APIs between different API Environ
--registration https://localhost:9443/identity/connect/register \
--token https: https://localhost:9443/oauth2/token
```

* #### remove-env
```bash
Flags:
Expand All @@ -136,6 +150,7 @@ Command Line tool for importing and exporting APIs between different API Environ
Examples:
apimcli reset-user -e dev
```

* #### version
```bash
apimcli version
Expand All @@ -150,10 +165,3 @@ Command Line tool for importing and exporting APIs between different API Environ
apimcli set --httpRequestTimeout 10000
apimcli set --exportDirectory /home/user/exported
```
#### Global Flags
```bash
--verbose
--insecure, -k
--help, -h
```
6 changes: 3 additions & 3 deletions import-export-cli/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ fi
#platforms="linux/amd64/linux/x64"
#platforms="darwin/amd64/macosx/x64"
if [ "${full_build}" == "true" ]; then
echo "Building "$'\e[1m'"${filename^^}:${build_version}"$'\e[0m'" for all platforms..."
# following line causes an error in MacOS
# echo "Building "$'\e[1m'"${filename^^}:${build_version}"$'\e[0m'" for all platforms..."
platforms="darwin/amd64/macosx/x64 linux/386/linux/i586 linux/amd64/linux/x64 windows/386/windows/i586 windows/amd64/windows/x64"
else
detectPlatformSpecificBuild
Expand Down Expand Up @@ -112,9 +113,8 @@ do
zipdir="${buildPath}/$filename"
mkdir -p $zipdir

cp -r "${baseDir}/resources/README.md" $zipdir > /dev/null 2>&1
cp -r "${baseDir}/resources/README.html" $zipdir > /dev/null 2>&1
cp -r "${baseDir}/LICENSE" $zipdir > /dev/null 2>&1
cp -r "${baseDir}/resources/exported" ${zipdir} > /dev/null 2>&1

# set destination path for binary
destination="$zipdir/$output"
Expand Down
14 changes: 9 additions & 5 deletions import-export-cli/cmd/addEnv.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,18 @@ var addEnvCmd = &cobra.Command{
Long: addEnvCmdLongDesc + addEnvCmdExamples,
Run: func(cmd *cobra.Command, args []string) {
utils.Logln(utils.LogPrefixInfo + addEnvCmdLiteral + " called")
err := addEnv(flagAddEnvName, flagPublisherEndpoint, flagRegistrationEndpoint, flagTokenEndpoint,
utils.MainConfigFilePath)
if err != nil {
utils.HandleErrorAndExit("Error adding environment", err)
}
executeAddEnvCmd(utils.MainConfigFilePath)
},
}

func executeAddEnvCmd(mainConfigFilePath string) {
err := addEnv(flagAddEnvName, flagPublisherEndpoint, flagRegistrationEndpoint, flagTokenEndpoint,
mainConfigFilePath)
if err != nil {
utils.HandleErrorAndExit("Error adding environment", err)
}
}

// addEnv adds a new environment and its endpoints and writes to config file
// @param envName : Name of the Environment
// @param publisherEndpoint : API Manager Endpoint for the environment
Expand Down
4 changes: 2 additions & 2 deletions import-export-cli/cmd/addEnv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func TestAddEnv2(t *testing.T) {
func TestAddEnv3(t *testing.T) {

sampleMainConfigFileName := "sample_main_config.yaml"
sampleMainConfigFilePath := filepath.Join(utils.ApplicationRoot, sampleMainConfigFileName)
sampleMainConfigFilePath := filepath.Join(utils.ConfigDirPath, sampleMainConfigFileName)

var sampleMainConnfig = new(utils.MainConfig)
sampleMainConnfig.Config = utils.Config{10000, ""}
Expand All @@ -85,7 +85,7 @@ func TestAddEnv3(t *testing.T) {
// TetsAddEnv4 - Correct Details - Successfully add new environment
func TestAddEnv4(t *testing.T) {
sampleMainConfigFileName := "sample_main_config.yaml"
sampleMainConfigFilePath := filepath.Join(utils.ApplicationRoot, sampleMainConfigFileName)
sampleMainConfigFilePath := filepath.Join(utils.ConfigDirPath, sampleMainConfigFileName)

var sampleMainConnfig = new(utils.MainConfig)
sampleMainConnfig.Config = utils.Config{10000, ""}
Expand Down
27 changes: 23 additions & 4 deletions import-export-cli/cmd/apis.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ var listApisCmdEnvironment string
var listApisCmdUsername string
var listApisCmdPassword string
var listApisCmdQuery string
var listApisCmdToken string

// apisCmd related info
const apisCmdLiteral = "apis"
Expand All @@ -56,6 +57,23 @@ var apisCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
utils.Logln(utils.LogPrefixInfo + listCmdLiteral + " " + apisCmdLiteral + " called")

executeListApisCmd()
},
}

func executeListApisCmd() {
if flagExportAPICmdToken != "" {
// token provided with --token (-t) flag
if exportAPICmdUsername != "" || exportAPICmdPassword != "" {
// username and/or password provided with -u and/or -p flags
// Error
utils.HandleErrorAndExit("username/password provided with OAuth token.", nil)
} else {
// token only, proceed with token
}
} else {
// no token provided with --token (-t) flag
// proceed with username and password
accessToken, apiManagerEndpoint, preCommandErr := utils.ExecutePreCommand(listApisCmdEnvironment, listApisCmdUsername,
listApisCmdPassword, utils.MainConfigFilePath, utils.EnvKeysAllFilePath)

Expand All @@ -78,7 +96,7 @@ var apisCmd = &cobra.Command{
} else {
utils.HandleErrorAndExit("Error calling '"+listCmdLiteral+" "+apisCmdLiteral+"'", preCommandErr)
}
},
}
}

// GetAPIList
Expand All @@ -102,7 +120,7 @@ func GetAPIList(query string, accessToken string, apiManagerEndpoint string) (in
utils.Logln(utils.LogPrefixInfo+"URL:", finalUrl)

headers := make(map[string]string)
headers[utils.HeaderAuthorization] = utils.HeaderValueAuthBearerPrefix + " " + accessToken
headers[utils.HeaderAuthorization] = utils.HeaderValueAuthPrefixBearer + " " + accessToken

resp, err := utils.InvokeGETRequest(finalUrl, headers)

Expand Down Expand Up @@ -144,16 +162,17 @@ func printAPIs(apis []utils.API) {
}

table.Render() // Send output

}

func init() {
ListCmd.AddCommand(apisCmd)

apisCmd.Flags().StringVarP(&listApisCmdEnvironment, "environment", "e",
utils.GetDefaultEnvironment(utils.MainConfigFilePath), "Environment to be searched")
utils.DefaultEnvironmentName, "Environment to be searched")
apisCmd.Flags().StringVarP(&listApisCmdQuery, "query", "q", "",
"(Optional) query to search for APIs")
apisCmd.Flags().StringVarP(&listApisCmdToken, "token", "t", "",
"OAuth token to be used instead of username and password")
apisCmd.Flags().StringVarP(&listApisCmdUsername, "username", "u", "", "Username")
apisCmd.Flags().StringVarP(&listApisCmdPassword, "password", "p", "", "Password")
}
42 changes: 24 additions & 18 deletions import-export-cli/cmd/envs.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,44 +30,50 @@ import (
// envsCmd related info
const EnvsCmdLiteral = "envs"
const EnvsCmdShortDesc = "Display the list of environments"

var EnvsCmdLongDesc = dedent.Dedent(`
Display a list of environments defined in '`+utils.MainConfigFileName+`' file
Display a list of environments defined in '` + utils.MainConfigFileName + `' file
`)

var EnvsCmdExamples = dedent.Dedent(`
`+utils.ProjectName+` list envs
` + utils.ProjectName + ` list envs
`)

// envsCmd represents the envs command
var envsCmd = &cobra.Command{
Use: EnvsCmdLiteral,
Short: EnvsCmdShortDesc,
Long: EnvsCmdLongDesc + EnvsCmdExamples,
Long: EnvsCmdLongDesc + EnvsCmdExamples,
Run: func(cmd *cobra.Command, args []string) {
utils.Logln(utils.LogPrefixInfo + listCmdLiteral + " " + EnvsCmdLiteral + " called")
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Publisher Endpoint", "Registration Endpoint", "Token Endpoint"})

var data [][]string

envs := utils.GetMainConfigFromFile(utils.MainConfigFilePath).Environments

for env, endpoints := range envs {
data = append(data, []string{env, endpoints.PublisherEndpoint, endpoints.RegistrationEndpoint,
endpoints.TokenEndpoint})
if len(envs) > 0 {
printEnvs(envs)
} else {
fmt.Println("No configured environments found")
}

for _, v := range data {
table.Append(v)
}

fmt.Printf("Environments available in file '%s'\n", utils.MainConfigFileName)
table.Render()
},
}

func printEnvs(envEndpoints map[string]utils.EnvEndpoints) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Publisher Endpoint", "Registration Endpoint", "Token Endpoint"})
var data [][]string

for env, endpoints := range envEndpoints {
data = append(data, []string{env, endpoints.PublisherEndpoint, endpoints.RegistrationEndpoint,
endpoints.TokenEndpoint})
}

for _, v := range data {
table.Append(v)
}

table.Render()
}

func init() {
ListCmd.AddCommand(envsCmd)

}
Loading

0 comments on commit 64d27ea

Please sign in to comment.