other

package
v1.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2025 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Copyright © 2025 NAME HERE <EMAIL ADDRESS>

Index

Constants

This section is empty.

Variables

View Source
var AliasCmd = &cobra.Command{
	Use:   "alias",
	Short: "Manage command aliases",
	Long:  `Manage aliases for frequently used commands.`,
}

AliasCmd represents the alias command

View Source
var ApiResourcesCmd = &cobra.Command{
	Use:   "api_resources",
	Short: "Displays supported API resources",
	Example: `  # List all API resources for all services
  $ cfctl api_resources

  # List API resources for a specific service
  $ cfctl api_resources -s identity

  # List API resources for multiple services
  $ cfctl api_resources -s identity,inventory,repository`,
	Run: func(cmd *cobra.Command, args []string) {
		home, err := os.UserHomeDir()
		if err != nil {
			log.Fatalf("Unable to find home directory: %v", err)
		}

		settingPath := filepath.Join(home, ".cfctl", "setting.yaml")

		mainV := viper.New()
		mainV.SetConfigFile(settingPath)
		mainV.SetConfigType("yaml")
		mainConfigErr := mainV.ReadInConfig()

		var currentEnv string
		var envConfig map[string]interface{}

		if mainConfigErr == nil {
			currentEnv = mainV.GetString("environment")
			if currentEnv != "" {
				envConfig = mainV.GetStringMap(fmt.Sprintf("environments.%s", currentEnv))
			}
		}

		if envConfig == nil {
			return
		}

		endpointsMap, err := loadEndpointsFromCache(currentEnv)
		if err != nil {

			endpointName, ok := envConfig["endpoint"].(string)
			if !ok || endpointName == "" {
				return
			}

			endpointsMap, err = configs.FetchEndpointsMap(endpointName)
			if err != nil {
				log.Fatalf("Failed to fetch endpointsMap from '%s': %v", endpointName, err)
			}
		}

		shortNamesFile := filepath.Join(home, ".cfctl", "short_names.yaml")
		shortNamesMap := make(map[string]string)
		if _, err := os.Stat(shortNamesFile); err == nil {
			file, err := os.Open(shortNamesFile)
			if err != nil {
				log.Fatalf("Failed to open short_names.yaml file: %v", err)
			}
			defer file.Close()

			err = yaml.NewDecoder(file).Decode(&shortNamesMap)
			if err != nil {
				log.Fatalf("Failed to decode short_names.yaml: %v", err)
			}
		}

		if endpoints != "" {
			selectedEndpoints := strings.Split(endpoints, ",")
			for i := range selectedEndpoints {
				selectedEndpoints[i] = strings.TrimSpace(selectedEndpoints[i])
			}
			var allData [][]string

			for _, endpointName := range selectedEndpoints {
				serviceEndpoint, ok := endpointsMap[endpointName]
				if !ok {
					log.Printf("No endpoint found for %s", endpointName)
					continue
				}

				result, err := format.FetchServiceResources(endpointName, serviceEndpoint, shortNamesMap)
				if err != nil {
					log.Printf("Error processing service %s: %v", endpointName, err)
					continue
				}

				allData = append(allData, result...)
			}

			sort.Slice(allData, func(i, j int) bool {
				return allData[i][0] < allData[j][0]
			})

			renderTable(allData)
			return
		}

		// If no specific endpoints are provided, list all services
		var wg sync.WaitGroup
		dataChan := make(chan [][]string, len(endpointsMap))
		errorChan := make(chan error, len(endpointsMap))

		for service, endpoint := range endpointsMap {
			wg.Add(1)
			go func(service, endpoint string) {
				defer wg.Done()
				result, err := format.FetchServiceResources(service, endpoint, shortNamesMap)
				if err != nil {
					errorChan <- fmt.Errorf("Error processing service %s: %v", service, err)
					return
				}
				dataChan <- result
			}(service, endpoint)
		}

		wg.Wait()
		close(dataChan)
		close(errorChan)

		if len(errorChan) > 0 {
			for err := range errorChan {
				log.Println(err)
			}
		}

		var allData [][]string
		for data := range dataChan {
			allData = append(allData, data...)
		}

		sort.Slice(allData, func(i, j int) bool {
			return allData[i][0] < allData[j][0]
		})

		renderTable(allData)
	},
}
View Source
var ApplyCmd = &cobra.Command{
	Use:   "apply",
	Short: "Apply a configuration to a resource using a file",
	Long:  `Apply the configuration in the YAML file to create or update a resource`,
	Example: `  # Create test.yaml
  service: identity
  verb: create
  resource: user
  spec:
    user_id: test-user
    auth_type: LOCAL

  # Apply the configuration in test.yaml
  $ cfctl apply -f test.yaml`,
	RunE: func(cmd *cobra.Command, args []string) error {
		filename, _ := cmd.Flags().GetString("filename")
		if filename == "" {
			return fmt.Errorf("filename is required (-f flag)")
		}

		data, err := os.ReadFile(filename)
		if err != nil {
			return fmt.Errorf("failed to read file: %v", err)
		}

		var resource ResourceSpec
		if err := yaml.Unmarshal(data, &resource); err != nil {
			return fmt.Errorf("failed to parse YAML: %v", err)
		}

		// Convert spec to parameters
		var parameters []string
		for key, value := range resource.Spec {
			switch v := value.(type) {
			case string:
				parameters = append(parameters, fmt.Sprintf("%s=%s", key, v))
			case bool, int, float64:
				parameters = append(parameters, fmt.Sprintf("%s=%v", key, v))
			case []interface{}, map[string]interface{}:

				jsonBytes, err := json.Marshal(v)
				if err != nil {
					return fmt.Errorf("failed to marshal parameter %s: %v", key, err)
				}
				parameters = append(parameters, fmt.Sprintf("%s=%s", key, string(jsonBytes)))
			default:

				jsonBytes, err := json.Marshal(v)
				if err != nil {
					return fmt.Errorf("failed to marshal parameter %s: %v", key, err)
				}
				parameters = append(parameters, fmt.Sprintf("%s=%s", key, string(jsonBytes)))
			}
		}

		options := &transport.FetchOptions{
			Parameters: parameters,
		}

		_, err = transport.FetchService(resource.Service, resource.Verb, resource.Resource, options)
		if err != nil {
			pterm.Error.Println(err.Error())
			return nil
		}

		pterm.Success.Printf("Resource %s/%s applied successfully\n", resource.Service, resource.Resource)
		return nil
	},
}

