Skip to content

Commit

Permalink
Implement YAML logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ezh committed Feb 13, 2020
1 parent 4538b40 commit 3ed74da
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 33 deletions.
48 changes: 30 additions & 18 deletions cloudselect/cloudselect.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import chardet
import dependency_injector.providers as providers
import pkg_resources
from yaml import safe_load

import cloudselect
from cloudselect import Container
Expand All @@ -42,43 +43,51 @@ class CloudSelect:
"""

extension = "cloud.json"
configpath = appdirs.user_config_dir("cloudselect")
extensions = ["cloud.json", "cloud.yml", "cloud.yaml"]
importer = staticmethod(__import__)

def __init__(self):
def __init__(self, configpath=None):
"""Class constructor."""
self.configpath = appdirs.user_config_dir("cloudselect")
if configpath:
self.configpath = configpath
self.logger = None

def configuration_exists(self, name):
"""Check if configuration/profile exists."""
if os.path.isfile(name):
return True
else:
file_name = ".".join(filter(None, [name, self.extension]))
for i in self.extensions:
if os.path.isfile(name):
return True
file_name = ".".join(filter(None, [name, i]))
full_path = os.path.join(self.configpath, file_name)
return os.path.isfile(full_path)
if os.path.isfile(full_path):
return True
return False

def configuration_read(self, name=None):
"""Read configuration/profile."""
"""
Read json configuration from configpath
Read JSON/YAML configuration from configpath
Copy initial configuration from cloud.json.dist to cloud.json if needed
""" # pylint: disable=W0105
full_path = name
if name and os.path.isfile(name):
full_path = os.path.abspath(name)
name = os.path.basename(name).replace(".{}".format(self.extension), "")
else:
file_name = ".".join(filter(None, [name, self.extension]))
full_path = os.path.join(self.configpath, file_name)
for i in self.extensions:
if name and os.path.isfile(name):
full_path = os.path.abspath(name)
name = os.path.basename(name).replace(".{}".format(i), "")
break
file_name = ".".join(filter(None, [name, i]))
full_path_candidate = os.path.join(self.configpath, file_name)
if os.path.isfile(full_path_candidate):
full_path = full_path_candidate
break

try:
if name is None and not os.path.isfile(full_path):
if not os.path.exists(self.configpath):
os.mkdir(self.configpath)
source = pkg_resources.resource_string(
__name__, "{}.dist".format(self.extension),
__name__, "{}.dist".format(self.extensions[0]),
)
with open(full_path, "w") as f:
data = json.loads(source.decode())
Expand All @@ -87,7 +96,10 @@ def configuration_read(self, name=None):
)
charenc = chardet.detect(open(full_path, "rb").read())["encoding"]
with open(full_path, "r", encoding=charenc) as f:
return json.load(f)
if full_path.endswith(".json"):
return json.load(f)
else:
return safe_load(f)
except Exception as e:
message = "Unable to read configuration {}: {}".format(full_path, str(e))
if self.logger:
Expand All @@ -114,7 +126,7 @@ def fabric(self, configuration, args):
Container.args = providers.Object(args)
Container.config = providers.Configuration(name="config", default=configuration)
Container.configpath = providers.Object(self.configpath)
Container.extension = providers.Object(self.extension)
Container.extensions = providers.Object(self.extensions)
Container.options = providers.Callable(self.options)
Container.selector = providers.Singleton(Selector)

Expand Down
42 changes: 27 additions & 15 deletions cloudselect/selector.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,20 @@ def __init__(self):
def complete(self, cline, cpoint):
"""List profiles for shell completion."""
configpath = Container.configpath()
extension = Container.extension()
extensions = Container.extensions()

prefix = cline[0:cpoint].partition(" ")[-1]
self.logger.debug(
"Complete line %s, point %s, prefix %s", cline, cpoint, prefix,
)
profiles = []
for profile in os.listdir(configpath):
if profile.endswith(".{}".format(extension)):
name = profile.replace(".{}".format(extension), "")
if name.startswith(prefix):
print(name)
for extension in extensions:
if profile.endswith(".{}".format(extension)):
name = profile.replace(".{}".format(extension), "")
if name.startswith(prefix):
profiles.append(name)
print("\n".join(sorted(set(profiles))))

def edit(self, configuration):
"""Edit profile or shared configuration file if file is None."""
Expand Down Expand Up @@ -104,16 +107,21 @@ def get_editor(self):
def profile_list(self):
"""List available profiles."""
configpath = Container.configpath()
extension = Container.extension()
extensions = Container.extensions()

self.logger.debug("List all available profiles from %s", configpath)
empty = True
profiles = []
print("CloudSelect profiles:")

for profile in os.listdir(configpath):
if profile.endswith(".{}".format(extension)):
empty = False
print("- {}".format(profile.replace(".{}".format(extension), "")))
if empty:
for extension in extensions:
if profile.endswith(".{}".format(extension)):
profiles.append(
"- {}".format(profile.replace(".{}".format(extension), "")),
)
if profiles:
print("\n".join(sorted(set(profiles))))
else:
print("- NO PROFILES -")

def profile_process(self):
Expand Down Expand Up @@ -148,14 +156,18 @@ def select(self):
"""Entry point. Select instances."""
args = Container.args()
configpath = Container.configpath()
extension = Container.extension()
extensions = Container.extensions()

if args.edit is None or args.edit:
if args.edit is None:
configuration = os.path.join(configpath, "{}".format(extension))
configuration = os.path.join(configpath, "{}".format(extensions[0]))
return self.edit(configuration)
profile = os.path.join(configpath, "{}.{}".format(args.edit, extension))
return self.edit(profile)
for extension in extensions:
profile = os.path.join(configpath, "{}.{}".format(args.edit, extension))
if os.path.isfile(profile):
return self.edit(profile)
print("Profile '{}' does not exist".format(args.edit), file=sys.stderr)
return self.logger.error("Profile '%s' does not exist", args.edit)
if args.reporter is None:
return self.reporter_list()
if not args.profile:
Expand Down

0 comments on commit 3ed74da

Please sign in to comment.