Completed
Push — master ( 7c9762...3da29d )
by Charles
01:17
created

MetadataParamType.convert()   A

Complexity

Conditions 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
c 0
b 0
f 0
dl 0
loc 13
ccs 10
cts 10
cp 1
crap 4
rs 9.2
1
# -*- coding: utf-8 -*-
2 1
'''
3
    Main module
4
'''
5 1
import os
6 1
import re
7
8 1
from pprint import pprint
0 ignored issues
show
Unused Code introduced by
Unused pprint imported from pprint
Loading history...
9
10 1
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...
11 1
from tabulate import tabulate
0 ignored issues
show
Configuration introduced by
The import tabulate 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...
12
13 1
import git_app_version.version
14 1
from git_app_version.dumper import FileDumper
15 1
from git_app_version.githandler import GitHandler, RESERVED_KEYS
16
17 1
__version__ = git_app_version.version.__version__
18
19
20 1
def print_version(ctx, param, value):
1 ignored issue
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The argument param seems to be unused.
Loading history...
21 1
    if not value or ctx.resilient_parsing:
22 1
        return
23 1
    click.echo('git-app-version ' + __version__)
24 1
    ctx.exit()
25
26
27 1
CONTEXT_SETTINGS = {'help_option_names': ['-h', '--help']}
28
29 1
class MetadataParamType(click.ParamType):
1 ignored issue
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Coding Style introduced by
This class has no __init__ method.
Loading history...
30 1
    name = 'metadata'
31
32 1
    def convert(self, value, param, ctx):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
33 1
        try:
34 1
            match = re.match(r'^([^=]+)=(.*)$', value)
35 1
            if not match:
36 1
                raise ValueError('%s is not a valid meta data string e.g. : <key>=<value>' % value)
37
38 1
            if match.group(1) in RESERVED_KEYS:
39 1
                raise ValueError('%s is a reserved key' % match.group(1))
40
41 1
            return {match.group(1): match.group(2).strip('"\'')}
42
43 1
        except ValueError as e:
0 ignored issues
show
Coding Style Naming introduced by
The name e does not conform to the variable naming conventions ([a-z_][a-z0-9_]{2,30}$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
44 1
            self.fail(e.message, param, ctx)
1 ignored issue
show
Bug introduced by
The Instance of MetadataParamType does not seem to have a member named fail.

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...
Bug introduced by
The Instance of ValueError does not seem to have a member named message.

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...
45
46 1
METADATA = MetadataParamType()
47
48 1
@click.command(context_settings=CONTEXT_SETTINGS)
49 1
@click.option('--version', '-V', is_flag=True, callback=print_version,
50
              expose_value=False, is_eager=True)
51
# @click.option('--verbose', '-v', count=True)
52 1
@click.option('--quiet', '-q', is_flag=True, help='silent mode')
53 1
@click.option('--output', '-o', default='version',
54
              help='output file path (without extension).'
55
              ' Default is \'<repository-path>/version\'.')
56 1
@click.option('--format', '-f', 'output_formats',
57
              type=click.Choice(['json', 'yml', 'xml', 'ini', 'sh']),
58
              multiple=True, default=['json'],
59
              help='output file format and extension, Default is json.')
60 1
@click.option('--namespace', '-n', default='',
61
              help='namespace like notation in version file, use dot separator'
62
              ' to segment namespaces e.g.: \'foo.bar.git\'.'
63
              ' Default is \'app_version\' for XML and INI'
64
              ' and no namespace for JSON and YAML.'
65
              ' Never used for Shell file.')
66 1
@click.option('--meta', '-m', type=METADATA, multiple=True,
67
              help='meta data to add, format = "<key>=<value>"')
1 ignored issue
show
best-practice introduced by
Too many arguments (8/5)
Loading history...
Comprehensibility introduced by
This function exceeds the maximum number of variables (17/15).
Loading history...
68 1
@click.argument('repository', type=click.Path(
69
    exists=True, resolve_path=True, file_okay=False, readable=True),
70
    default=os.getcwd())
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation.
default=os.getcwd())
^ |
Loading history...
71 1
@click.argument('commit', default='HEAD')
72 1
@click.pass_context
73
def dump(ctx, repository, commit, output, output_formats, namespace, meta, quiet):
74
    '''
75
    Get Git commit informations and store them in a INI/XML/YAML/JSON/SH file
76
77
    \b
78
    REPOSITORY git repository path, Default is the current directory.
79
    COMMIT     git commit to check, Default is HEAD.
80
    '''
81
82 1
    try:
83 1
        vcs = GitHandler(repository)
84
85 1
        data = vcs.get_infos(commit=commit)
86
87
        # add metadatas
88 1
        for item in meta:
89 1
            for k,v in item.iteritems():
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
for k,v in item.iteritems():
^
Loading history...
Coding Style Naming introduced by
The name v does not conform to the variable naming conventions ([a-z_][a-z0-9_]{2,30}$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
90 1
                data[k] = v
91
92 1
        if not quiet:
93 1
            print_commit_table(data)
94
95 1
        dumper = FileDumper()
96 1
        if not quiet and len(output_formats):
97 1
            click.echo("written to :")
98
99 1
        for output_format in output_formats:
100 1
            dest = dumper.dump(
101
                data=data,
102
                fileformat=output_format,
103
                target=output,
104
                cwd=repository,
105
                namespace=namespace)
106 1
            if not quiet:
107 1
                click.echo(dest)
108
109 1
        ctx.exit(0)
110
111 1
    except (RuntimeError, ValueError, TypeError) as exc:
112 1
        click.echo("Error Writing version config file : " + str(exc))
113 1
        ctx.exit(1)
114
115
116 1
def print_commit_table(data):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
117 1
    click.echo('Git commit :')
118 1
    keys = sorted(data.keys())
119 1
    table = []
120 1
    for key in keys:
121 1
        if isinstance(data[key], list):
122 1
            item = ' '.join(data[key])
123
        else:
124 1
            item = data[key]
125
126 1
        table.append([key, item])
127
128
    click.echo(tabulate(table, tablefmt='simple'))
129