Completed
Pull Request — master (#2895)
by Anthony
15:15 queued 05:04
created

ActionAliasExecuteCommand.run_and_print()   A

Complexity

Conditions 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 1
c 2
b 0
f 2
dl 0
loc 5
rs 9.4285
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 st2client import models
17
from st2client.models.action_alias import ActionAlias
18
from st2client.commands.action import ActionRunCommandMixin
0 ignored issues
show
Unused Code introduced by
Unused ActionRunCommandMixin imported from st2client.commands.action
Loading history...
19
from st2client.commands import resource
20
from st2client.formatters import table
21
22
__all__ = [
23
    'ActionAliasBranch'
24
]
25
26
27
class ActionAliasBranch(resource.ResourceBranch):
28
    def __init__(self, description, app, subparsers, parent_parser=None):
29
        super(ActionAliasBranch, self).__init__(
30
            ActionAlias, description, app, subparsers,
31
            parent_parser=parent_parser, read_only=False,
32
            commands={
33
                'list': ActionAliasListCommand,
34
                'get': ActionAliasGetCommand
35
            })
36
37
        self.commands['match'] = ActionAliasMatchCommand(
38
            self.resource, self.app, self.subparsers,
39
            add_help=False)
40
        self.commands['execute'] = ActionAliasExecuteCommand(
41
            self.resource, self.app, self.subparsers,
42
            add_help=False)
43
44
45
class ActionAliasListCommand(resource.ContentPackResourceListCommand):
46
    display_attributes = ['ref', 'pack', 'description', 'enabled']
47
48
49
class ActionAliasGetCommand(resource.ContentPackResourceGetCommand):
50
    display_attributes = ['all']
51
    attribute_display_order = ['id', 'ref', 'pack', 'name', 'description',
52
                               'enabled', 'action_ref', 'formats']
53
54
55
class ActionAliasMatchCommand(resource.ResourceCommand):
56
    display_attributes = ['id', 'name', 'description']
57
58
    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 19).

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...
59
        super(ActionAliasMatchCommand, self).__init__(
60
            resource, 'match',
61
            'Get the list of %s that match the command text.' %
62
            resource.get_plural_display_name().lower(),
63
            *args, **kwargs)
64
65
        self.parser.add_argument('match_text',
66
                                 metavar='command',
67
                                 help=help)
68
69
        self.parser.add_argument('-a', '--attr', nargs='+',
70
                                 default=self.display_attributes,
71
                                 help=('List of attributes to include in the '
72
                                       'output. "all" will return all '
73
                                       'attributes.'))
74
        self.parser.add_argument('-w', '--width', nargs='+', type=int,
75
                                 default=None,
76
                                 help=('Set the width of columns in output.'))
77
78
    @resource.add_auth_token_to_kwargs_from_cli
79
    def run(self, args, **kwargs):
80
        matches = self.manager.match(args.match_text, **kwargs)
81
        return [match['actionalias'] for match in matches]  # show only alias objects
82
83
    def run_and_print(self, args, **kwargs):
84
        instances = self.run(args, **kwargs)
85
        self.print_output(instances, table.MultiColumnTable,
86
                          attributes=args.attr, widths=args.width,
87
                          json=args.json, yaml=args.yaml)
88
89
90
class ActionAliasExecuteCommand(resource.ResourceCommand):
91
    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 19).

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...
92
        super(ActionAliasExecuteCommand, self).__init__(
93
            resource, 'execute',
94
            'Execute the command text by finding a matching ActionAlias.',
95
            *args, **kwargs)
96
97
        self.parser.add_argument('command_text',
98
                                 metavar='command',
99
                                 help=help)
100
        self.parser.add_argument('-h', '--help',
101
                                 action='store_true', dest='help',
102
                                 help='Print usage for the given action.')
103
        self.parser.add_argument('--trace-tag', '--trace_tag',
104
                                 help='A trace tag string to track execution later.',
105
                                 dest='trace_tag', required=False)
106
        self.parser.add_argument('--trace-id',
107
                                 help='Existing trace id for this execution.',
108
                                 dest='trace_id', required=False)
109
        self.parser.add_argument('-a', '--async',
110
                                 action='store_true', dest='async',
111
                                 help='Do not wait for action to finish.')
112
        self.parser.add_argument('-u', '--user', type=str, default=None,
113
                                 help='User under which to run the action (admins only).')
114
115
    @resource.add_auth_token_to_kwargs_from_cli
116
    def run(self, args, **kwargs):
117
        matches = self.manager.match(args.match_text, **kwargs)
118
119
        match = matches[0]
120
        action_alias = match['actionalias']
121
122
        execution = models.ActionAliasExecution()
123
        execution.name = action_alias['name']
124
        execution.format = match['representation']
125
        execution.command = args.match_text
126
        execution.source_channel = 'cli'  # ?
127
        execution.notification_channel = None
128
        execution.notification_route = None
129
        execution.user = args.user
130
131
        action_exec_mgr = self.app.client.managers['ActionAliasExecution']
132
133
        execution = action_exec_mgr.create(execution, **kwargs)
134
135
        return execution
136
137
    def run_and_print(self, args, **kwargs):
138
        instances = self.run(args, **kwargs)
139
        self.print_output(instances, table.MultiColumnTable,
140
                          attributes=args.attr, widths=args.width,
141
                          json=args.json, yaml=args.yaml)
142