utils

package
v0.0.18 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Overview

Copyright Project Harbor Authors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const KeyringService = "harbor-cli"
View Source
const KeyringUser = "harbor-cli-encryption-key"

Variables

View Source
var (
	ClientInstance *v2client.HarborAPI
	ClientOnce     sync.Once
	ClientErr      error
)
View Source
var (
	CurrentHarborData   *HarborData
	CurrentHarborConfig *HarborConfig
)
View Source
var ConfigInitialization = &Once{}
View Source
var ConfigurationCategories = map[string]string{

	"AuthMode":                         "authentication",
	"LdapBaseDn":                       "authentication",
	"LdapFilter":                       "authentication",
	"LdapGroupAdminDn":                 "authentication",
	"LdapGroupAttributeName":           "authentication",
	"LdapGroupBaseDn":                  "authentication",
	"LdapGroupMembershipAttribute":     "authentication",
	"LdapGroupSearchFilter":            "authentication",
	"LdapGroupSearchScope":             "authentication",
	"LdapScope":                        "authentication",
	"LdapSearchDn":                     "authentication",
	"LdapSearchPassword":               "authentication",
	"LdapTimeout":                      "authentication",
	"LdapUID":                          "authentication",
	"LdapURL":                          "authentication",
	"OIDCAdminGroup":                   "authentication",
	"OIDCAutoOnboard":                  "authentication",
	"OIDCClientID":                     "authentication",
	"OIDCClientSecret":                 "authentication",
	"OIDCEndpoint":                     "authentication",
	"OIDCExtraRedirectParms":           "authentication",
	"OIDCGroupFilter":                  "authentication",
	"OIDCGroupsClaim":                  "authentication",
	"OIDCName":                         "authentication",
	"OIDCScope":                        "authentication",
	"OIDCUserClaim":                    "authentication",
	"HTTPAuthproxyAdminGroups":         "authentication",
	"HTTPAuthproxyAdminUsernames":      "authentication",
	"HTTPAuthproxyEndpoint":            "authentication",
	"HTTPAuthproxyServerCertificate":   "authentication",
	"HTTPAuthproxySkipSearch":          "authentication",
	"HTTPAuthproxyTokenreviewEndpoint": "authentication",
	"UaaClientID":                      "authentication",
	"UaaClientSecret":                  "authentication",
	"UaaEndpoint":                      "authentication",
	"PrimaryAuthMode":                  "authentication",
	"LdapVerifyCert":                   "authentication",
	"OIDCVerifyCert":                   "authentication",
	"OIDCLogout":                       "authentication",

	"UaaVerifyCert":              "security",
	"HTTPAuthproxyVerifyCert":    "security",
	"SelfRegistration":           "security",
	"ProjectCreationRestriction": "security",
	"RobotTokenDuration":         "security",
	"TokenExpiration":            "security",
	"SessionTimeout":             "security",

	"RobotNamePrefix":            "system",
	"ReadOnly":                   "system",
	"QuotaPerProjectEnable":      "system",
	"StoragePerProject":          "system",
	"NotificationEnable":         "system",
	"ScannerSkipUpdatePulltime":  "system",
	"SkipAuditLogDatabase":       "system",
	"AuditLogForwardEndpoint":    "system",
	"BannerMessage":              "system",
	"DisabledAuditLogEventTypes": "system",
}

Functions

func AddCredentialsToConfigFile added in v0.0.2

func AddCredentialsToConfigFile(credential Credential, configPath string) error

func ApplyDataFile added in v0.0.3

func ApplyDataFile(harborDataPath, harborConfigPath string) error

Helper function to update or create the data file

func BuildQueryParam added in v0.0.15

func BuildQueryParam(fuzzy, match, ranges []string, validKeys []string) (string, error)

Builds the `q` param for List API's

func CamelCaseToHR added in v0.0.12

func CamelCaseToHR(s string) string

This function covert camelCase to Human Readable form

func Capitalize added in v0.0.9

func Capitalize(s string) string

func ContextWithClient added in v0.0.2

func ContextWithClient() (context.Context, *v2client.HarborAPI, error)

func ConvertToConfigurations added in v0.0.11

func ConvertToConfigurations(resp *models.ConfigurationsResponse) *models.Configurations

func CreateConfigFile added in v0.0.2

func CreateConfigFile(configPath string) error

func CreateDataFile added in v0.0.3

func CreateDataFile(dataFilePath string, initialConfigPath string) error

func Decrypt added in v0.0.4

func Decrypt(key []byte, ciphertext string) (string, error)

func DefaultCredentialName added in v0.0.6

func DefaultCredentialName(username, server string) string

func DetermineConfigPath added in v0.0.3

func DetermineConfigPath(cfgFile string, userSpecifiedConfig bool) (string, error)

Helper function to determine the config path

