Vendor in latest containers/(buildah, image, common)

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>
This commit is contained in:
Daniel J Walsh
2022-12-21 06:12:45 -05:00
parent aecb5d3853
commit bfec23c363
13 changed files with 176 additions and 112 deletions

10
go.mod
View File

@ -11,10 +11,10 @@ require (
github.com/container-orchestrated-devices/container-device-interface v0.5.3
github.com/containernetworking/cni v1.1.2
github.com/containernetworking/plugins v1.1.1
github.com/containers/buildah v1.28.1-0.20221219201600-ca578b290144
github.com/containers/common v0.50.2-0.20221216120044-ef7e0d6f3002
github.com/containers/buildah v1.28.1-0.20221221082547-8403b6ebc13d
github.com/containers/common v0.50.2-0.20221219181826-6d0b8687fab6
github.com/containers/conmon v2.0.20+incompatible
github.com/containers/image/v5 v5.23.1-0.20221216122512-3963f229df32
github.com/containers/image/v5 v5.23.1-0.20221221081306-dc161470c86a
github.com/containers/ocicrypt v1.1.6
github.com/containers/psgo v1.8.0
github.com/containers/storage v1.44.1-0.20221215163359-b0949d90efad
@ -78,7 +78,7 @@ require (
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
github.com/chzyer/readline v1.5.1 // indirect
github.com/containerd/cgroups v1.0.4 // indirect
github.com/containerd/containerd v1.6.13 // indirect
github.com/containerd/containerd v1.6.14 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.13.0 // indirect
github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a // indirect
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f // indirect
@ -104,7 +104,7 @@ require (
github.com/kr/fs v0.1.0 // indirect
github.com/letsencrypt/boulder v0.0.0-20221109233200-85aa52084eaf // indirect
github.com/manifoldco/promptui v0.9.0 // indirect
github.com/mattn/go-runewidth v0.0.13 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/miekg/pkcs11 v1.1.1 // indirect
github.com/mistifyio/go-zfs/v3 v3.0.0 // indirect
github.com/moby/sys/mount v0.3.3 // indirect

19
go.sum
View File

@ -203,8 +203,8 @@ github.com/containerd/containerd v1.5.0-rc.0/go.mod h1:V/IXoMqNGgBlabz3tHD2TWDoT
github.com/containerd/containerd v1.5.1/go.mod h1:0DOxVqwDy2iZvrZp2JUx/E+hS0UNTVn7dJnIOwtYR4g=
github.com/containerd/containerd v1.5.7/go.mod h1:gyvv6+ugqY25TiXxcZC3L5yOeYgEw0QMhscqVp1AR9c=
github.com/containerd/containerd v1.5.9/go.mod h1:fvQqCfadDGga5HZyn3j4+dx56qj2I9YwBrlSdalvJYQ=
github.com/containerd/containerd v1.6.13 h1:7llWEzjLH/fao0f2lppn1L6NhjsvxqMdUQa2mgVCs+U=
github.com/containerd/containerd v1.6.13/go.mod h1:vDm+BbU+dD9uvuUlHr+KmcY0HKX8WDyI6dzJjNi4ee8=
github.com/containerd/containerd v1.6.14 h1:W+d0AJKVG3ioTZZyQwcw1Y3vvo6ZDYzAcjDcY4tkgGI=
github.com/containerd/containerd v1.6.14/go.mod h1:U2NnBPIhzJDm59xF7xB2MMHnKtggpZ+phKg8o2TKj2c=
github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
github.com/containerd/continuity v0.0.0-20190815185530-f2a389ac0a02/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
github.com/containerd/continuity v0.0.0-20191127005431-f65d91d395eb/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
@ -262,14 +262,14 @@ github.com/containernetworking/plugins v0.8.6/go.mod h1:qnw5mN19D8fIwkqW7oHHYDHV
github.com/containernetworking/plugins v0.9.1/go.mod h1:xP/idU2ldlzN6m4p5LmGiwRDjeJr6FLK6vuiUwoH7P8=
github.com/containernetworking/plugins v1.1.1 h1:+AGfFigZ5TiQH00vhR8qPeSatj53eNGz0C1d3wVYlHE=
github.com/containernetworking/plugins v1.1.1/go.mod h1:Sr5TH/eBsGLXK/h71HeLfX19sZPp3ry5uHSkI4LPxV8=
github.com/containers/buildah v1.28.1-0.20221219201600-ca578b290144 h1:2RQIBdC4z6JeUysEBFmdyRjeQL+XHikWGxDoWiPDsAw=
github.com/containers/buildah v1.28.1-0.20221219201600-ca578b290144/go.mod h1:UtGNHlAwNF1WV/Z63R/sPgxItTog/YPi/1gSfZ8ZdpE=
github.com/containers/common v0.50.2-0.20221216120044-ef7e0d6f3002 h1:wvT0IrvGcZ0tEAvF1CYjaI6xjQjXr4vDnrlHRAYEo0Q=
github.com/containers/common v0.50.2-0.20221216120044-ef7e0d6f3002/go.mod h1:EhEJRALj8qJWhnnzk6nY6wqDkSjfGpU2DwcLb9UpVoM=
github.com/containers/buildah v1.28.1-0.20221221082547-8403b6ebc13d h1:OyqOrN7QTtA7g5ZgQkV5lChAn5cVQB0dnVqjNd93DuQ=
github.com/containers/buildah v1.28.1-0.20221221082547-8403b6ebc13d/go.mod h1:PAftqTiRApPwzIaY42fDm/FRqOuLgd+ZZtVzIu3/eco=
github.com/containers/common v0.50.2-0.20221219181826-6d0b8687fab6 h1:YHKUFceIwqDEiILofIwhuGb1L/WqOKDkNFeIXNLzDd0=
github.com/containers/common v0.50.2-0.20221219181826-6d0b8687fab6/go.mod h1:zOsh8liNqXFOnudQxZ4nsXl1oxbCQ69OxkwuQlmEQ2U=
github.com/containers/conmon v2.0.20+incompatible h1:YbCVSFSCqFjjVwHTPINGdMX1F6JXHGTUje2ZYobNrkg=
github.com/containers/conmon v2.0.20+incompatible/go.mod h1:hgwZ2mtuDrppv78a/cOBNiCm6O0UMWGx1mu7P00nu5I=
github.com/containers/image/v5 v5.23.1-0.20221216122512-3963f229df32 h1:buu4aAeaGmzQARE8fKCgrv8LozD7L1mmWR0NUvndUDE=
github.com/containers/image/v5 v5.23.1-0.20221216122512-3963f229df32/go.mod h1:9UsDb0O3SOR9NNceSEjjwE8jgHrvuEO54QeeyQj+XGo=
github.com/containers/image/v5 v5.23.1-0.20221221081306-dc161470c86a h1:bE3qm7hqQ4dw7Qlm8M9c1v/q7Oxa1CWAC4eR8PMPVGk=
github.com/containers/image/v5 v5.23.1-0.20221221081306-dc161470c86a/go.mod h1:6gb7ZBQbqoAq4Rf27qeNwyURKpKXuQc6Bpu4pBGdMdw=
github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a h1:spAGlqziZjCJL25C6F1zsQY05tfCKE9F5YwtEWWe6hU=
github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a/go.mod h1:9rfv8iPl1ZP7aqh9YA68wnZv2NUDbXdcdPHVz0pFbPY=
github.com/containers/ocicrypt v1.0.1/go.mod h1:MeJDzk1RJHv89LjsH0Sp5KTY3ZYkjXO/C+bKAeWFIrc=
@ -653,8 +653,9 @@ github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o=
github.com/mattn/go-shellwords v1.0.6/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o=
github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk=

View File

@ -32,11 +32,6 @@ type dockerConfigFile struct {
CredHelpers map[string]string `json:"credHelpers,omitempty"`
}
type authPath struct {
path string
legacyFormat bool
}
var (
defaultPerUIDPathFormat = filepath.FromSlash("/run/containers/%d/auth.json")
xdgConfigHomePath = filepath.FromSlash("containers/auth.json")
@ -52,6 +47,19 @@ var (
ErrNotSupported = errors.New("not supported")
)
// authPath combines a path to a file with container registry access keys,
// along with expected properties of that path (currently just whether it's)
// legacy format or not.
type authPath struct {
path string
legacyFormat bool
}
// newAuthPathDefault constructs an authPath in non-legacy format.
func newAuthPathDefault(path string) authPath {
return authPath{path: path, legacyFormat: false}
}
// SetCredentials stores the username and password in a location
// appropriate for sys and the users configuration.
// A valid key is a repository, a namespace within a registry, or a registry hostname;
@ -149,8 +157,8 @@ func GetAllCredentials(sys *types.SystemContext) (map[string]types.DockerAuthCon
// Special-case the built-in helper for auth files.
case sysregistriesv2.AuthenticationFileHelper:
for _, path := range getAuthFilePaths(sys, homedir.Get()) {
// readJSONFile returns an empty map in case the path doesn't exist.
auths, err := readJSONFile(path.path, path.legacyFormat)
// parse returns an empty map in case the path doesn't exist.
auths, err := path.parse()
if err != nil {
return nil, fmt.Errorf("reading JSON file %q: %w", path.path, err)
}
@ -208,9 +216,9 @@ func GetAllCredentials(sys *types.SystemContext) (map[string]types.DockerAuthCon
// by tests.
func getAuthFilePaths(sys *types.SystemContext, homeDir string) []authPath {
paths := []authPath{}
pathToAuth, lf, err := getPathToAuth(sys)
pathToAuth, err := getPathToAuth(sys)
if err == nil {
paths = append(paths, authPath{path: pathToAuth, legacyFormat: lf})
paths = append(paths, pathToAuth)
} else {
// Error means that the path set for XDG_RUNTIME_DIR does not exist
// but we don't want to completely fail in the case that the user is pulling a public image
@ -222,14 +230,12 @@ func getAuthFilePaths(sys *types.SystemContext, homeDir string) []authPath {
if xdgCfgHome == "" {
xdgCfgHome = filepath.Join(homeDir, ".config")
}
paths = append(paths, authPath{path: filepath.Join(xdgCfgHome, xdgConfigHomePath), legacyFormat: false})
paths = append(paths, newAuthPathDefault(filepath.Join(xdgCfgHome, xdgConfigHomePath)))
if dockerConfig := os.Getenv("DOCKER_CONFIG"); dockerConfig != "" {
paths = append(paths,
authPath{path: filepath.Join(dockerConfig, "config.json"), legacyFormat: false},
)
paths = append(paths, newAuthPathDefault(filepath.Join(dockerConfig, "config.json")))
} else {
paths = append(paths,
authPath{path: filepath.Join(homeDir, dockerHomePath), legacyFormat: false},
newAuthPathDefault(filepath.Join(homeDir, dockerHomePath)),
)
}
paths = append(paths,
@ -281,7 +287,7 @@ func getCredentialsWithHomeDir(sys *types.SystemContext, key, homeDir string) (t
// Anonymous function to query credentials from auth files.
getCredentialsFromAuthFiles := func() (types.DockerAuthConfig, string, error) {
for _, path := range getAuthFilePaths(sys, homeDir) {
authConfig, err := findCredentialsInFile(key, registry, path.path, path.legacyFormat)
authConfig, err := findCredentialsInFile(key, registry, path)
if err != nil {
return types.DockerAuthConfig{}, "", err
}
@ -502,26 +508,26 @@ func listAuthsFromCredHelper(credHelper string) (map[string]string, error) {
// getPathToAuth gets the path of the auth.json file used for reading and writing credentials
// returns the path, and a bool specifies whether the file is in legacy format
func getPathToAuth(sys *types.SystemContext) (string, bool, error) {
func getPathToAuth(sys *types.SystemContext) (authPath, error) {
return getPathToAuthWithOS(sys, runtime.GOOS)
}
// getPathToAuthWithOS is an internal implementation detail of getPathToAuth,
// it exists only to allow testing it with an artificial runtime.GOOS.
func getPathToAuthWithOS(sys *types.SystemContext, goOS string) (string, bool, error) {
func getPathToAuthWithOS(sys *types.SystemContext, goOS string) (authPath, error) {
if sys != nil {
if sys.AuthFilePath != "" {
return sys.AuthFilePath, false, nil
return newAuthPathDefault(sys.AuthFilePath), nil
}
if sys.LegacyFormatAuthFilePath != "" {
return sys.LegacyFormatAuthFilePath, true, nil
return authPath{path: sys.LegacyFormatAuthFilePath, legacyFormat: true}, nil
}
if sys.RootForImplicitAbsolutePaths != "" {
return filepath.Join(sys.RootForImplicitAbsolutePaths, fmt.Sprintf(defaultPerUIDPathFormat, os.Getuid())), false, nil
return newAuthPathDefault(filepath.Join(sys.RootForImplicitAbsolutePaths, fmt.Sprintf(defaultPerUIDPathFormat, os.Getuid()))), nil
}
}
if goOS == "windows" || goOS == "darwin" {
return filepath.Join(homedir.Get(), nonLinuxAuthFilePath), false, nil
return newAuthPathDefault(filepath.Join(homedir.Get(), nonLinuxAuthFilePath)), nil
}
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
@ -533,20 +539,20 @@ func getPathToAuthWithOS(sys *types.SystemContext, goOS string) (string, bool, e
// This means the user set the XDG_RUNTIME_DIR variable and either forgot to create the directory
// or made a typo while setting the environment variable,
// so return an error referring to $XDG_RUNTIME_DIR instead of xdgRuntimeDirPath inside.
return "", false, fmt.Errorf("%q directory set by $XDG_RUNTIME_DIR does not exist. Either create the directory or unset $XDG_RUNTIME_DIR.: %w", runtimeDir, err)
return authPath{}, fmt.Errorf("%q directory set by $XDG_RUNTIME_DIR does not exist. Either create the directory or unset $XDG_RUNTIME_DIR.: %w", runtimeDir, err)
} // else ignore err and let the caller fail accessing xdgRuntimeDirPath.
return filepath.Join(runtimeDir, xdgRuntimeDirPath), false, nil
return newAuthPathDefault(filepath.Join(runtimeDir, xdgRuntimeDirPath)), nil
}
return fmt.Sprintf(defaultPerUIDPathFormat, os.Getuid()), false, nil
return newAuthPathDefault(fmt.Sprintf(defaultPerUIDPathFormat, os.Getuid())), nil
}
// readJSONFile unmarshals the authentications stored in the auth.json file and returns it
// parse unmarshals the authentications stored in the auth.json file and returns it
// or returns an empty dockerConfigFile data structure if auth.json does not exist
// if the file exists and is empty, readJSONFile returns an error
func readJSONFile(path string, legacyFormat bool) (dockerConfigFile, error) {
// if the file exists and is empty, this function returns an error.
func (path authPath) parse() (dockerConfigFile, error) {
var auths dockerConfigFile
raw, err := os.ReadFile(path)
raw, err := os.ReadFile(path.path)
if err != nil {
if os.IsNotExist(err) {
auths.AuthConfigs = map[string]dockerAuthConfig{}
@ -555,15 +561,15 @@ func readJSONFile(path string, legacyFormat bool) (dockerConfigFile, error) {
return dockerConfigFile{}, err
}
if legacyFormat {
if path.legacyFormat {
if err = json.Unmarshal(raw, &auths.AuthConfigs); err != nil {
return dockerConfigFile{}, fmt.Errorf("unmarshaling JSON at %q: %w", path, err)
return dockerConfigFile{}, fmt.Errorf("unmarshaling JSON at %q: %w", path.path, err)
}
return auths, nil
}
if err = json.Unmarshal(raw, &auths); err != nil {
return dockerConfigFile{}, fmt.Errorf("unmarshaling JSON at %q: %w", path, err)
return dockerConfigFile{}, fmt.Errorf("unmarshaling JSON at %q: %w", path.path, err)
}
if auths.AuthConfigs == nil {
@ -583,41 +589,41 @@ func readJSONFile(path string, legacyFormat bool) (dockerConfigFile, error) {
// The editor may also return a human-readable description of the updated location; if it is "",
// the file itself is used.
func modifyJSON(sys *types.SystemContext, editor func(auths *dockerConfigFile) (bool, string, error)) (string, error) {
path, legacyFormat, err := getPathToAuth(sys)
path, err := getPathToAuth(sys)
if err != nil {
return "", err
}
if legacyFormat {
return "", fmt.Errorf("writes to %s using legacy format are not supported", path)
if path.legacyFormat {
return "", fmt.Errorf("writes to %s using legacy format are not supported", path.path)
}
dir := filepath.Dir(path)
dir := filepath.Dir(path.path)
if err = os.MkdirAll(dir, 0700); err != nil {
return "", err
}
auths, err := readJSONFile(path, false)
auths, err := path.parse()
if err != nil {
return "", fmt.Errorf("reading JSON file %q: %w", path, err)
return "", fmt.Errorf("reading JSON file %q: %w", path.path, err)
}
updated, description, err := editor(&auths)
if err != nil {
return "", fmt.Errorf("updating %q: %w", path, err)
return "", fmt.Errorf("updating %q: %w", path.path, err)
}
if updated {
newData, err := json.MarshalIndent(auths, "", "\t")
if err != nil {
return "", fmt.Errorf("marshaling JSON %q: %w", path, err)
return "", fmt.Errorf("marshaling JSON %q: %w", path.path, err)
}
if err = ioutils.AtomicWriteFile(path, newData, 0600); err != nil {
return "", fmt.Errorf("writing to file %q: %w", path, err)
if err = ioutils.AtomicWriteFile(path.path, newData, 0600); err != nil {
return "", fmt.Errorf("writing to file %q: %w", path.path, err)
}
}
if description == "" {
description = path
description = path.path
}
return description, nil
}
@ -671,17 +677,17 @@ func deleteAuthFromCredHelper(credHelper, registry string) error {
// findCredentialsInFile looks for credentials matching "key"
// (which is "registry" or a namespace in "registry") in "path".
func findCredentialsInFile(key, registry, path string, legacyFormat bool) (types.DockerAuthConfig, error) {
auths, err := readJSONFile(path, legacyFormat)
func findCredentialsInFile(key, registry string, path authPath) (types.DockerAuthConfig, error) {
auths, err := path.parse()
if err != nil {
return types.DockerAuthConfig{}, fmt.Errorf("reading JSON file %q: %w", path, err)
return types.DockerAuthConfig{}, fmt.Errorf("reading JSON file %q: %w", path.path, err)
}
// First try cred helpers. They should always be normalized.
// This intentionally uses "registry", not "key"; we don't support namespaced
// credentials in helpers.
if ch, exists := auths.CredHelpers[registry]; exists {
logrus.Debugf("Looking up in credential helper %s based on credHelpers entry in %s", ch, path)
logrus.Debugf("Looking up in credential helper %s based on credHelpers entry in %s", ch, path.path)
return getAuthFromCredHelper(ch, registry)
}
@ -689,7 +695,7 @@ func findCredentialsInFile(key, registry, path string, legacyFormat bool) (types
// (This is not a feature of ~/.docker/config.json; we support it even for
// those files as an extension.)
var keys []string
if !legacyFormat {
if !path.legacyFormat {
keys = authKeysForKey(key)
} else {
keys = []string{registry}
@ -699,7 +705,7 @@ func findCredentialsInFile(key, registry, path string, legacyFormat bool) (types
// keys we prefer exact matches as well.
for _, key := range keys {
if val, exists := auths.AuthConfigs[key]; exists {
return decodeDockerAuth(path, key, val)
return decodeDockerAuth(path.path, key, val)
}
}
@ -713,14 +719,14 @@ func findCredentialsInFile(key, registry, path string, legacyFormat bool) (types
// so account for that as well.
registry = normalizeRegistry(registry)
for k, v := range auths.AuthConfigs {
if normalizeAuthFileKey(k, legacyFormat) == registry {
return decodeDockerAuth(path, k, v)
if normalizeAuthFileKey(k, path.legacyFormat) == registry {
return decodeDockerAuth(path.path, k, v)
}
}
// Only log this if we found nothing; getCredentialsWithHomeDir logs the
// source of found data.
logrus.Debugf("No credentials matching %s found in %s", key, path)
logrus.Debugf("No credentials matching %s found in %s", key, path.path)
return types.DockerAuthConfig{}, nil
}

View File

@ -335,7 +335,7 @@ func loadShortNameAliasConf(confPath string) (*shortNameAliasConf, *shortNameAli
return &conf, cache, nil
}
func shortNameAliasesConfPathAndLock(ctx *types.SystemContext) (string, lockfile.Locker, error) {
func shortNameAliasesConfPathAndLock(ctx *types.SystemContext) (string, *lockfile.LockFile, error) {
shortNameAliasesConfPath, err := shortNameAliasesConfPath(ctx)
if err != nil {
return "", nil, err
@ -346,6 +346,6 @@ func shortNameAliasesConfPathAndLock(ctx *types.SystemContext) (string, lockfile
}
lockPath := shortNameAliasesConfPath + ".lock"
locker, err := lockfile.GetLockfile(lockPath)
locker, err := lockfile.GetLockFile(lockPath)
return shortNameAliasesConfPath, locker, err
}

View File

@ -1,16 +0,0 @@
language: go
sudo: false
go:
- 1.13.x
- tip
before_install:
- go get -t -v ./...
script:
- go generate
- git diff --cached --exit-code
- ./go.test.sh
after_success:
- bash <(curl -s https://codecov.io/bash)

View File

@ -1,7 +1,7 @@
go-runewidth
============
[![Build Status](https://travis-ci.org/mattn/go-runewidth.png?branch=master)](https://travis-ci.org/mattn/go-runewidth)
[![Build Status](https://github.com/mattn/go-runewidth/workflows/test/badge.svg?branch=master)](https://github.com/mattn/go-runewidth/actions?query=workflow%3Atest)
[![Codecov](https://codecov.io/gh/mattn/go-runewidth/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-runewidth)
[![GoDoc](https://godoc.org/github.com/mattn/go-runewidth?status.svg)](http://godoc.org/github.com/mattn/go-runewidth)
[![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-runewidth)](https://goreportcard.com/report/github.com/mattn/go-runewidth)

View File

@ -1,12 +0,0 @@
#!/usr/bin/env bash
set -e
echo "" > coverage.txt
for d in $(go list ./... | grep -v vendor); do
go test -race -coverprofile=profile.out -covermode=atomic "$d"
if [ -f profile.out ]; then
cat profile.out >> coverage.txt
rm profile.out
fi
done

View File

@ -2,6 +2,7 @@ package runewidth
import (
"os"
"strings"
"github.com/rivo/uniseg"
)
@ -34,7 +35,13 @@ func handleEnv() {
EastAsianWidth = env == "1"
}
// update DefaultCondition
DefaultCondition.EastAsianWidth = EastAsianWidth
if DefaultCondition.EastAsianWidth != EastAsianWidth {
DefaultCondition.EastAsianWidth = EastAsianWidth
if len(DefaultCondition.combinedLut) > 0 {
DefaultCondition.combinedLut = DefaultCondition.combinedLut[:0]
CreateLUT()
}
}
}
type interval struct {
@ -89,6 +96,7 @@ var nonprint = table{
// Condition have flag EastAsianWidth whether the current locale is CJK or not.
type Condition struct {
combinedLut []byte
EastAsianWidth bool
StrictEmojiNeutral bool
}
@ -104,10 +112,16 @@ func NewCondition() *Condition {
// RuneWidth returns the number of cells in r.
// See http://www.unicode.org/reports/tr11/
func (c *Condition) RuneWidth(r rune) int {
if r < 0 || r > 0x10FFFF {
return 0
}
if len(c.combinedLut) > 0 {
return int(c.combinedLut[r>>1]>>(uint(r&1)*4)) & 3
}
// optimized version, verified by TestRuneWidthChecksums()
if !c.EastAsianWidth {
switch {
case r < 0x20 || r > 0x10FFFF:
case r < 0x20:
return 0
case (r >= 0x7F && r <= 0x9F) || r == 0xAD: // nonprint
return 0
@ -124,7 +138,7 @@ func (c *Condition) RuneWidth(r rune) int {
}
} else {
switch {
case r < 0 || r > 0x10FFFF || inTables(r, nonprint, combining):
case inTables(r, nonprint, combining):
return 0
case inTable(r, narrow):
return 1
@ -138,6 +152,27 @@ func (c *Condition) RuneWidth(r rune) int {
}
}
// CreateLUT will create an in-memory lookup table of 557056 bytes for faster operation.
// This should not be called concurrently with other operations on c.
// If options in c is changed, CreateLUT should be called again.
func (c *Condition) CreateLUT() {
const max = 0x110000
lut := c.combinedLut
if len(c.combinedLut) != 0 {
// Remove so we don't use it.
c.combinedLut = nil
} else {
lut = make([]byte, max/2)
}
for i := range lut {
i32 := int32(i * 2)
x0 := c.RuneWidth(i32)
x1 := c.RuneWidth(i32 + 1)
lut[i] = uint8(x0) | uint8(x1)<<4
}
c.combinedLut = lut
}
// StringWidth return width as you can see
func (c *Condition) StringWidth(s string) (width int) {
g := uniseg.NewGraphemes(s)
@ -180,11 +215,47 @@ func (c *Condition) Truncate(s string, w int, tail string) string {
return s[:pos] + tail
}
// TruncateLeft cuts w cells from the beginning of the `s`.
func (c *Condition) TruncateLeft(s string, w int, prefix string) string {
if c.StringWidth(s) <= w {
return prefix
}
var width int
pos := len(s)
g := uniseg.NewGraphemes(s)
for g.Next() {
var chWidth int
for _, r := range g.Runes() {
chWidth = c.RuneWidth(r)
if chWidth > 0 {
break // See StringWidth() for details.
}
}
if width+chWidth > w {
if width < w {
_, pos = g.Positions()
prefix += strings.Repeat(" ", width+chWidth-w)
} else {
pos, _ = g.Positions()
}
break
}
width += chWidth
}
return prefix + s[pos:]
}
// Wrap return string wrapped with w cells
func (c *Condition) Wrap(s string, w int) string {
width := 0
out := ""
for _, r := range []rune(s) {
for _, r := range s {
cw := c.RuneWidth(r)
if r == '\n' {
out += string(r)
@ -257,6 +328,11 @@ func Truncate(s string, w int, tail string) string {
return DefaultCondition.Truncate(s, w, tail)
}
// TruncateLeft cuts w cells from the beginning of the `s`.
func TruncateLeft(s string, w int, prefix string) string {
return DefaultCondition.TruncateLeft(s, w, prefix)
}
// Wrap return string wrapped with w cells
func Wrap(s string, w int) string {
return DefaultCondition.Wrap(s, w)
@ -271,3 +347,12 @@ func FillLeft(s string, w int) string {
func FillRight(s string, w int) string {
return DefaultCondition.FillRight(s, w)
}
// CreateLUT will create an in-memory lookup table of 557055 bytes for faster operation.
// This should not be called concurrently with other operations.
func CreateLUT() {
if len(DefaultCondition.combinedLut) > 0 {
return
}
DefaultCondition.CreateLUT()
}

View File

@ -1,3 +1,4 @@
//go:build appengine
// +build appengine
package runewidth

View File

@ -1,5 +1,5 @@
// +build js
// +build !appengine
//go:build js && !appengine
// +build js,!appengine
package runewidth

View File

@ -1,6 +1,5 @@
// +build !windows
// +build !js
// +build !appengine
//go:build !windows && !js && !appengine
// +build !windows,!js,!appengine
package runewidth

View File

@ -1,5 +1,5 @@
// +build windows
// +build !appengine
//go:build windows && !appengine
// +build windows,!appengine
package runewidth

10
vendor/modules.txt vendored
View File

@ -69,7 +69,7 @@ github.com/container-orchestrated-devices/container-device-interface/specs-go
# github.com/containerd/cgroups v1.0.4
## explicit; go 1.17
github.com/containerd/cgroups/stats/v1
# github.com/containerd/containerd v1.6.13
# github.com/containerd/containerd v1.6.14
## explicit; go 1.17
github.com/containerd/containerd/errdefs
github.com/containerd/containerd/log
@ -95,7 +95,7 @@ github.com/containernetworking/cni/pkg/version
# github.com/containernetworking/plugins v1.1.1
## explicit; go 1.17
github.com/containernetworking/plugins/pkg/ns
# github.com/containers/buildah v1.28.1-0.20221219201600-ca578b290144
# github.com/containers/buildah v1.28.1-0.20221221082547-8403b6ebc13d
## explicit; go 1.17
github.com/containers/buildah
github.com/containers/buildah/bind
@ -118,7 +118,7 @@ github.com/containers/buildah/pkg/rusage
github.com/containers/buildah/pkg/sshagent
github.com/containers/buildah/pkg/util
github.com/containers/buildah/util
# github.com/containers/common v0.50.2-0.20221216120044-ef7e0d6f3002
# github.com/containers/common v0.50.2-0.20221219181826-6d0b8687fab6
## explicit; go 1.17
github.com/containers/common/libimage
github.com/containers/common/libimage/define
@ -172,7 +172,7 @@ github.com/containers/common/version
# github.com/containers/conmon v2.0.20+incompatible
## explicit
github.com/containers/conmon/runner/config
# github.com/containers/image/v5 v5.23.1-0.20221216122512-3963f229df32
# github.com/containers/image/v5 v5.23.1-0.20221221081306-dc161470c86a
## explicit; go 1.17
github.com/containers/image/v5/copy
github.com/containers/image/v5/directory
@ -515,7 +515,7 @@ github.com/letsencrypt/boulder/sa/proto
github.com/manifoldco/promptui
github.com/manifoldco/promptui/list
github.com/manifoldco/promptui/screenbuf
# github.com/mattn/go-runewidth v0.0.13
# github.com/mattn/go-runewidth v0.0.14
## explicit; go 1.9
github.com/mattn/go-runewidth
# github.com/mattn/go-shellwords v1.0.12