compose/fig/cli/command.py

85 lines
2.6 KiB
Python
Raw Normal View History

from __future__ import unicode_literals
from __future__ import absolute_import
from ..packages.docker import Client
from requests.exceptions import ConnectionError
import errno
2013-12-11 15:25:32 +01:00
import logging
import os
import re
2013-12-11 15:25:32 +01:00
import yaml
import six
2014-02-19 23:42:21 +01:00
import sys
2013-12-11 15:25:32 +01:00
from ..project import Project
from ..service import ConfigError
2013-12-11 15:25:32 +01:00
from .docopt_command import DocoptCommand
from .formatter import Formatter
from .utils import cached_property, docker_url, call_silently, is_mac, is_ubuntu
from . import errors
2013-12-11 15:25:32 +01:00
log = logging.getLogger(__name__)
class Command(DocoptCommand):
2014-01-09 16:30:36 +01:00
base_dir = '.'
def dispatch(self, *args, **kwargs):
try:
super(Command, self).dispatch(*args, **kwargs)
except ConnectionError:
if call_silently(['which', 'docker']) != 0:
if is_mac():
raise errors.DockerNotFoundMac()
elif is_ubuntu():
raise errors.DockerNotFoundUbuntu()
else:
raise errors.DockerNotFoundGeneric()
elif call_silently(['which', 'docker-osx']) == 0:
raise errors.ConnectionErrorDockerOSX()
else:
raise errors.ConnectionErrorGeneric(self.client.base_url)
2013-12-11 15:25:32 +01:00
@cached_property
def client(self):
return Client(docker_url())
2013-12-11 15:25:32 +01:00
@cached_property
def project(self):
try:
yaml_path = self.check_yaml_filename()
2014-01-09 16:30:36 +01:00
config = yaml.load(open(yaml_path))
except IOError as e:
if e.errno == errno.ENOENT:
2014-01-09 16:30:36 +01:00
log.error("Can't find %s. Are you in the right directory?", os.path.basename(e.filename))
else:
log.error(e)
2014-02-19 23:42:21 +01:00
sys.exit(1)
try:
return Project.from_config(self.project_name, config, self.client)
except ConfigError as e:
raise errors.UserError(six.text_type(e))
@cached_property
def project_name(self):
project = os.path.basename(os.getcwd())
project = re.sub(r'[^a-zA-Z0-9]', '', project)
if not project:
project = 'default'
return project
2013-12-11 15:25:32 +01:00
@cached_property
def formatter(self):
return Formatter()
def check_yaml_filename(self):
if os.path.exists(os.path.join(self.base_dir, 'fig.yaml')):
log.warning("Fig just read the file 'fig.yaml' on startup, rather than 'fig.yml'")
log.warning("Please be aware that fig.yml the expected extension in most cases, and using .yaml can cause compatibility issues in future")
return os.path.join(self.base_dir, 'fig.yaml')
else:
return os.path.join(self.base_dir, 'fig.yml')