Test Failed
Push — master ( e380d0...f5671d )
by W
02:58
created

st2client/st2client/commands/triggerinstance.py (2 issues)

1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
from __future__ import absolute_import
17
18
from st2client.commands import resource
19
from st2client.formatters import table
20
from st2client.models import TriggerInstance
21
from st2client.utils.date import format_isodate_for_user_timezone
22
23
24
class TriggerInstanceResendCommand(resource.ResourceCommand):
25
    def __init__(self, resource, *args, **kwargs):
0 ignored issues
show
Comprehensibility Bug introduced by
resource is re-defining a name which is already available in the outer-scope (previously defined on line 18).

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...
26
27
        super(TriggerInstanceResendCommand, self).__init__(
28
            resource, kwargs.pop('name', 're-emit'),
29
            'Re-emit a particular trigger instance.',
30
            *args, **kwargs)
31
32
        self.parser.add_argument('id', nargs='?',
33
                                 metavar='id',
34
                                 help='ID of trigger instance to re-emit.')
35
        self.parser.add_argument(
36
            '-h', '--help',
37
            action='store_true', dest='help',
38
            help='Print usage for the given command.')
39
40
    def run(self, args, **kwargs):
41
        return self.manager.re_emit(args.id)
42
43
    @resource.add_auth_token_to_kwargs_from_cli
44
    def run_and_print(self, args, **kwargs):
45
        ret = self.run(args, **kwargs)
46
        if 'message' in ret:
47
            print(ret['message'])
48
49
50
class TriggerInstanceBranch(resource.ResourceBranch):
51
    def __init__(self, description, app, subparsers, parent_parser=None):
52
        super(TriggerInstanceBranch, self).__init__(
53
            TriggerInstance, description, app, subparsers,
54
            parent_parser=parent_parser, read_only=True,
55
            commands={
56
                'list': TriggerInstanceListCommand,
57
                'get': TriggerInstanceGetCommand
58
            })
59
60
        self.commands['re-emit'] = TriggerInstanceResendCommand(self.resource, self.app,
61
                                                                self.subparsers, add_help=False)
62
63
64
class TriggerInstanceListCommand(resource.ResourceCommand):
65
    display_attributes = ['id', 'trigger', 'occurrence_time', 'status']
66
67
    attribute_transform_functions = {
68
        'occurrence_time': format_isodate_for_user_timezone
69
    }
70
71
    def __init__(self, resource, *args, **kwargs):
0 ignored issues
show
Comprehensibility Bug introduced by
resource is re-defining a name which is already available in the outer-scope (previously defined on line 18).

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...
72
73
        self.default_limit = 50
74
75
        super(TriggerInstanceListCommand, self).__init__(
76
            resource, 'list', 'Get the list of the %s most recent %s.' %
77
            (self.default_limit, resource.get_plural_display_name().lower()),
78
            *args, **kwargs)
79
80
        self.resource_name = resource.get_plural_display_name().lower()
81
        self.group = self.parser.add_argument_group()
82
        self.parser.add_argument('-n', '--last', type=int, dest='last',
83
                                 default=self.default_limit,
84
                                 help=('List N most recent %s. Use -n -1 to fetch the full result \
85
                                       set.' % self.resource_name))
86
87
        # Filter options
88
        self.group.add_argument('--trigger', help='Trigger reference to filter the list.')
89
90
        self.parser.add_argument('-tg', '--timestamp-gt', type=str, dest='timestamp_gt',
91
                                 default=None,
92
                                 help=('Only return trigger instances with occurrence_time '
93
                                       'greater than the one provided. '
94
                                       'Use time in the format 2000-01-01T12:00:00.000Z'))
95
        self.parser.add_argument('-tl', '--timestamp-lt', type=str, dest='timestamp_lt',
96
                                 default=None,
97
                                 help=('Only return trigger instances with timestamp '
98
                                       'lower than the one provided. '
99
                                       'Use time in the format 2000-01-01T12:00:00.000Z'))
100
101
        self.group.add_argument('--status',
102
                                help='Can be pending, processing, processed or processing_failed.')
103
104
        # Display options
105
        self.parser.add_argument('-a', '--attr', nargs='+',
106
                                 default=self.display_attributes,
107
                                 help=('List of attributes to include in the '
108
                                       'output. "all" will return all '
109
                                       'attributes.'))
110
        self.parser.add_argument('-w', '--width', nargs='+', type=int,
111
                                 default=None,
112
                                 help=('Set the width of columns in output.'))
113
114
    @resource.add_auth_token_to_kwargs_from_cli
115
    def run(self, args, **kwargs):
116
        # Filtering options
117
        if args.trigger:
118
            kwargs['trigger'] = args.trigger
119
        if args.timestamp_gt:
120
            kwargs['timestamp_gt'] = args.timestamp_gt
121
        if args.timestamp_lt:
122
            kwargs['timestamp_lt'] = args.timestamp_lt
123
        if args.status:
124
            kwargs['status'] = args.status
125
126
        return self.manager.query_with_count(limit=args.last, **kwargs)
127
128
    def run_and_print(self, args, **kwargs):
129
        instances, count = self.run(args, **kwargs)
130
        if args.json or args.yaml:
131
            self.print_output(reversed(instances), table.MultiColumnTable,
132
                              attributes=args.attr, widths=args.width,
133
                              json=args.json, yaml=args.yaml,
134
                              attribute_transform_functions=self.attribute_transform_functions)
135
        else:
136
            self.print_output(reversed(instances), table.MultiColumnTable,
137
                              attributes=args.attr, widths=args.width,
138
                              attribute_transform_functions=self.attribute_transform_functions)
139
            if args.last and count and count > args.last:
140
                table.SingleRowTable.note_box(self.resource_name, args.last)
141
142
143
class TriggerInstanceGetCommand(resource.ResourceGetCommand):
144
    display_attributes = ['all']
145
    attribute_display_order = ['id', 'trigger', 'occurrence_time', 'payload']
146
147
    pk_argument_name = 'id'
148
149
    @resource.add_auth_token_to_kwargs_from_cli
150
    def run(self, args, **kwargs):
151
        resource_id = getattr(args, self.pk_argument_name, None)
152
        return self.get_resource_by_id(resource_id, **kwargs)
153