command.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from ..packages.docker import Client
  4. from requests.exceptions import ConnectionError
  5. import errno
  6. import logging
  7. import os
  8. import re
  9. import yaml
  10. from ..project import Project
  11. from .docopt_command import DocoptCommand
  12. from .formatter import Formatter
  13. from .utils import cached_property, docker_url
  14. from .errors import UserError
  15. log = logging.getLogger(__name__)
  16. class Command(DocoptCommand):
  17. base_dir = '.'
  18. def dispatch(self, *args, **kwargs):
  19. try:
  20. super(Command, self).dispatch(*args, **kwargs)
  21. except ConnectionError:
  22. raise UserError("""
  23. Couldn't connect to Docker daemon at %s - is it running?
  24. If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
  25. """ % self.client.base_url)
  26. @cached_property
  27. def client(self):
  28. return Client(docker_url())
  29. @cached_property
  30. def project(self):
  31. try:
  32. yaml_path = os.path.join(self.base_dir, 'fig.yml')
  33. config = yaml.load(open(yaml_path))
  34. except IOError as e:
  35. if e.errno == errno.ENOENT:
  36. log.error("Can't find %s. Are you in the right directory?", os.path.basename(e.filename))
  37. else:
  38. log.error(e)
  39. exit(1)
  40. return Project.from_config(self.project_name, config, self.client)
  41. @cached_property
  42. def project_name(self):
  43. project = os.path.basename(os.getcwd())
  44. project = re.sub(r'[^a-zA-Z0-9]', '', project)
  45. if not project:
  46. project = 'default'
  47. return project
  48. @cached_property
  49. def formatter(self):
  50. return Formatter()