# Path: pgctl/config.py
# class Config:
# 
#     def __init__(self, projectname, defaults=None):
#         self.projectname = projectname
#         self.defaults = defaults
# 
#     def from_file(self, filename):
#         # TODO P3: refactor this spaghetti
#         # TODO(ckuehl|2019-08-08): why do we support .ini files??
#         if filename.endswith(('.conf', '.ini')):
#             parser = configparser.ConfigParser()
#             parser.read(filename)
#             result = dict(parser.items(self.projectname))
#             for key, value in result.items():
#                 if key.endswith('_list'):
#                     value = result.pop(key).split()
#                     key = key.rsplit('_list', 1)[0]
#                     result[key] = value
#             return result
#         elif filename.endswith(('.yaml', '.yml')):
#             return yaml.load(
#                 open(filename),
#                 Loader=getattr(yaml, 'CSafeLoader', yaml.SafeLoader),
#             )
#         elif filename.endswith('.json'):
#             return json.load(open(filename))
#         else:
#             raise UnrecognizedConfig('Unknown config type: %s' % filename)
# 
#     def from_glob(self, pattern):
#         from pgctl.configsearch import glob
#         results = []
#         for fname in glob(pattern):
#             try:
#                 config = self.from_file(fname)
#             except UnrecognizedConfig:
#                 continue
#             else:
#                 results.append(config)
# 
#         if len(results) == 1:
#             return results[0]
#         elif len(results) > 1:
#             raise AmbiguousConfig('multiple configurations found at %s' % pattern)
# 
#     def from_path_prefix(self, pattern_prefix):
#         pattern = ''.join((pattern_prefix, self.projectname, '.*'))
#         return self.from_glob(pattern)
# 
#     def from_system(self):
#         if environ.get('PGCTL_NO_GLOBAL_CONFIG') == 'true':
#             return {}
#         etc = join(environ.get('PREFIX', '/'), 'etc', '')
#         return self.from_path_prefix(etc)
# 
#     def from_homedir(self):
#         if environ.get('PGCTL_NO_GLOBAL_CONFIG') == 'true':
#             return {}
#         home = environ.get('HOME', '$HOME')
#         return self.from_path_prefix(home + '/.')
# 
#     def from_environ(self, env=None):
#         if env is None:
#             env = environ
# 
#         var_prefix = self.projectname.upper() + '_'
#         config = {}
#         for varname, value in env.items():
#             if varname.startswith(var_prefix):
#                 varname = varname.replace(var_prefix, '', 1).lower()
#                 if varname.endswith('_list'):
#                     varname = varname.rsplit('_list', 1)[0]
#                     value = value.split()
#                 config[varname] = value
#         return config
# 
#     def from_app(self, path='.'):
#         pattern = self.projectname + '.*'
#         return merge(
#             self.from_glob(join(parentdir, pattern))
#             for parentdir in reversed(tuple(search_parent_directories(path)))
#         )
# 
#     def from_cli(self, args):
#         configs = []
#         if args.config is not None:
#             configs.append(self.from_file(args.config))
#         configs.append(vars(args))
#         return merge(configs)
# 
#     def combined(self, defaults=(), args=Dummy()):
#         return merge((
#             defaults,
#             self.from_system(),
#             self.from_homedir(),
#             self.from_app(),
#             self.from_environ(),
#             self.from_cli(args),
#         ))


import os
import pytest
from argparse import Namespace
from contextlib import contextmanager
from unittest import mock
from testing.norm import norm_trailing_whitespace_json
from testing.subprocess import assert_command
from pgctl.config import Config
        from sys import executable
[my]
app = app
apps_list =
    1
    2
    3\
