Skip to content

Commit

Permalink
Feature: Usage of config file.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ri-P committed Jun 4, 2015
1 parent ceb80da commit 99099d6
Show file tree
Hide file tree
Showing 6 changed files with 128 additions and 34 deletions.
1 change: 0 additions & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
include README.md
include LICENSE
include cfg/config.yml
include bin/ethunder
recursive-include ethunder/test *.py
4 changes: 0 additions & 4 deletions cfg/config.yml

This file was deleted.

7 changes: 5 additions & 2 deletions ethunder/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
"""
EnlightedThunder
~~~~~~~
A project to explore the possibilites of GitHub and Python deployment.
This is a personal discovery and not considered usefull for other. It's
probabliy best if you just ignore it.
Expand All @@ -13,3 +13,6 @@
"""

__version__ = "0.1.0"

class EThunderError(Exception):
pass
33 changes: 12 additions & 21 deletions ethunder/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@
import os.path
import sys

import yaml
import docopt
import appdirs
import ethunder
from ethunder.config import configurate

__author__ = "Richard Pfeifer"

configpath = appdirs.user_config_dir("ethunder", appauthor=None)

class EThunderError(Exception):
pass


def parse_commandline(argv):
"""
Expand All @@ -37,29 +39,18 @@ def parse_commandline(argv):
return arguments


def parse_config():
"""
Read the YAML config-file.
"""
with open(os.path.join(configpath, "config.yml"), 'r') as configfile:
cfg = yaml.load(configfile)
ethunder.value1 = cfg['value1']
ethunder.path_to_rainbow = cfg['path_to_rainbow']
ethunder.is_awesome = cfg['is_awesome']


def print_message():
awesome_negation = "not "
if ethunder.is_awesome:
if ethunder.config["is_awesome"]:
awesome_negation = ""
msg = (
"Hello world. This is ethunder and it is {0}awesome!\n"
"\tRainbow can be found at: {1}\n"
"\tvalue1 = {2}"
"\tvalue1 = {2}"
).format(
awesome_negation,
os.path.normpath(ethunder.path_to_rainbow),
ethunder.value1
awesome_negation,
os.path.normpath(ethunder.config["path_to_rainbow"]),
ethunder.config["value1"]
)
print(msg)

Expand All @@ -68,8 +59,8 @@ def Main():
parse_commandline(sys.argv[1:])

try:
parse_config()
print_message()
configurate()
print_message()
except KeyboardInterrupt:
print("Shutdown requested...exiting")
sys.exit(0)
Expand Down
109 changes: 109 additions & 0 deletions ethunder/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# -*- coding: utf-8 -*-
"""
Provide tools to load configuration parameters from text-file using YAML.
"""

from __future__ import print_function
from __future__ import unicode_literals

import yaml
import os.path
import appdirs
import shutil
import datetime
import ethunder
from ethunder import EThunderError

__author__ = "Richard Pfeifer"


config_dir = appdirs.user_config_dir("ethunder", appauthor=None)
config_filename = "config.yml"

default_config = {
"path_to_rainbow": "ick schwörs µus",
"value1": 0,
"is_awesome": True,
}


class NoValidConfigfileError(EThunderError):
pass


def construct_yaml_str(self, node):
"""
Override the default string handling function to always return unicode
objects.
"""
return self.construct_scalar(node)
yaml.Loader.add_constructor("tag:yaml.org,2002:str", construct_yaml_str)
yaml.SafeLoader.add_constructor("tag:yaml.org,2002:str", construct_yaml_str)


def create_default_configfile():
"""
Create a configfile with default config-values at the configpath.
"""
config_path = os.path.join(config_dir, config_filename)
if os.path.isfile(config_path):
backup_filename = "config_backup_{0}.yml".format(
datetime.datetime.now().isoformat())
backup_filename = backup_filename.replace(":", "-")
backup_filepath = os.path.join(config_dir, backup_filename)
shutil.move(config_path, backup_filepath)
with open(config_path, 'w') as config_out_file:
d = yaml.safe_dump(
ethunder.config,
default_flow_style=False,
encoding=('utf-8'),
allow_unicode=True)
print(d)
config_out_file.write(d)

def set_config():
"""
Set configuration either from YAML config-file or from defaults.
"""
configpath = os.path.join(config_dir, config_filename)
ethunder.config = {}
ethunder.config.update(default_config)
try:
try:
print("try open")
with open(configpath, 'r') as configfile:
print("opened")
try:
cfg = yaml.safe_load(configfile)
except Exception as e:
print("error while loading: {0}".format(e))
raise NoValidConfigfileError(e)
else:
print("should have cfg")
except IOError:
print("create empty cfg")
cfg = {}
raise NoValidConfigfileError(
"config.yml not found at {0}".format(configpath))
else:
if not isinstance(cfg, dict):
raise NoValidConfigfileError(
"Invalid configfile at {0}".format(configpath))
except NoValidConfigfileError:
raise
else:
ethunder.config.update(cfg)
print("Following config was read: {0}".format(ethunder.config))


def configurate():
"""
Make sure we have the needed configuration values.
"""
try:
set_config()
except NoValidConfigfileError:
create_default_configfile()

if __name__ == "__main__":
configurate()
8 changes: 2 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
from setuptools import setup
import appdirs

import ethunder

config_dir = appdirs.user_config_dir("ethunder", appauthor=None)

config = {
'name': 'EThunder',
'description': 'A test project.',
Expand All @@ -25,10 +22,9 @@
'install_requires': ['docopt==0.6.1',
'appdirs==1.4.0',
'nose==1.3.4',
'pyYaml==3.11',
],
'pyYaml==3.11',
],
'packages': ['ethunder', 'ethunder.test'],
'data_files': [(config_dir, ['cfg/config.yml'])],
'include_package_data': True,
'entry_points': {'console_scripts':
['ethunder = ethunder.app:Main',
Expand Down

0 comments on commit 99099d6

Please sign in to comment.