command.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. import six
  11. from ..project import Project
  12. from ..service import ConfigError
  13. from .docopt_command import DocoptCommand
  14. from .formatter import Formatter
  15. from .utils import cached_property, docker_url
  16. from .errors import UserError
  17. log = logging.getLogger(__name__)
  18. class Command(DocoptCommand):
  19. base_dir = '.'
  20. def dispatch(self, *args, **kwargs):
  21. try:
  22. super(Command, self).dispatch(*args, **kwargs)
  23. except ConnectionError:
  24. raise UserError("""
  25. Couldn't connect to Docker daemon at %s - is it running?
  26. If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
  27. """ % self.client.base_url)
  28. @cached_property
  29. def client(self):
  30. return Client(docker_url())
  31. @cached_property
  32. def project(self):
  33. try:
  34. yaml_path = self.check_yaml_filename()
  35. config = yaml.load(open(yaml_path))
  36. except IOError as e:
  37. if e.errno == errno.ENOENT:
  38. log.error("Can't find %s. Are you in the right directory?", os.path.basename(e.filename))
  39. else:
  40. log.error(e)
  41. exit(1)
  42. try:
  43. return Project.from_config(self.project_name, config, self.client)
  44. except ConfigError as e:
  45. raise UserError(six.text_type(e))
  46. @cached_property
  47. def project_name(self):
  48. project = os.path.basename(os.getcwd())
  49. project = re.sub(r'[^a-zA-Z0-9]', '', project)
  50. if not project:
  51. project = 'default'
  52. return project
  53. @cached_property
  54. def formatter(self):
  55. return Formatter()
  56. def check_yaml_filename(self):
  57. if os.path.exists(os.path.join(self.base_dir, 'fig.yaml')):
  58. log.warning("Fig just read the file 'fig.yaml' on startup, rather than 'fig.yml'")
  59. log.warning("Please be aware that fig.yml the expected extension in most cases, and using .yaml can cause compatibility issues in future")
  60. return os.path.join(self.base_dir, 'fig.yaml')
  61. else:
  62. return os.path.join(self.base_dir, 'fig.yml')