''')
    a.join('my.yaml').write('app/a: app/a')
    b.join('my.yaml').write('app/b: app/b')
    c.join('my.junk').write('junk!')
    c.join('foo.json').write('{"foo": "bar"}')

    with mock.patch.dict(os.environ, {
        'PREFIX': tmpdir.strpath,
        'HOME': home.strpath,
        'MY_ENVIRON': 'environ',
        'MY_ENVIRONS_LIST': '1 2 3',
    }):
        with c.as_cwd():
            yield


class DescribeCombined:

    @pytest.fixture(autouse=True)
    def use_global_config_values(self):
        with mock.patch.dict(os.environ, {'PGCTL_NO_GLOBAL_CONFIG': 'false'}):
            yield

    def it_combines_all_the_configs(self, tmpdir):

# Path: pgctl/config.py
# class Config:
# 
#     def __init__(self, projectname, defaults=None):
#         self.projectname = projectname
#         self.defaults = defaults
# 
#     def from_file(self, filename):
#         # TODO P3: refactor this spaghetti
#         # TODO(ckuehl|2019-08-08): why do we support .ini files??
#         if filename.endswith(('.conf', '.ini')):
#             parser = configparser.ConfigParser()
#             parser.read(filename)
#             result = dict(parser.items(self.projectname))
#             for key, value in result.items():
#                 if key.endswith('_list'):
#                     value = result.pop(key).split()
#                     key = key.rsplit('_list', 1)[0]
#                     result[key] = value
#             return result
#         elif filename.endswith(('.yaml', '.yml')):
#             return yaml.load(
#                 open(filename),
#                 Loader=getattr(yaml, 'CSafeLoader', yaml.SafeLoader),
#             )
#         elif filename.endswith('.json'):
#             return json.load(open(filename))
#         else:
#             raise UnrecognizedConfig('Unknown config type: %s' % filename)
# 
#     def from_glob(self, pattern):
#         from pgctl.configsearch import glob
#         results = []
#         for fname in glob(pattern):
#             try:
#                 config = self.from_file(fname)
#             except UnrecognizedConfig:
#                 continue
#             else:
#                 results.append(config)
# 
#         if len(results) == 1:
#             return results[0]
#         elif len(results) > 1:
#             raise AmbiguousConfig('multiple configurations found at %s' % pattern)
# 
#     def from_path_prefix(self, pattern_prefix):
#         pattern = ''.join((pattern_prefix, self.projectname, '.*'))
#         return self.from_glob(pattern)
# 
#     def from_system(self):
#         if environ.get('PGCTL_NO_GLOBAL_CONFIG') == 'true':
#             return {}
#         etc = join(environ.get('PREFIX', '/'), 'etc', '')
#         return self.from_path_prefix(etc)
# 
#     def from_homedir(self):
#         if environ.get('PGCTL_NO_GLOBAL_CONFIG') == 'true':
#             return {}
#         home = environ.get('HOME', '$HOME')
#         return self.from_path_prefix(home + '/.')
# 
#     def from_environ(self, env=None):
#         if env is None:
#             env = environ
# 
#         var_prefix = self.projectname.upper() + '_'
#         config = {}
#         for varname, value in env.items():
#             if varname.startswith(var_prefix):
#                 varname = varname.replace(var_prefix, '', 1).lower()
#                 if varname.endswith('_list'):
#                     varname = varname.rsplit('_list', 1)[0]
#                     value = value.split()
#                 config[varname] = value
#         return config
# 
#     def from_app(self, path='.'):
#         pattern = self.projectname + '.*'
#         return merge(
#             self.from_glob(join(parentdir, pattern))
#             for parentdir in reversed(tuple(search_parent_directories(path)))
#         )
# 
#     def from_cli(self, args):
#         configs = []
#         if args.config is not None:
#             configs.append(self.from_file(args.config))
#         configs.append(vars(args))
#         return merge(configs)
# 
#     def combined(self, defaults=(), args=Dummy()):
#         return merge((
#             defaults,
#             self.from_system(),
#             self.from_homedir(),
#             self.from_app(),
#             self.from_environ(),
#             self.from_cli(args),
#         ))


# Path: tests/spec/config.py
import os
import pytest
from argparse import Namespace
from contextlib import contextmanager
from unittest import mock
from testing.norm import norm_trailing_whitespace_json
from testing.subprocess import assert_command
from pgctl.config import Config
        from sys import executable

[my]
app = app
apps_list =
    1
    2
    3\
''')
    a.join('my.yaml').write('app/a: app/a')
    b.join('my.yaml').write('app/b: app/b')
    c.join('my.junk').write('junk!')
    c.join('foo.json').write('{"foo": "bar"}')

    with mock.patch.dict(os.environ, {
        'PREFIX': tmpdir.strpath,
        'HOME': home.strpath,
        'MY_ENVIRON': 'environ',
        'MY_ENVIRONS_LIST': '1 2 3',
    }):
        with c.as_cwd():
            yield


class DescribeCombined:

    @pytest.fixture(autouse=True)
    def use_global_config_values(self):
        with mock.patch.dict(os.environ, {'PGCTL_NO_GLOBAL_CONFIG': 'false'}):
            yield

    def it_combines_all_the_configs(self, tmpdir):

        config = Config('my', {'default': 'default'})