Skip to content
This repository has been archived by the owner on Jun 4, 2021. It is now read-only.

Update code to be Python3 compatible #85

Merged
merged 2 commits into from
Jun 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions client/docker_creds_.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@
# limitations under the License.
"""This package exposes credentials for talking to a Docker registry."""

from __future__ import absolute_import
from __future__ import division

from __future__ import print_function

import abc
import base64
import errno
import io
import json
import logging
import os
Expand All @@ -27,11 +31,11 @@
import httplib2
from oauth2client import client as oauth2client

import six

class Provider(object):
"""Interface for providing User Credentials for use with a Docker Registry."""

__metaclass__ = abc.ABCMeta # For enforcing that methods are overridden.
class Provider(six.with_metaclass(abc.ABCMeta, object)):
"""Interface for providing User Credentials for use with a Docker Registry."""

# pytype: disable=bad-return-type
@abc.abstractmethod
Expand Down Expand Up @@ -63,7 +67,7 @@ def suffix(self):

def Get(self):
"""Gets the credential in a form suitable for an Authorization header."""
return '%s %s' % (self._scheme, self.suffix)
return u'%s %s' % (self._scheme, self.suffix)


class Basic(SchemeProvider):
Expand All @@ -84,7 +88,9 @@ def password(self):

@property
def suffix(self):
return base64.b64encode(self.username + ':' + self.password)
u = self.username.encode('utf8')
p = self.password.encode('utf8')
return base64.b64encode(u + b':' + p).decode('utf8')


_USERNAME = '_token'
Expand Down Expand Up @@ -159,9 +165,7 @@ def Get(self):
# Some keychains expect a scheme:
# https://github.com/bazelbuild/rules_docker/issues/111
stdout = p.communicate(input='https://' + self._registry)[0]

output = stdout.decode()
if output.strip() == _MAGIC_NOT_FOUND_MESSAGE:
if stdout.strip() == _MAGIC_NOT_FOUND_MESSAGE:
# Use empty auth when no auth is found.
logging.info('Credentials not found, falling back to anonymous auth.')
return Anonymous().Get()
Expand All @@ -170,16 +174,14 @@ def Get(self):
raise Exception('Error fetching credential for %s, exit status: %d\n%s' %
(self._name, p.returncode, stdout))

blob = json.loads(output)
blob = json.loads(stdout)
logging.info('Successfully obtained Docker credentials.')
return Basic(blob['Username'], blob['Secret']).Get()


class Keychain(object):
class Keychain(six.with_metaclass(abc.ABCMeta, object)):
"""Interface for resolving an image reference to a credential."""

__metaclass__ = abc.ABCMeta # For enforcing that methods are overridden.

# pytype: disable=bad-return-type
@abc.abstractmethod
def Resolve(self, name):
Expand Down Expand Up @@ -235,7 +237,7 @@ def Resolve(self, name):
logging.info('Loading Docker credentials for repository %r', str(name))
config_file = os.path.join(_GetConfigDirectory(), 'config.json')
try:
with open(config_file, 'r') as reader:
with io.open(config_file, u'r', encoding='utf8') as reader:
cfg = json.loads(reader.read())
except IOError:
# If the file doesn't exist, fallback on anonymous auth.
Expand All @@ -257,7 +259,8 @@ def Resolve(self, name):
if form % name.registry in auths:
entry = auths[form % name.registry]
if 'auth' in entry:
username, password = base64.b64decode(entry['auth']).split(':', 1)
decoded = base64.b64decode(entry['auth']).decode('utf8')
username, password = decoded.split(':', 1)
return Basic(username, password)
elif 'username' in entry and 'password' in entry:
return Basic(entry['username'], entry['password'])
Expand Down
16 changes: 7 additions & 9 deletions client/docker_name_.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@
# limitations under the License.
"""This package defines Tag a way of representing an image uri."""

from __future__ import absolute_import
from __future__ import division

from __future__ import print_function

import os
import sys
import urlparse
import six.moves.urllib.parse



Expand All @@ -39,13 +42,8 @@ class BadNameException(Exception):
DEFAULT_TAG = 'latest'


def _check_element(
name,
element,
characters,
min_len,
max_len
):
def _check_element(name, element, characters, min_len,
max_len):
"""Checks a given named element matches character and length restrictions.

Args:
Expand Down Expand Up @@ -86,7 +84,7 @@ def _check_digest(digest):

def _check_registry(registry):
# Per RFC 3986, netlocs (authorities) are required to be prefixed with '//'
parsed_hostname = urlparse.urlparse('//' + registry)
parsed_hostname = six.moves.urllib.parse.urlparse('//' + registry)

# If urlparse doesn't recognize the given registry as a netloc, fail
# validation.
Expand Down
9 changes: 6 additions & 3 deletions client/monitor_.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,22 @@
# limitations under the License.
"""This module contains utilities for monitoring client side calls."""

from __future__ import absolute_import
from __future__ import division

from __future__ import print_function

import abc
import six



class Context(object):
class Context(six.with_metaclass(abc.ABCMeta, object)):
"""Interface for implementations of client monitoring context manager.

All client operations are executed inside this context.
"""

__metaclass__ = abc.ABCMeta # For enforcing that methods are overridden.

@abc.abstractmethod
def __init__(self, operation):
pass
Expand All @@ -46,6 +48,7 @@ def __exit__(self, exc_type,
class Nop(Context):
"""Default implementation of Context that does nothing."""

# pylint: disable=useless-super-delegation
def __init__(self, operation):
super(Nop, self).__init__(operation)

Expand Down
3 changes: 3 additions & 0 deletions client/v1/docker_creds_.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
# limitations under the License.
"""This package exposes credentials for talking to a Docker registry."""

from __future__ import absolute_import
from __future__ import division

from __future__ import print_function

from containerregistry.client import docker_creds

Expand Down
3 changes: 3 additions & 0 deletions client/v1/docker_http_.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
# limitations under the License.
"""This package facilitates HTTP/REST requests to the registry."""

from __future__ import absolute_import
from __future__ import division

from __future__ import print_function

from containerregistry.client import docker_creds
from containerregistry.client import docker_name
Expand Down
Loading