ApplyCmd represents the apply command

View Source
var LoginCmd = &cobra.Command{
	Use:   "login",
	Short: "Login to SpaceONE",
	Long: `A command that allows you to login to SpaceONE.
It will prompt you for your User ID, Password, and fetch the Domain ID automatically, then fetch the token.`,
	Run: executeLogin,
}

LoginCmd represents the login command

View Source
var SettingCmd = &cobra.Command{
	Use:   "setting",
	Short: "Manage cfctl setting file",
	Long: `Manage setting file for cfctl. 
You can initialize, switch environments, and display the current configuration.`,
}

SettingCmd represents the setting command

Functions

func GetIdentityEndpoint added in v1.0.11

func GetIdentityEndpoint(apiEndpoint string) (string, bool, error)

GetIdentityEndpoint fetches the identity service endpoint from the API endpoint

func GetSettingDir added in v1.0.0

func GetSettingDir() string

GetSettingDir returns the directory where setting file are stored

Types

type ResourceSpec added in v1.0.13

type ResourceSpec struct {
	Service  string                 `yaml:"service"`
	Verb     string                 `yaml:"verb"`
	Resource string                 `yaml:"resource"`
	Spec     map[string]interface{} `yaml:"spec"`
}

type ServiceEndpoint added in v1.0.11

type ServiceEndpoint struct {
	Name     string `json:"name"`
	Service  string `json:"service"`
	Endpoint string `json:"endpoint"`
}

type TokenInfo added in v0.0.7

type TokenInfo struct {
	Token string `yaml:"token"`
}

type UserCredentials added in v0.0.7

type UserCredentials struct {
	UserID   string `yaml:"userid"`
	Password string `yaml:"password"`
	Token    string `yaml:"token"`
}

Define a struct for user credentials

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL