github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/cmd/podman/remoteclientconfig/configfile.go (about)

     1  package remoteclientconfig
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/BurntSushi/toml"
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  // ReadRemoteConfig takes an io.Reader representing the remote configuration
    11  // file and returns a remoteconfig
    12  func ReadRemoteConfig(reader io.Reader) (*RemoteConfig, error) {
    13  	var remoteConfig RemoteConfig
    14  	// the configuration file does not exist
    15  	if reader == nil {
    16  		return &remoteConfig, ErrNoConfigationFile
    17  	}
    18  	_, err := toml.DecodeReader(reader, &remoteConfig)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  	// We need to validate each remote connection has fields filled out
    23  	for name, conn := range remoteConfig.Connections {
    24  		if len(conn.Destination) < 1 {
    25  			return nil, errors.Errorf("connection %q has no destination defined", name)
    26  		}
    27  	}
    28  	return &remoteConfig, err
    29  }
    30  
    31  // GetDefault returns the default RemoteConnection. If there is only one
    32  // connection, we assume it is the default as well
    33  func (r *RemoteConfig) GetDefault() (*RemoteConnection, error) {
    34  	if len(r.Connections) == 0 {
    35  		return nil, ErrNoDefinedConnections
    36  	}
    37  	for _, v := range r.Connections {
    38  		v := v
    39  		if len(r.Connections) == 1 {
    40  			// if there is only one defined connection, we assume it is
    41  			// the default whether tagged as such or not
    42  			return &v, nil
    43  		}
    44  		if v.IsDefault {
    45  			return &v, nil
    46  		}
    47  	}
    48  	return nil, ErrNoDefaultConnection
    49  }
    50  
    51  // GetRemoteConnection "looks up" a remote connection by name and returns it in the
    52  // form of a RemoteConnection
    53  func (r *RemoteConfig) GetRemoteConnection(name string) (*RemoteConnection, error) {
    54  	if len(r.Connections) == 0 {
    55  		return nil, ErrNoDefinedConnections
    56  	}
    57  	for k, v := range r.Connections {
    58  		v := v
    59  		if k == name {
    60  			return &v, nil
    61  		}
    62  	}
    63  	return nil, errors.Wrap(ErrConnectionNotFound, name)
    64  }