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
45 changes: 28 additions & 17 deletions cmd/importURL.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,8 @@ func NewImportURLCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm
Use: "import-url",
Short: "import API artifacts from URL on Microcks server",
Long: `import API artifacts from URL on Microcks server`,
Args: validateImportURLArgs,
RunE: func(cmd *cobra.Command, args []string) error {
// Parse subcommand args first.
if len(args) == 0 {
return errors.Wrapf(errors.KindUsage, "import-url requires a <specificationFileURL[:primary[:secret]]> argument")
}

specificationFiles := args[0]

mc, _, err := newCommandClient(globalClientOpts)
Expand Down Expand Up @@ -64,24 +60,39 @@ func NewImportURLCommand(globalClientOpts *connectors.ClientOptions) *cobra.Comm
return importURLCmd
}

func validateImportURLArgs(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.Wrapf(errors.KindUsage, "import-url requires a <specificationFileURL[:primary[:secret]]> argument")
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this way it gives to many responsibilities to this function.
Cobra offer pre-hook Args which is the right place for this kind of validation
this is also valid for the if len(arg) == 0 check

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I totally agree here. We can use that functionality to shift our validation much closer to the actual user input.

for _, f := range strings.Split(args[0], ",") {
lower := strings.ToLower(f)
if !strings.HasPrefix(lower, "https://") && !strings.HasPrefix(lower, "http://") {
return errors.Wrapf(
errors.KindUsage,
"invalid artifact URL '%s': must start with http:// or https://",
f,
)
}
}
return nil
}

func parseImportURLArg(f string) (string, bool, string) {
mainArtifact := true
secret := ""

// Check if URL starts with https or http
if strings.HasPrefix(f, "https://") || strings.HasPrefix(f, "http://") {
parts := strings.Split(f, ":")
n := len(parts)
parts := strings.Split(f, ":")
n := len(parts)

for i := 2; i < n; i++ {
if val, parseErr := strconv.ParseBool(parts[i]); parseErr == nil {
mainArtifact = val
if i+1 < n {
secret = strings.Join(parts[i+1:], ":")
}
f = strings.Join(parts[:i], ":")
break
for i := 2; i < n; i++ {
if val, parseErr := strconv.ParseBool(parts[i]); parseErr == nil {
mainArtifact = val
if i+1 < n {
secret = strings.Join(parts[i+1:], ":")
}
f = strings.Join(parts[:i], ":")
break
}
}
return f, mainArtifact, secret
Expand Down
Loading