func EmptyStringValidator added in v0.0.6

func EmptyStringValidator(variable string) func(string) error

func Encrypt added in v0.0.4

func Encrypt(key, plaintext []byte) (string, error)

func EnsureConfigFileExists added in v0.0.3

func EnsureConfigFileExists(harborConfigPath string) error

Helper function to ensure config file exists

func ExtractConfigValues added in v0.0.15

func ExtractConfigValues[T ConfigType](cfg T) map[string]any

func ExtractConfigurationsByCategory added in v0.0.11

func ExtractConfigurationsByCategory(resp *models.ConfigurationsResponse, category string) *models.Configurations

func FormatCreatedTime added in v0.0.2

func FormatCreatedTime(timestamp string) (string, error)

func FormatSize added in v0.0.2

func FormatSize(size int64) string

func FormatUrl added in v0.0.2

func FormatUrl(url string) string

func FromKebabCase added in v0.0.17

func FromKebabCase(s string) string

func GenerateEncryptionKey added in v0.0.4

func GenerateEncryptionKey() error

func GetClient added in v0.0.2

func GetClient() (*v2client.HarborAPI, error)

func GetClientByConfig

func GetClientByConfig(clientConfig *harbor.ClientSetConfig) *v2client.HarborAPI

func GetClientByCredentialName

func GetClientByCredentialName(credentialName string) (*v2client.HarborAPI, error)

Returns Harbor v2 client after resolving the credential name

func GetDataPaths added in v0.0.3

func GetDataPaths() (harborDataPath string, harborDataDir string)

Helper function to get data paths

func GetEncryptionKey added in v0.0.4

func GetEncryptionKey() ([]byte, error)

func GetSecretStdin added in v0.0.8

func GetSecretStdin(prompt string) (string, error)

Get Password as Stdin

func GetUserIdFromUser added in v0.0.12

func GetUserIdFromUser() int64

GetUserIdFromUser retrieves the user ID from the current user context using viper and the Harbor client.

func InitConfig added in v0.0.3

func InitConfig(cfgFile string, userSpecifiedConfig bool)

func IsCategory added in v0.0.11

func IsCategory(fieldName string, category string) bool

func ParseHarborErrorCode added in v0.0.6

func ParseHarborErrorCode(err error) string

func ParseHarborErrorMsg added in v0.0.6

func ParseHarborErrorMsg(err error) string

func ParseProjectRepo added in v0.0.2

func ParseProjectRepo(projectRepo string) (project, repo string, err error)

func ParseProjectRepoReference added in v0.0.2

func ParseProjectRepoReference(projectRepoReference string) (project, repo, reference string, err error)

func PrintFormat added in v0.0.3

func PrintFormat[T any](resp T, format string) error

func PrintPayloadInJSONFormat

func PrintPayloadInJSONFormat(payload any)

func PrintPayloadInYAMLFormat added in v0.0.3

func PrintPayloadInYAMLFormat(payload any)

func ReadConfig added in v0.0.3

func ReadConfig(harborConfigPath string) error

Helper function to read the config file using Viper

func RemoveColumns added in v0.0.12

func RemoveColumns(columns []table.Column, colsToRemove []string) []table.Column

RemoveColumns removes columns with specified titles from the given columns array.

func SanitizeServerAddress added in v0.0.3

func SanitizeServerAddress(server string) string

func SavePayloadJSON added in v0.0.8

func SavePayloadJSON(filename string, payload any)

func SetCurrentHarborConfig added in v0.0.7

func SetCurrentHarborConfig(config *HarborConfig) error

SetCurrentHarborConfig replaces the current HarborConfig with the provided one, both in memory and in the config file.

func SetKeyringProvider added in v0.0.4

func SetKeyringProvider(provider KeyringProvider)

func StorageStringToBytes added in v0.0.6

func StorageStringToBytes(storage string) (int64, error)

func ToKebabCase added in v0.0.8

func ToKebabCase(s string) string

func UpdateConfigFile added in v0.0.4

func UpdateConfigFile(config *HarborConfig) error

UpdateConfigFile updates the YAML config file on disk with the values in the given HarborConfig, and also updates the in-memory CurrentHarborConfig.

func UpdateCredentialsInConfigFile added in v0.0.3

func UpdateCredentialsInConfigFile(updatedCredential Credential, configPath string) error

func UpdateDataFile added in v0.0.3

func UpdateDataFile(dataFilePath string, newConfigPath string) error

func ValidateConfigPath added in v0.0.3

func ValidateConfigPath(configPath string) bool

func ValidateEmail added in v0.0.2

func ValidateEmail(email string) bool

func ValidateFL added in v0.0.2

func ValidateFL(name string) bool

func ValidatePassword added in v0.0.2

func ValidatePassword(password string) error

check if the password format is valid

func ValidateProjectName added in v0.0.2

