Skip to content
Snippets Groups Projects
execute.go 888 B
// Copyright 2022 schukai GmbH. All rights reserved.
// Use of this source code is governed by a AGPL-3.0
// license that can be found in the LICENSE file.

package xflags

import (
	"reflect"
)

func (s *Settings[C]) Execute() *Settings[C] {
	if len(s.errors) > 0 {
		return s
	}

	if s.command == nil {
		s.errors = append(s.errors, MissingCommandError)
		return s
	}

	if !s.command.flagSet.Parsed() {
		s.errors = append(s.errors, NotParsedError)
	} else {
		callCmdFunctions(s.command.commands)
	}

	return s
}

func callCmdFunctions[C any](commands []*cmd[C]) {
	for _, command := range commands {
		if command.flagSet.Parsed() {

			f := reflect.ValueOf(&command.settings.definitions).MethodByName(command.functionName)
			if f.IsValid() {
				m := command.settings
				in := []reflect.Value{reflect.ValueOf(m)}
				f.Call(in)
			}

			callCmdFunctions(command.commands)
		}
	}

}