Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func NewCommad() *cobra.Command {
errors.CheckError(err)
command.PersistentFlags().StringVar(&clientOpts.ConfigPath, "config", defaultLocalConfigPath, "Path to Microcks config")
command.PersistentFlags().StringVar(&clientOpts.Context, "microcks-context", "", "Name of the Microcks context to use")
command.PersistentFlags().BoolVar(&clientOpts.Verbose, "verbose", false, "Produce dumps of HTTP exchanges")
command.PersistentFlags().BoolVarP(&clientOpts.Verbose, "verbose", "v", false, "print HTTP request and response details to stderr")
command.PersistentFlags().BoolVar(&clientOpts.InsecureTLS, "insecure-tls", false, "Whether to accept insecure HTTPS connection")
command.PersistentFlags().StringVar(&clientOpts.CaCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs")
command.PersistentFlags().StringVar(&clientOpts.ClientId, "keycloakClientId", "", "Keycloak Realm Service Account ClientId")
Expand Down
6 changes: 2 additions & 4 deletions cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,8 @@ func NewImportCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command

specificationFiles := args[0]

// Initialize config from command options.
config.InsecureTLS = globalClientOpts.InsecureTLS
config.CaCertPaths = globalClientOpts.CaCertPaths
config.Verbose = globalClientOpts.Verbose

// Read local config file in case we need some context info.
localConfig, err := config.ReadLocalConfig(globalClientOpts.ConfigPath)
Expand All @@ -63,7 +61,7 @@ func NewImportCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command

if globalClientOpts.ServerAddr != "" && globalClientOpts.ClientId != "" && globalClientOpts.ClientSecret != "" {
// Create client with server address.
mc = connectors.NewMicrocksClient(globalClientOpts.ServerAddr)
mc = connectors.NewMicrocksClient(globalClientOpts.ServerAddr, globalClientOpts.Verbose)

keycloakURL, err := mc.GetKeycloakURL()
if err != nil {
Expand All @@ -74,7 +72,7 @@ func NewImportCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command
var oauthToken string = "unauthenticated-token"
if keycloakURL != "null" {
// If Keycloak is enabled, retrieve an OAuth token using Keycloak Client.
kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret)
kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret, globalClientOpts.Verbose)

oauthToken, err = kc.ConnectAndGetToken()
if err != nil {
Expand Down
83 changes: 45 additions & 38 deletions cmd/importDir.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,19 +78,10 @@ var supportedExtensions = map[string]bool{
".xml": true,
}

type ImportError struct {
File string
Err error
}

type ValidationError struct {
Message string
}

func (e ImportError) Error() string {
return fmt.Sprintf("failed to import %s: %v", e.File, e.Err)
}

func (e ValidationError) Error() string {
return e.Message
}
Expand All @@ -99,7 +90,6 @@ func NewImportDirCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm
var (
recursive bool
pattern string
verbose bool
)

var importDirCmd = &cobra.Command{
Expand All @@ -126,36 +116,54 @@ func NewImportDirCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm

config.InsecureTLS = globalClientOpts.InsecureTLS
config.CaCertPaths = globalClientOpts.CaCertPaths
config.Verbose = globalClientOpts.Verbose

localConfig, err := config.ReadLocalConfig(globalClientOpts.ConfigPath)
if err != nil {
fmt.Println(err)
return
}
var mc connectors.MicrocksClient

if localConfig == nil {
fmt.Println("Please login to perform operation...")
return
}
if globalClientOpts.ServerAddr != "" && globalClientOpts.ClientId != "" && globalClientOpts.ClientSecret != "" {
mc = connectors.NewMicrocksClient(globalClientOpts.ServerAddr, globalClientOpts.Verbose)

if globalClientOpts.Context == "" {
globalClientOpts.Context = localConfig.CurrentContext
}
keycloakURL, err := mc.GetKeycloakURL()
if err != nil {
fmt.Printf("Got error when invoking Microcks client retrieving config: %s", err)
os.Exit(1)
}

// Create client
mc, err := connectors.NewClient(*globalClientOpts)
if err != nil {
fmt.Printf("error %v", err)
return
var oauthToken string = "unauthenticated-token"
if keycloakURL != "null" {
kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret, globalClientOpts.Verbose)
oauthToken, err = kc.ConnectAndGetToken()
if err != nil {
fmt.Printf("Got error when invoking Keycloak client: %s", err)
os.Exit(1)
}
}
mc.SetOAuthToken(oauthToken)
} else {
localConfig, err := config.ReadLocalConfig(globalClientOpts.ConfigPath)
if err != nil {
fmt.Println(err)
return
}
if localConfig == nil {
fmt.Println("Please login to perform operation...")
return
}
if globalClientOpts.Context == "" {
globalClientOpts.Context = localConfig.CurrentContext
}
mc, err = connectors.NewClient(*globalClientOpts)
if err != nil {
fmt.Printf("error %v", err)
return
}
}

// Set up business logic dependencies
fs := &RealFileSystem{}
importConfig := ImportConfig{
Recursive: recursive,
Pattern: pattern,
Verbose: verbose,
Verbose: globalClientOpts.Verbose,
}

// Execute business logic
Expand All @@ -170,29 +178,29 @@ func NewImportDirCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm
}

// Display results
if verbose {
fmt.Printf("Found %d specification files to import...\n", result.TotalFiles)
if globalClientOpts.Verbose {
fmt.Fprintf(os.Stderr, "Found %d specification files to import...\n", result.TotalFiles)
for i, file := range result.SuccessFiles {
fmt.Printf("[%d/%d] Imported: %s\n", i+1, result.TotalFiles, file)
fmt.Fprintf(os.Stderr, "[%d/%d] Imported: %s\n", i+1, result.TotalFiles, file)
}
for i, file := range result.FailedFiles {
errorMsg := "Unknown error"
errorMsg := "unknown error"
if i < len(result.Errors) {
errorMsg = result.Errors[i]
}
fmt.Printf("✗ Failed: %s - %s\n", file, errorMsg)
fmt.Fprintf(os.Stderr, "Failed: %s - %s\n", file, errorMsg)
}
} else {
fmt.Println("\nImport results:")
for _, file := range result.SuccessFiles {
fmt.Printf("Imported: %s\n", file)
fmt.Printf("Imported: %s\n", file)
}
for i, file := range result.FailedFiles {
errorMsg := "Unknown error"
errorMsg := "unknown error"
if i < len(result.Errors) {
errorMsg = result.Errors[i]
}
fmt.Printf("Failed: %s - %s\n", file, errorMsg)
fmt.Printf("Failed: %s - %s\n", file, errorMsg)
}
}

Expand All @@ -202,7 +210,6 @@ func NewImportDirCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm

importDirCmd.Flags().BoolVar(&recursive, "recursive", false, "Scan subdirectories recursively")
importDirCmd.Flags().StringVar(&pattern, "pattern", "", "File pattern to match (e.g., '*.yaml', 'openapi.*')")
importDirCmd.Flags().BoolVar(&verbose, "verbose", false, "Show detailed progress")

return importDirCmd
}
Expand Down
31 changes: 2 additions & 29 deletions cmd/importDir_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/microcks/microcks-cli/pkg/connectors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type MockMicrocksClient struct {
Expand Down Expand Up @@ -68,7 +68,7 @@ func (m *MockFileSystem) Walk(root string, walkFn filepath.WalkFunc) error {
}

for path, isDir := range m.Files {
if filepath.HasPrefix(path, root) {
if strings.HasPrefix(path, root) {
info := &MockFileInfo{name: filepath.Base(path), isDir: isDir}
if err := walkFn(path, info, nil); err != nil {
return err
Expand Down Expand Up @@ -374,10 +374,6 @@ func TestNewImportDirCommand(t *testing.T) {
patternFlag := cmd.Flags().Lookup("pattern")
assert.NotNil(t, patternFlag)
assert.Equal(t, "string", patternFlag.Value.Type())

verboseFlag := cmd.Flags().Lookup("verbose")
assert.NotNil(t, verboseFlag)
assert.Equal(t, "bool", verboseFlag.Value.Type())
}

// TestImportResult tests the ImportResult struct
Expand All @@ -398,26 +394,3 @@ func TestImportResult(t *testing.T) {
assert.Len(t, result.FailedFiles, 2)
assert.Len(t, result.Errors, 2)
}

// Benchmark tests for performance
func BenchmarkImportDirectory(b *testing.B) {
// Create a mock with many files
mockClient := &MockMicrocksClient{}
mockFS := &MockFileSystem{
Files: make(map[string]bool),
}

// Add 100 test files
for i := 0; i < 100; i++ {
path := fmt.Sprintf("/test/spec_%d.yaml", i)
mockFS.Files[path] = false
}

config := ImportConfig{Recursive: false, Pattern: ""}

b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := ImportDirectory(mockClient, mockFS, "/test", config)
require.NoError(b, err)
}
}
5 changes: 2 additions & 3 deletions cmd/importURL.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,12 @@ func NewImportURLCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm

config.InsecureTLS = globalClientOpts.InsecureTLS
config.CaCertPaths = globalClientOpts.CaCertPaths
config.Verbose = globalClientOpts.Verbose

var mc connectors.MicrocksClient

if globalClientOpts.ServerAddr != "" && globalClientOpts.ClientId != "" && globalClientOpts.ClientSecret != "" {
// create client with server address
mc = connectors.NewMicrocksClient(globalClientOpts.ServerAddr)
mc = connectors.NewMicrocksClient(globalClientOpts.ServerAddr, globalClientOpts.Verbose)

keycloakURL, err := mc.GetKeycloakURL()
if err != nil {
Expand All @@ -60,7 +59,7 @@ func NewImportURLCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm
var oauthToken string = "unauthenticated-token"
if keycloakURL != "null" {
// If Keycloak is enabled, retrieve an OAuth token using Keycloak Client.
kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret)
kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret, globalClientOpts.Verbose)

oauthToken, err = kc.ConnectAndGetToken()
if err != nil {
Expand Down
11 changes: 5 additions & 6 deletions cmd/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,9 @@ microcks login http://localhost:8080 --sso --sso-launch-browser=false

config.InsecureTLS = globalClientOpts.InsecureTLS
config.CaCertPaths = globalClientOpts.CaCertPaths
config.Verbose = globalClientOpts.Verbose

server = args[0]
mc := connectors.NewMicrocksClient(server)
mc := connectors.NewMicrocksClient(server, globalClientOpts.Verbose)
keycloakUrl, err := mc.GetKeycloakURL()

if err != nil {
Expand Down Expand Up @@ -120,13 +119,13 @@ microcks login http://localhost:8080 --sso --sso-launch-browser=false
os.Exit(1)
}
//Perform login and retrive tokens
authToken, refreshToken = passwordLogin(keycloakUrl, clientID, clientSecret, username, password)
authToken, refreshToken = passwordLogin(keycloakUrl, clientID, clientSecret, username, password, globalClientOpts.Verbose)
authCfg.ClientId = clientID
authCfg.ClientSecret = clientSecret
} else {
httpClient := mc.HttpClient()
ctx = oidc.ClientContext(ctx, httpClient)
kc := connectors.NewKeycloakClient(keycloakUrl, "", "")
kc := connectors.NewKeycloakClient(keycloakUrl, "", "", globalClientOpts.Verbose)
oauth2conf, err := kc.GetOIDCConfig()
errors.CheckError(err)
authToken, refreshToken = oauth2login(ctx, ssoProt, oauth2conf, ssoLaunchBrowser)
Expand Down Expand Up @@ -308,8 +307,8 @@ func ssoAuthFlow(url string, ssoLaunchBrowser bool) {
}
}

func passwordLogin(keycloakURL, clientId, clientSecret, Username, Password string) (string, string) {
kc := connectors.NewKeycloakClient(keycloakURL, clientId, clientSecret)
func passwordLogin(keycloakURL, clientId, clientSecret, Username, Password string, verbose bool) (string, string) {
kc := connectors.NewKeycloakClient(keycloakURL, clientId, clientSecret, verbose)
username, password := promptCredentials(Username, Password)

authToken, refreshToken, err := kc.ConnectAndGetTokenAndRefreshToken(username, password)
Expand Down
5 changes: 2 additions & 3 deletions cmd/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ func NewTestCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command {
// Collect optional HTTPS transport flags.
config.InsecureTLS = globalClientOpts.InsecureTLS
config.CaCertPaths = globalClientOpts.CaCertPaths
config.Verbose = globalClientOpts.Verbose

// Compute time to wait in milliseconds.
var waitForMilliseconds int64
Expand Down Expand Up @@ -117,7 +116,7 @@ func NewTestCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command {

// create client with server address
serverAddr = globalClientOpts.ServerAddr
mc = connectors.NewMicrocksClient(serverAddr)
mc = connectors.NewMicrocksClient(serverAddr, globalClientOpts.Verbose)

keycloakURL, err := mc.GetKeycloakURL()
if err != nil {
Expand All @@ -128,7 +127,7 @@ func NewTestCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command {
var oauthToken string = "unauthenticated-token"
if keycloakURL != "null" {
// If Keycloak is enabled, retrieve an OAuth token using Keycloak Client.
kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret)
kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret, globalClientOpts.Verbose)

oauthToken, err = kc.ConnectAndGetToken()
if err != nil {
Expand Down
31 changes: 0 additions & 31 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
strings "strings"
Expand All @@ -31,8 +29,6 @@ var (
InsecureTLS bool = false
// CaCertPaths defines extra paths (comma-separated) of CRT files to add to system CA Roots.
CaCertPaths string
// Verbose represents a debug flag for HTTP Exchanges
Verbose bool = false

ConfigPath = filepath.Join(os.Getenv("HOME"), ".microcks-cli", "config.yaml")
)
Expand Down Expand Up @@ -67,30 +63,3 @@ func CreateTLSConfig() *tls.Config {
}
return tlsConfig
}

// DumpRequestIfRequired takes care of dumping request if configured that way
func DumpRequestIfRequired(name string, req *http.Request, body bool) {
if Verbose {
fmt.Printf("\nDumping request '%s':\n", name)
dump, err := httputil.DumpRequestOut(req, body)
if err != nil {
fmt.Println("Got error while dumping request out")
}
fmt.Printf("%s", dump)
}
}

// DumpResponseIfRequired takes care of dumping request if configured that way
func DumpResponseIfRequired(name string, resp *http.Response, body bool) {
if Verbose {
fmt.Printf("\nDumping response '%s':\n", name)
dump, err := httputil.DumpResponse(resp, body)
if err != nil {
fmt.Println("Got error while dumping response")
}
fmt.Printf("%s", dump)
if body {
fmt.Println("")
}
}
}
Loading