func ValidateProjectName(projectName string) bool

check if the project name is valid

func ValidateRegistryName added in v0.0.2

func ValidateRegistryName(rn string) bool

func ValidateStorageLimit added in v0.0.2

func ValidateStorageLimit(sl string) error

func ValidateTagName added in v0.0.2

func ValidateTagName(tagName string) bool

check if the tag name is valid

func ValidateURL added in v0.0.6

func ValidateURL(rawURL string) error

ValidateURL checks if the URL has valid format, non-empty host, and host is a valid IP or domain. Domain regex: labels must start/end with alphanumeric, can contain hyphens, max 63 chars, TLD min 2 letters.

func ValidateUserName added in v0.0.2

func ValidateUserName(username string) bool

ValidateUserName checks if the username is valid by length and allowed characters.

Types

type ConfigType added in v0.0.15

type ConfigType interface {
	*models.Configurations | *models.ConfigurationsResponse
}

type Credential

type Credential struct {
	Name          string `yaml:"name"`
	Username      string `yaml:"username"`
	Password      string `yaml:"password"`
	ServerAddress string `yaml:"serveraddress"`
}

func GetCredentials added in v0.0.2

func GetCredentials(credentialName string) (Credential, error)

type EnvironmentKeyring added in v0.0.5

type EnvironmentKeyring struct {
	EnvVarName string
}

EnvironmentKeyring implements KeyringProvider using environment variables

func (*EnvironmentKeyring) Delete added in v0.0.5

func (e *EnvironmentKeyring) Delete(service, user string) error

func (*EnvironmentKeyring) Get added in v0.0.5

func (e *EnvironmentKeyring) Get(service, user string) (string, error)

func (*EnvironmentKeyring) Set added in v0.0.5

func (e *EnvironmentKeyring) Set(service, user, password string) error

type FileKeyring added in v0.0.5

type FileKeyring struct {
	BaseDir string
}

FileKeyring implements KeyringProvider using files in a directory

func (*FileKeyring) Delete added in v0.0.5

func (f *FileKeyring) Delete(service, user string) error

func (*FileKeyring) Get added in v0.0.5

func (f *FileKeyring) Get(service, user string) (string, error)

func (*FileKeyring) Set added in v0.0.5

func (f *FileKeyring) Set(service, user, password string) error

type HarborConfig added in v0.0.2

type HarborConfig struct {
	CurrentCredentialName string                `mapstructure:"current-credential-name" yaml:"current-credential-name"`
	Credentials           []Credential          `mapstructure:"credentials" yaml:"credentials"`
	Configurations        models.Configurations `mapstructure:"configurations" yaml:"configurations"`
}

func GetCurrentHarborConfig added in v0.0.3

func GetCurrentHarborConfig() (*HarborConfig, error)

type HarborData added in v0.0.3

type HarborData struct {
	ConfigPath string `mapstructure:"configpath" yaml:"configpath"`
}

func GetCurrentHarborData added in v0.0.3

func GetCurrentHarborData() (*HarborData, error)

func ReadDataFile added in v0.0.3

func ReadDataFile(dataFilePath string) (HarborData, error)

type HarborErrorPayload added in v0.0.6

type HarborErrorPayload struct {
	Errors []struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"errors"`
}

type KeyringProvider added in v0.0.4

type KeyringProvider interface {
	Set(service, user, password string) error
	Get(service, user string) (string, error)
	Delete(service, user string) error
}

func GetKeyringProvider added in v0.0.5

func GetKeyringProvider() KeyringProvider

GetKeyringProvider selects the appropriate keyring provider

type MockKeyring added in v0.0.4

type MockKeyring struct {
	// contains filtered or unexported fields
}

func NewMockKeyring added in v0.0.4

func NewMockKeyring() *MockKeyring

func (*MockKeyring) Delete added in v0.0.4

func (m *MockKeyring) Delete(service, user string) error

func (*MockKeyring) Get added in v0.0.4

func (m *MockKeyring) Get(service, user string) (string, error)

func (*MockKeyring) Set added in v0.0.4

func (m *MockKeyring) Set(service, user, password string) error

type Once added in v0.0.3

type Once struct {
	// contains filtered or unexported fields
}

func (*Once) Do added in v0.0.3

func (o *Once) Do(f func())

func (*Once) Reset added in v0.0.3

func (o *Once) Reset()

type SystemKeyring added in v0.0.4

type SystemKeyring struct{}

func (*SystemKeyring) Delete added in v0.0.4

func (s *SystemKeyring) Delete(service, user string) error

func (*SystemKeyring) Get added in v0.0.4

func (s *SystemKeyring) Get(service, user string) (string, error)

func (*SystemKeyring) Set added in v0.0.4

func (s *SystemKeyring) Set(service, user, password string) error

Jump to

Keyboard shortcuts

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