Passed
Push — master ( 1e4a43...ac1734 )
by
unknown
03:35
created

ActionAliasExecuteCommand.__init__()   A

Complexity

Conditions 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
c 1
b 0
f 1
dl 0
loc 14
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.models.action_alias import ActionAlias
17
from st2client.models.action_alias import ActionAliasMatch
18
from st2client.models.aliasexecution import ActionAliasExecution
19
from st2client.commands import resource
20
from st2client.formatters import table
21
22
23
__all__ = [
24
    'ActionAliasBranch',
25
    'ActionAliasMatchCommand',
26
    'ActionAliasExecuteCommand'
27
]
28
29
30
class ActionAliasBranch(resource.ResourceBranch):
31
    def __init__(self, description, app, subparsers, parent_parser=None):
32
        super(ActionAliasBranch, self).__init__(
33
            ActionAlias, description, app, subparsers,
34
            parent_parser=parent_parser, read_only=False,
35
            commands={
36
                'list': ActionAliasListCommand,
37
                'get': ActionAliasGetCommand
38
            })
39
40
        self.commands['match'] = ActionAliasMatchCommand(
41
            self.resource, self.app, self.subparsers,
42
            add_help=False)
43
        self.commands['execute'] = ActionAliasExecuteCommand(
44
            self.resource, self.app, self.subparsers,
45
            add_help=False)
46
47
48
class ActionAliasListCommand(resource.ContentPackResourceListCommand):
49
    display_attributes = ['ref', 'pack', 'description', 'enabled']
50
51
52
class ActionAliasGetCommand(resource.ContentPackResourceGetCommand):
53
    display_attributes = ['all']
54
    attribute_display_order = ['id', 'ref', 'pack', 'name', 'description',
55
                               'enabled', 'action_ref', 'formats']
56
57
58
class ActionAliasMatchCommand(resource.ResourceCommand):
59
    display_attributes = ['name', 'description']
60
61
    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...
62
        super(ActionAliasMatchCommand, self).__init__(
63
            resource, 'match',
64
            'Get the list of %s that match the command text.' %
65
            resource.get_plural_display_name().lower(),
66
            *args, **kwargs)
67
68
        self.parser.add_argument('match_text',
69
                                 metavar='command',
70
                                 help=help)
71
        self.parser.add_argument('-h', '--help',
72
                                 action='store_true', dest='help',
73
                                 help='Print usage for the given action.')
74
        self.parser.add_argument('-a', '--attr', nargs='+',
75
                                 default=self.display_attributes,
76
                                 help=('List of attributes to include in the '
77
                                       'output. "all" will return all '
78
                                       'attributes.'))
79
        self.parser.add_argument('-w', '--width', nargs='+', type=int,
80
                                 default=None,
81
                                 help=('Set the width of columns in output.'))
82
83
    @resource.add_auth_token_to_kwargs_from_cli
84
    def run(self, args, **kwargs):
85
        alias_match = ActionAliasMatch()
86
        alias_match.command = args.match_text
87
88
        match, _ = self.manager.match(alias_match, **kwargs)
89
        return [match]
90
91
    def run_and_print(self, args, **kwargs):
92
        instances = self.run(args, **kwargs)
93
        self.print_output(instances, table.MultiColumnTable,
94
                          attributes=args.attr, widths=args.width,
95
                          json=args.json, yaml=args.yaml)
96
97
98
class ActionAliasExecuteCommand(resource.ResourceCommand):
99
    display_attributes = ['name']
100
101
    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...
102
        super(ActionAliasExecuteCommand, self).__init__(
103
            resource, 'execute',
104
            ('Execute the command text by finding a matching %s.' %
105
             resource.get_display_name().lower()), *args, **kwargs)
106
107
        self.parser.add_argument('command_text',
108
                                 metavar='command',
109
                                 help=help)
110
        self.parser.add_argument('-h', '--help',
111
                                 action='store_true', dest='help',
112
                                 help='Print usage for the given action.')
113
        self.parser.add_argument('-u', '--user', type=str, default=None,
114
                                 help='User under which to run the action (admins only).')
115
116
    @resource.add_auth_token_to_kwargs_from_cli
117
    def run(self, args, **kwargs):
118
        alias_match = ActionAliasMatch()
119
        alias_match.command = args.command_text
120
121
        action_alias, representation = self.manager.match(alias_match, **kwargs)
122
123
        execution = ActionAliasExecution()
124
        execution.name = action_alias.name
125
        execution.format = representation
126
        execution.command = args.command_text
127
        execution.source_channel = 'cli'  # ?
128
        execution.notification_channel = None
129
        execution.notification_route = None
130
        execution.user = args.user
131
132
        action_exec_mgr = self.app.client.managers['ActionAliasExecution']
133
134
        execution = action_exec_mgr.create(execution, **kwargs)
135
        return execution
136
137
    def run_and_print(self, args, **kwargs):
138
        execution = self.run(args, **kwargs)
139
        print("Matching Action-alias: '%s'" % execution.actionalias['ref'])
140
        print("To get the results, execute:\n st2 execution get %s" %
141
              (execution.execution['id']))
142