本文整理汇总了Golang中github.com/docker/distribution/reference.WithName函数的典型用法代码示例。如果您正苦于以下问题:Golang WithName函数的具体用法?Golang WithName怎么用?Golang WithName使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WithName函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewRepositoryInfo
// NewRepositoryInfo validates and breaks down a repository name into a RepositoryInfo
func (config *ServiceConfig) NewRepositoryInfo(reposName reference.Named) (*RepositoryInfo, error) {
if err := validateNoSchema(reposName.Name()); err != nil {
return nil, err
}
repoInfo := &RepositoryInfo{}
var (
indexName string
err error
)
indexName, repoInfo.RemoteName, err = loadRepositoryName(reposName)
if err != nil {
return nil, err
}
repoInfo.Index, err = config.NewIndexInfo(indexName)
if err != nil {
return nil, err
}
if repoInfo.Index.Official {
repoInfo.LocalName, err = normalizeLibraryRepoName(repoInfo.RemoteName)
if err != nil {
return nil, err
}
repoInfo.RemoteName = repoInfo.LocalName
// If the normalized name does not contain a '/' (e.g. "foo")
// then it is an official repo.
if strings.IndexRune(repoInfo.RemoteName.Name(), '/') == -1 {
repoInfo.Official = true
// Fix up remote name for official repos.
repoInfo.RemoteName, err = reference.WithName("library/" + repoInfo.RemoteName.Name())
if err != nil {
return nil, err
}
}
repoInfo.CanonicalName, err = reference.WithName("docker.io/" + repoInfo.RemoteName.Name())
if err != nil {
return nil, err
}
} else {
repoInfo.LocalName, err = localNameFromRemote(repoInfo.Index.Name, repoInfo.RemoteName)
if err != nil {
return nil, err
}
repoInfo.CanonicalName = repoInfo.LocalName
}
return repoInfo, nil
}
示例2: normalizeLibraryRepoName
// normalizeLibraryRepoName removes the library prefix from
// the repository name for official repos.
func normalizeLibraryRepoName(name reference.Named) (reference.Named, error) {
if strings.HasPrefix(name.Name(), "library/") {
// If pull "library/foo", it's stored locally under "foo"
return reference.WithName(strings.SplitN(name.Name(), "/", 2)[1])
}
return name, nil
}
示例3: TestMirrorEndpointLookup
func TestMirrorEndpointLookup(t *testing.T) {
containsMirror := func(endpoints []APIEndpoint) bool {
for _, pe := range endpoints {
if pe.URL == "my.mirror" {
return true
}
}
return false
}
s := Service{Config: makeServiceConfig([]string{"my.mirror"}, nil)}
imageName, err := reference.WithName(IndexName + "/test/image")
if err != nil {
t.Error(err)
}
pushAPIEndpoints, err := s.LookupPushEndpoints(imageName)
if err != nil {
t.Fatal(err)
}
if containsMirror(pushAPIEndpoints) {
t.Fatal("Push endpoint should not contain mirror")
}
pullAPIEndpoints, err := s.LookupPullEndpoints(imageName)
if err != nil {
t.Fatal(err)
}
if !containsMirror(pullAPIEndpoints) {
t.Fatal("Pull endpoint should contain mirror")
}
}
示例4: TestValidateRepositoryName
func TestValidateRepositoryName(t *testing.T) {
validRepoNames := []string{
"docker/docker",
"library/debian",
"debian",
"docker.io/docker/docker",
"docker.io/library/debian",
"docker.io/debian",
"index.docker.io/docker/docker",
"index.docker.io/library/debian",
"index.docker.io/debian",
"127.0.0.1:5000/docker/docker",
"127.0.0.1:5000/library/debian",
"127.0.0.1:5000/debian",
"thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev",
}
invalidRepoNames := []string{
"https://github.com/docker/docker",
"docker/Docker",
"-docker",
"-docker/docker",
"-docker.io/docker/docker",
"docker///docker",
"docker.io/docker/Docker",
"docker.io/docker///docker",
"1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a",
"docker.io/1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a",
}
for _, name := range invalidRepoNames {
named, err := reference.WithName(name)
if err == nil {
err := ValidateRepositoryName(named)
assertNotEqual(t, err, nil, "Expected invalid repo name: "+name)
}
}
for _, name := range validRepoNames {
named, err := reference.WithName(name)
if err != nil {
t.Fatalf("could not parse valid name: %s", name)
}
err = ValidateRepositoryName(named)
assertEqual(t, err, nil, "Expected valid repo name: "+name)
}
}
示例5: legacyLoad
func (l *tarexporter) legacyLoad(tmpDir string, outStream io.Writer) error {
legacyLoadedMap := make(map[string]image.ID)
dirs, err := ioutil.ReadDir(tmpDir)
if err != nil {
return err
}
// every dir represents an image
for _, d := range dirs {
if d.IsDir() {
if err := l.legacyLoadImage(d.Name(), tmpDir, legacyLoadedMap); err != nil {
return err
}
}
}
// load tags from repositories file
repositoriesPath, err := safePath(tmpDir, legacyRepositoriesFileName)
if err != nil {
return err
}
repositoriesFile, err := os.Open(repositoriesPath)
if err != nil {
if !os.IsNotExist(err) {
return err
}
return repositoriesFile.Close()
}
defer repositoriesFile.Close()
repositories := make(map[string]map[string]string)
if err := json.NewDecoder(repositoriesFile).Decode(&repositories); err != nil {
return err
}
for name, tagMap := range repositories {
for tag, oldID := range tagMap {
imgID, ok := legacyLoadedMap[oldID]
if !ok {
return fmt.Errorf("invalid target ID: %v", oldID)
}
named, err := reference.WithName(name)
if err != nil {
return err
}
ref, err := reference.WithTag(named, tag)
if err != nil {
return err
}
l.setLoadedTag(ref, imgID, outStream)
}
}
return nil
}
示例6: WithName
// WithName returns a named object representing the given string. If the input
// is invalid ErrReferenceInvalidFormat will be returned.
func WithName(name string) (Named, error) {
name = normalize(name)
if err := validateName(name); err != nil {
return nil, err
}
r, err := distreference.WithName(name)
if err != nil {
return nil, err
}
return &namedRef{r}, nil
}
示例7: validateRemoteName
func validateRemoteName(remoteName string) error {
if !strings.Contains(remoteName, "/") {
// the repository name must not be a valid image ID
if err := image.ValidateID(remoteName); err == nil {
return fmt.Errorf("Invalid repository name (%s), cannot specify 64-byte hexadecimal strings", remoteName)
}
}
_, err := reference.WithName(remoteName)
return err
}
示例8: splitReposName
// splitReposName breaks a reposName into an index name and remote name
func splitReposName(reposName reference.Named) (indexName string, remoteName reference.Named, err error) {
var remoteNameStr string
indexName, remoteNameStr = reference.SplitHostname(reposName)
if indexName == "" || (!strings.Contains(indexName, ".") &&
!strings.Contains(indexName, ":") && indexName != "localhost") {
// This is a Docker Index repos (ex: samalba/hipache or ubuntu)
// 'docker.io'
indexName = IndexName
remoteName = reposName
} else {
remoteName, err = reference.WithName(remoteNameStr)
}
return
}
示例9: postImagesTag
func (s *router) postImagesTag(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := httputils.ParseForm(r); err != nil {
return err
}
repo := r.Form.Get("repo")
tag := r.Form.Get("tag")
newTag, err := reference.WithName(repo)
if err != nil {
return err
}
if tag != "" {
if newTag, err = reference.WithTag(newTag, tag); err != nil {
return err
}
}
if err := s.daemon.TagImage(newTag, vars["name"]); err != nil {
return err
}
w.WriteHeader(http.StatusCreated)
return nil
}
示例10: handlerPutTag
func handlerPutTag(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
vars := mux.Vars(r)
repositoryName, err := reference.WithName(vars["repository"])
if err != nil {
apiError(w, "Could not parse repository", 400)
return
}
repositoryName = NormalizeLocalName(repositoryName)
tagName := vars["tag"]
tags, exists := testRepositories[repositoryName.String()]
if !exists {
tags = make(map[string]string)
testRepositories[repositoryName.String()] = tags
}
tagValue := ""
readJSON(r, tagValue)
tags[tagName] = tagValue
writeResponse(w, true, 200)
}
示例11: handlerGetDeleteTags
func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
repositoryName, err := reference.WithName(mux.Vars(r)["repository"])
if err != nil {
apiError(w, "Could not parse repository", 400)
return
}
repositoryName = NormalizeLocalName(repositoryName)
tags, exists := testRepositories[repositoryName.String()]
if !exists {
apiError(w, "Repository not found", 404)
return
}
if r.Method == "DELETE" {
delete(testRepositories, repositoryName.String())
writeResponse(w, true, 200)
return
}
writeResponse(w, tags, 200)
}
示例12: handlerGetTag
func handlerGetTag(w http.ResponseWriter, r *http.Request) {
if !requiresAuth(w, r) {
return
}
vars := mux.Vars(r)
repositoryName, err := reference.WithName(vars["repository"])
if err != nil {
apiError(w, "Could not parse repository", 400)
return
}
repositoryName = NormalizeLocalName(repositoryName)
tagName := vars["tag"]
tags, exists := testRepositories[repositoryName.String()]
if !exists {
apiError(w, "Repository not found", 404)
return
}
tag, exists := tags[tagName]
if !exists {
apiError(w, "Tag not found", 404)
return
}
writeResponse(w, tag, 200)
}
示例13: Commit
// Commit creates a new filesystem image from the current state of a container.
// The image can optionally be tagged into a repository.
func (daemon *Daemon) Commit(name string, c *ContainerCommitConfig) (string, error) {
container, err := daemon.Get(name)
if err != nil {
return "", err
}
// It is not possible to commit a running container on Windows
if runtime.GOOS == "windows" && container.IsRunning() {
return "", fmt.Errorf("Windows does not support commit of a running container")
}
if c.Pause && !container.isPaused() {
daemon.containerPause(container)
defer daemon.containerUnpause(container)
}
if c.MergeConfigs {
if err := runconfig.Merge(c.Config, container.Config); err != nil {
return "", err
}
}
rwTar, err := daemon.exportContainerRw(container)
if err != nil {
return "", err
}
defer func() {
if rwTar != nil {
rwTar.Close()
}
}()
var history []image.History
rootFS := image.NewRootFS()
if container.ImageID != "" {
img, err := daemon.imageStore.Get(container.ImageID)
if err != nil {
return "", err
}
history = img.History
rootFS = img.RootFS
}
l, err := daemon.layerStore.Register(rwTar, rootFS.ChainID())
if err != nil {
return "", err
}
defer layer.ReleaseAndLog(daemon.layerStore, l)
h := image.History{
Author: c.Author,
Created: time.Now().UTC(),
CreatedBy: strings.Join(container.Config.Cmd.Slice(), " "),
Comment: c.Comment,
EmptyLayer: true,
}
if diffID := l.DiffID(); layer.DigestSHA256EmptyTar != diffID {
h.EmptyLayer = false
rootFS.Append(diffID)
}
history = append(history, h)
config, err := json.Marshal(&image.Image{
V1Image: image.V1Image{
DockerVersion: dockerversion.Version,
Config: c.Config,
Architecture: runtime.GOARCH,
OS: runtime.GOOS,
Container: container.ID,
ContainerConfig: *container.Config,
Author: c.Author,
Created: h.Created,
},
RootFS: rootFS,
History: history,
})
if err != nil {
return "", err
}
id, err := daemon.imageStore.Create(config)
if err != nil {
return "", err
}
if container.ImageID != "" {
if err := daemon.imageStore.SetParent(id, container.ImageID); err != nil {
return "", err
}
}
if c.Repo != "" {
newTag, err := reference.WithName(c.Repo) // todo: should move this to API layer
if err != nil {
//.........这里部分代码省略.........
示例14: Upload
func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) {
if fs, ok := pd.layer.(distribution.Describable); ok {
if d := fs.Descriptor(); len(d.URLs) > 0 {
progress.Update(progressOutput, pd.ID(), "Skipped foreign layer")
return d, nil
}
}
diffID := pd.DiffID()
pd.pushState.Lock()
if descriptor, ok := pd.pushState.remoteLayers[diffID]; ok {
// it is already known that the push is not needed and
// therefore doing a stat is unnecessary
pd.pushState.Unlock()
progress.Update(progressOutput, pd.ID(), "Layer already exists")
return descriptor, nil
}
pd.pushState.Unlock()
// Do we have any metadata associated with this layer's DiffID?
v2Metadata, err := pd.v2MetadataService.GetMetadata(diffID)
if err == nil {
descriptor, exists, err := layerAlreadyExists(ctx, v2Metadata, pd.repoInfo, pd.repo, pd.pushState)
if err != nil {
progress.Update(progressOutput, pd.ID(), "Image push failed")
return distribution.Descriptor{}, retryOnError(err)
}
if exists {
progress.Update(progressOutput, pd.ID(), "Layer already exists")
pd.pushState.Lock()
pd.pushState.remoteLayers[diffID] = descriptor
pd.pushState.Unlock()
return descriptor, nil
}
}
logrus.Debugf("Pushing layer: %s", diffID)
// if digest was empty or not saved, or if blob does not exist on the remote repository,
// then push the blob.
bs := pd.repo.Blobs(ctx)
var layerUpload distribution.BlobWriter
mountAttemptsRemaining := 3
// Attempt to find another repository in the same registry to mount the layer
// from to avoid an unnecessary upload.
// Note: metadata is stored from oldest to newest, so we iterate through this
// slice in reverse to maximize our chances of the blob still existing in the
// remote repository.
for i := len(v2Metadata) - 1; i >= 0 && mountAttemptsRemaining > 0; i-- {
mountFrom := v2Metadata[i]
sourceRepo, err := reference.ParseNamed(mountFrom.SourceRepository)
if err != nil {
continue
}
if pd.repoInfo.Hostname() != sourceRepo.Hostname() {
// don't mount blobs from another registry
continue
}
namedRef, err := reference.WithName(mountFrom.SourceRepository)
if err != nil {
continue
}
// TODO (brianbland): We need to construct a reference where the Name is
// only the full remote name, so clean this up when distribution has a
// richer reference package
remoteRef, err := distreference.WithName(namedRef.RemoteName())
if err != nil {
continue
}
canonicalRef, err := distreference.WithDigest(remoteRef, mountFrom.Digest)
if err != nil {
continue
}
logrus.Debugf("attempting to mount layer %s (%s) from %s", diffID, mountFrom.Digest, sourceRepo.FullName())
layerUpload, err = bs.Create(ctx, client.WithMountFrom(canonicalRef))
switch err := err.(type) {
case distribution.ErrBlobMounted:
progress.Updatef(progressOutput, pd.ID(), "Mounted from %s", err.From.Name())
err.Descriptor.MediaType = schema2.MediaTypeLayer
pd.pushState.Lock()
pd.pushState.confirmedV2 = true
pd.pushState.remoteLayers[diffID] = err.Descriptor
pd.pushState.Unlock()
// Cache mapping from this layer's DiffID to the blobsum
if err := pd.v2MetadataService.Add(diffID, metadata.V2Metadata{Digest: mountFrom.Digest, SourceRepository: pd.repoInfo.FullName()}); err != nil {
return distribution.Descriptor{}, xfer.DoNotRetry{Err: err}
}
return err.Descriptor, nil
//.........这里部分代码省略.........
示例15: localNameFromRemote
// localNameFromRemote combines the index name and the repo remote name
// to generate a repo local name.
func localNameFromRemote(indexName string, remoteName reference.Named) (reference.Named, error) {
return reference.WithName(indexName + "/" + remoteName.Name())
}