command.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 ..packages import six
  11. import sys
  12. from ..project import Project
  13. from ..service import ConfigError
  14. from .docopt_command import DocoptCommand
  15. from .formatter import Formatter
  16. from .utils import cached_property, docker_url, call_silently, is_mac, is_ubuntu
  17. from . import errors
  18. log = logging.getLogger(__name__)
  19. class Command(DocoptCommand):
  20. base_dir = '.'
  21. def dispatch(self, *args, **kwargs):
  22. try:
  23. super(Command, self).dispatch(*args, **kwargs)
  24. except ConnectionError:
  25. if call_silently(['which', 'docker']) != 0:
  26. if is_mac():
  27. raise errors.DockerNotFoundMac()
  28. elif is_ubuntu():
  29. raise errors.DockerNotFoundUbuntu()
  30. else:
  31. raise errors.DockerNotFoundGeneric()
  32. elif call_silently(['which', 'docker-osx']) == 0:
  33. raise errors.ConnectionErrorDockerOSX()
  34. else:
  35. raise errors.ConnectionErrorGeneric(self.client.base_url)
  36. @cached_property
  37. def client(self):
  38. return Client(docker_url())
  39. @cached_property
  40. def project(self):
  41. try:
  42. yaml_path = self.check_yaml_filename()
  43. config = yaml.load(open(yaml_path))
  44. except IOError as e:
  45. if e.errno == errno.ENOENT:
  46. raise errors.FigFileNotFound(os.path.basename(e.filename))
  47. raise errors.UserError(six.text_type(e))
  48. try:
  49. return Project.from_config(self.project_name, config, self.client)
  50. except ConfigError as e:
  51. raise errors.UserError(six.text_type(e))
  52. @cached_property
  53. def project_name(self):
  54. project = os.path.basename(os.getcwd())
  55. project = re.sub(r'[^a-zA-Z0-9]', '', project)
  56. if not project:
  57. project = 'default'
  58. return project
  59. @cached_property
  60. def formatter(self):
  61. return Formatter()
  62. def check_yaml_filename(self):
  63. if os.path.exists(os.path.join(self.base_dir, 'fig.yaml')):
  64. log.warning("Fig just read the file 'fig.yaml' on startup, rather than 'fig.yml'")
  65. log.warning("Please be aware that fig.yml the expected extension in most cases, and using .yaml can cause compatibility issues in future")
  66. return os.path.join(self.base_dir, 'fig.yaml')
  67. else:
  68. return os.path.join(self.base_dir, 'fig.yml')