Completed
Push — pyup-update-pytest-3.2.3-to-3.... ( 5144af )
by Michael
07:18 queued 07:12
created

Project.load()   B

Complexity

Conditions 4

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
dl 0
loc 39
ccs 0
cts 0
cp 0
crap 20
rs 8.5806
1 3
import io
2 3
import os
3
import sys
4 3
from os.path import exists, expanduser, expandvars, join, curdir
5 3
from pathlib import Path
6 3
7
import attr
0 ignored issues
show
Configuration introduced by
The import attr could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
8 3
import click
0 ignored issues
show
Configuration introduced by
The import click could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
9 3
import inflection
0 ignored issues
show
Configuration introduced by
The import inflection could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
10 3
import toml
0 ignored issues
show
Configuration introduced by
The import toml could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
11
12 3
from changes.models import BumpVersion
13 3
from changes import prompt
14
from .commands import info, note, debug
15
16
AUTH_TOKEN_ENVVAR = 'GITHUB_AUTH_TOKEN'
17
18 3
# via https://github.com/jakubroztocil/httpie/blob/6bdfc7a/httpie/config.py#L9
19
IS_WINDOWS = 'win32' in str(sys.platform).lower()
20
DEFAULT_CONFIG_FILE = str(os.environ.get(
21
    'CHANGES_CONFIG_FILE',
22 3
    expanduser('~/.changes') if not IS_WINDOWS else
23
    expandvars(r'%APPDATA%\\.changes')
24
))
25
26
PROJECT_CONFIG_FILE = '.changes.toml'
27
DEFAULT_RELEASES_DIRECTORY = 'docs/releases'
28
29 3
30 3
@attr.s
31 3
class Changes(object):
32 3
    auth_token = attr.ib()
33 3
34 3
    @classmethod
35
    def load(cls):
36 3
        tool_config_path = Path(str(os.environ.get(
37
            'CHANGES_CONFIG_FILE',
38 3
            expanduser('~/.changes') if not IS_WINDOWS else
39
            expandvars(r'%APPDATA%\\.changes')
40 3
        )))
41 3
42 3
        tool_settings = None
43 3
        if tool_config_path.exists():
44 3
            tool_settings = Changes(
45
                **(toml.load(tool_config_path.open())['changes'])
46
            )
47
48
        # envvar takes precedence over config file settings
49 3
        auth_token = os.environ.get(AUTH_TOKEN_ENVVAR)
50
        if auth_token:
51
            info('Found Github Auth Token in the environment')
52 3
            tool_settings = Changes(auth_token=auth_token)
53
        elif not (tool_settings and tool_settings.auth_token):
54 3
            while not auth_token:
55
                info('No auth token found, asking for it')
56 3
                # to interact with the Git*H*ub API
57
                note('You need a Github Auth Token for changes to create a release.')
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (85/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
58 3
                click.pause('Press [enter] to launch the GitHub "New personal access '
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (86/79).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
59 3
                            'token" page, to create a token for changes.')
60 3
                click.launch('https://github.com/settings/tokens/new')
61
                auth_token = click.prompt('Enter your changes token')
62 3
63
            if not tool_settings:
64
                tool_settings = Changes(auth_token=auth_token)
65 3
66 3
            tool_config_path.write_text(
0 ignored issues
show
Bug introduced by
The Instance of Path does not seem to have a member named write_text.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
67
                toml.dumps({
68
                    'changes': attr.asdict(tool_settings)
69 3
                })
70 3
            )
71
72 3
        return tool_settings
73 3
74
75
@attr.s
76
class Project(object):
77
    releases_directory = attr.ib()
78
    repository = attr.ib(default=None)
79
    bumpversion = attr.ib(default=None)
80
    labels = attr.ib(default=attr.Factory(dict))
81
82
    @classmethod
83
    def load(cls, repository):
84
        changes_project_config_path = Path(PROJECT_CONFIG_FILE)
85
        project_settings = None
86
87
        if changes_project_config_path.exists():
88
            # releases_directory, labels
89
            project_settings = Project(
90
                **(toml.load(changes_project_config_path.open())['changes'])
91
            )
92
93
        if not project_settings:
94
            releases_directory = Path(click.prompt(
95
                'Enter the directory to store your releases notes',
96
                DEFAULT_RELEASES_DIRECTORY,
97
                type=click.Path(exists=True, dir_okay=True)
98
            ))
99
100
            if not releases_directory.exists():
101
                debug('Releases directory {} not found, creating it.'.format(
102
                    releases_directory))
103
                releases_directory.mkdir(parents=True)
104
105
            project_settings = Project(
106
                releases_directory=str(releases_directory),
107
                labels=configure_labels(repository.labels),
108
            )
109
            # write config file
110
            changes_project_config_path.write_text(
0 ignored issues
show
Bug introduced by
The Instance of Path does not seem to have a member named write_text.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
111
                toml.dumps({
112
                    'changes': attr.asdict(project_settings)
113
                })
114
            )
115
116
        project_settings.repository = repository
117
        project_settings.bumpversion = BumpVersion.load(
118
            repository.latest_version)
119
120
        return project_settings
121
122
123
def configure_labels(github_labels):
124
    labels_keyed_by_name = {}
125
    for label in github_labels:
126
        labels_keyed_by_name[label['name']] = label
127
128
    # TODO: streamlined support for github defaults: enhancement, bug
129
    changelog_worthy_labels = prompt.choose_labels([
130
        properties['name']
131
        for _, properties in labels_keyed_by_name.items()
132
    ])
133
134
    # TODO: apply description transform in labels_prompt function
135
    described_labels = {}
136
    # auto-generate label descriptions
137
    for label_name in changelog_worthy_labels:
138
        label_properties = labels_keyed_by_name[label_name]
139
        # Auto-generate description as pluralised titlecase label name
140
        label_properties['description'] = inflection.pluralize(
141
            inflection.titleize(label_name)
142
        )
143
144
        described_labels[label_name] = label_properties
145
146
    return described_labels
147
148
149
# TODO: borg legacy
150
DEFAULTS = {
151
    'changelog': 'CHANGELOG.md',
152
    'readme': 'README.md',
153
    'github_auth_token': None,
154
}
155
156
157
class Config:
158
    """Deprecated"""
159
    test_command = None
160
    pypi = None
161
    skip_changelog = None
162
    changelog_content = None
163
    repo = None
164
165
    def __init__(self, module_name, dry_run, debug, no_input, requirements,
0 ignored issues
show
Comprehensibility Bug introduced by
debug is re-defining a name which is already available in the outer-scope (previously defined on line 14).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
166
                 new_version, current_version, repo_url, version_prefix):
167
        self.module_name = module_name
168
        # module_name => project_name => curdir
169
        self.dry_run = dry_run
170
        self.debug = debug
171
        self.no_input = no_input
172
        self.requirements = requirements
173
        self.new_version = (
174
            version_prefix + new_version
175
            if version_prefix
176
            else new_version
177
        )
178
        self.current_version = current_version
179
180
181
def project_config():
182
    """Deprecated"""
183
    project_name = curdir
184
185
    config_path = Path(join(project_name, PROJECT_CONFIG_FILE))
186
187
    if not exists(config_path):
188
        store_settings(DEFAULTS.copy())
189
        return DEFAULTS
190
191
    return toml.load(io.open(config_path)) or {}
192
193
194
def store_settings(settings):
195
    pass
196