Beispiel #1
0
 def eval(self):
     if not self.args.issue_project:
         raise UsageError(
             'project must be specified when creating an issue')
     if not (self.args.issue_parent or self.args.issue_type):
         self.args.issue_type = 'bug'
     if self.args.issue_type and not self.args.issue_type.lower(
     ) in self.jira.get_issue_types().keys(
     ) + self.jira.get_subtask_issue_types().keys():
         raise UsageError(
             "invalid issue type: %s (try using jira-cli "
             "list issue_types or jira-cli list subtask_types)" %
             self.args.issue_type)
     if self.args.issue_parent:
         if not self.args.issue_type:
             self.args.issue_type = 'sub-task'
         if not self.args.issue_type in self.jira.get_subtask_issue_types():
             raise UsageError(
                 "issues created with parents must be one of {%s}" %
                 ",".join(self.jira.get_subtask_issue_types()))
     description = self.args.issue_description or get_text_from_editor()
     print_output(
         self.jira.format_issue(
             self.jira.create_issue(self.args.issue_project,
                                    self.args.issue_type, self.args.title,
                                    description, self.args.issue_priority,
                                    self.args.issue_parent)))
Beispiel #2
0
    def show_work_log(self):
        issue = self.jira.get_issue(self.args.jira_id)
        if not issue:
            return

        if "timetracking" in issue and hasattr(issue["timetracking"],
                                               "originalEstimate"):
            print_output("{}: {}".format(
                colorfunc("Estimated", "white"),
                colorfunc(issue["timetracking"].originalEstimate, "blue")))

            print_output("{}: {}".format(
                colorfunc("Remaining", "white"),
                colorfunc(issue["timetracking"].remainingEstimate, "blue")))

            time_spent_seconds = getattr(issue["timetracking"],
                                         "timeSpentSeconds", 0)

            if time_spent_seconds <= issue[
                    "timetracking"].originalEstimateSeconds:
                color = "green"
            else:
                color = "red"

            print_output("{}: {}".format(
                colorfunc("Logged   ", "white"),
                colorfunc(
                    getattr(issue["timetracking"], "timeSpent",
                            str(time_spent_seconds) + "m"), color)))
        print_output("")

        worklogs = issue["worklog"].worklogs
        for worklog in worklogs:
            print_output(self.format_worklog(worklog))
Beispiel #3
0
    def eval(self):
        if self.args.oneline:
            mode = -1
        elif self.args.verbosity > 1:
            mode = self.args.verbosity
        else:
            mode = 0
        if self.args.search_freetext:
            issues = self.jira.search_issues(self.args.search_freetext, project = self.args.project)
        elif self.args.search_jql:
            issues = self.jira.search_issues_jql(self.args.search_jql)
        elif self.args.filter:
            issues = self.jira.get_issues_by_filter(*self.args.filter)
        else:
            issues = filter(lambda issue:issue is not None, [self.jira.get_issue(jira.upper()) for jira in self.args.jira_ids])

        for issue in issues:
            print_output(self.jira.format_issue(
                issue,
                mode=mode,
                formatter=self.args.format,
                comments_only=self.args.comments_only,
                last_comment=self.args.last_comment,
                num_comments=self.args.num_comments
            ))
Beispiel #4
0
    def eval(self):
        if self.args.oneline:
            mode = -1
        elif self.args.verbosity > 1:
            mode = self.args.verbosity
        else:
            mode = 0
        if self.args.search_freetext:
            issues = self.jira.search_issues(self.args.search_freetext, project=self.args.project)
        elif self.args.search_jql:
            issues = self.jira.search_issues_jql(self.args.search_jql)
        elif self.args.filter:
            issues = self.jira.get_issues_by_filter(*self.args.filter)
        else:
            issues = filter(lambda issue: issue is not None, [self.jira.get_issue(jira) for jira in self.args.jira_ids])

        for issue in issues:
            if self.args.debug:
                pprint.pprint(issue, stream=sys.stderr)
            print_output(self.jira.format_issue(
                issue,
                mode=mode,
                formatter=self.args.format,
                comments_only=self.args.comments_only
            ))
Beispiel #5
0
    def eval(self):
        if self.args.oneline:
            mode = -1
        elif self.args.verbosity > 1:
            mode = self.args.verbosity
        else:
            mode = 0
        if self.args.search_freetext:
            issues = self.jira.search_issues(self.args.search_freetext,
                                             project=self.args.project)
        elif self.args.search_jql:
            issues = self.jira.search_issues_jql(self.args.search_jql)
        elif self.args.filter:
            issues = self.jira.get_issues_by_filter(*self.args.filter)
        else:
            issues = [
                issue for issue in
                [self.jira.get_issue(jira) for jira in self.args.jira_ids]
                if issue is not None
            ]

        for issue in issues:
            print_output(
                self.jira.format_issue(issue,
                                       mode=mode,
                                       formatter=self.args.format,
                                       comments_only=self.args.comments_only))
Beispiel #6
0
def cli(args=sys.argv[1:]):
    import optparse
    alias_config = Config(section='alias')
    if set(list(alias_config.items().keys())).intersection(args):
        for alias, target in list(alias_config.items()).items():
            if args[0] == alias:
                args = shlex.split(target) + args[1:]
                break
    parser = build_parser()
    try:
        config = Config()
        pre_opts, pre_args = None, None
        try:
            optparser = optparse.OptionParser()

            def void(*args):
                raise SystemExit()

            optparser.print_usage = void
            optparser.add_option("", "--version", action='store_true', default=False)
            pre_opts, pre_args = optparser.parse_args(args)
        except SystemExit:
            pass
        if pre_opts and pre_opts.version:
            print(__version__)
            return
        if not (pre_opts and ("configure" in pre_args or "clear_cache" in pre_args)):
            post_args = parser.parse_args(args)
            jira = initialize(
                config, post_args.jira_url, post_args.username, post_args.password,
                persist=not (post_args.username or post_args.jira_url),
                protocol='rest'
            )
            return post_args.cmd(jira, post_args).execute()
        else:
            if "configure" in pre_args:
                config.reset()
                initialize(
                    config, "", "", "", True,
                    protocol='rest'
                )
            elif "clear_cache" in pre_args:
                clear_cache()
                print_output(colorfunc("jira-cli cache cleared", "green"))
            return

    except KeyboardInterrupt:
        print_error("aborted", severity=WARNING)
    except UsageWarning as e:
        print_error(str(e), severity=WARNING)
    except (JiraCliError, UsageError) as e:
        print_error(str(e))
    except (WebFault) as e:
        print_error(JiraCliError(e))
    except (JIRAError) as e:
        print_error(JiraCliError(e))
    except NotImplementedError as e:
        print_error(e)
Beispiel #7
0
def cli(args=sys.argv[1:]):
    parser = build_parser()
    try:
        config = Config()
        pre_opts, pre_args = None, None
        try:
            pre_opts, pre_args = fake_parse(args)
        except StopIteration:
            pre_opts, pre_args = None, None
            if "--v1" in args or config.v1:
                if '--v1' in sys.argv:
                    print_error(
                        "Use of the v1 interface is no longer supported. Please refer to jiracli.readthedocs.io",
                        WARNING
                    )
                    sys.argv.remove("--v1")
                return old_main()
        except SystemExit:
            pass
        if pre_opts and pre_opts.version:
            print(__version__)
            return
        if (
            not (pre_opts or pre_args) or (pre_opts and not (pre_opts.v1 or config.v1))
            and not (pre_opts and ("configure" in pre_args or "clear_cache" in pre_args))
        ):
            post_args = parser.parse_args(args)
            jira = initialize(
                config, post_args.jira_url, post_args.username, post_args.password,
                persist=not (post_args.username or post_args.jira_url),
                protocol=post_args.protocol or config.protocol or 'rest'
            )
            return post_args.cmd(jira, post_args).execute()
        else:
            if "configure" in pre_args:
                config.reset()
                initialize(
                    config, "", "", "", True,
                    protocol=pre_opts.protocol or config.protocol or 'soap'
                )
            elif "clear_cache" in pre_args:
                clear_cache()
                print_output(colorfunc("jira-cli cache cleared", "green"))
            return

    except KeyboardInterrupt:
        print_error("aborted", severity=WARNING)
    except UsageWarning as e:
        print_error(str(e), severity=WARNING)
    except (JiraCliError, UsageError) as e:
        print_error(str(e))
    except (WebFault) as e:
        print_error(JiraCliError(e))
    except (JIRAError) as e:
        print_error(JiraCliError(e))
    except NotImplementedError as e:
        print_error(e)
Beispiel #8
0
def cli(args=sys.argv[1:]):
    parser = build_parser()
    try:
        config = Config()
        pre_opts, pre_args = None, None
        try:
            pre_opts, pre_args = fake_parse(args)
        except StopIteration:
            pre_opts, pre_args = None, None
            if not ("--v2" in args or config.v2):
                return old_main()
        except SystemExit:
            pass
        if pre_opts and pre_opts.version:
            print(__version__)
            return
        if (not (pre_opts or pre_args)
                or (pre_opts and (pre_opts.v2 or config.v2)) and
                not (pre_opts and
                     ("configure" in pre_args or "clear_cache" in pre_args))):
            post_args = parser.parse_args(args)
            jira = initialize(
                config,
                post_args.jira_url,
                post_args.username,
                post_args.password,
                persist=not (post_args.username or post_args.jira_url),
                protocol=post_args.protocol or config.protocol or 'soap')
            return post_args.cmd(jira, post_args).execute()
        else:
            if "configure" in pre_args:
                config.reset()
                initialize(config,
                           "",
                           "",
                           "",
                           True,
                           protocol=pre_opts.protocol or config.protocol
                           or 'soap')
            elif "clear_cache" in pre_args:
                clear_cache()
                print_output(colorfunc("jira-cli cache cleared", "green"))
            return

    except KeyboardInterrupt:
        print_error("aborted", severity=WARNING)
    except UsageWarning as e:
        print_error(str(e), severity=WARNING)
    except (JiraCliError, UsageError) as e:
        print_error(str(e))
    except (WebFault) as e:
        print_error(JiraCliError(e))
    except (JIRAError) as e:
        print_error(JiraCliError(e))
    except NotImplementedError as e:
        print_error(e)
Beispiel #9
0
 def eval(self):
     mappers = {
         "issue_types": (self.jira.get_issue_types, ),
         'subtask_types': (self.jira.get_subtask_issue_types, ),
         'projects': (self.jira.get_projects, ),
         'priorities': (self.jira.get_priorities, ),
         'statuses': (self.jira.get_statuses, ),
         'resolutions': (self.jira.get_resolutions, ),
         'components': (self.jira.get_components, 'project'),
         'versions': (self.jira.list_versions, 'project'),
         'transitions': (self.jira.get_available_transitions, 'issue'),
         'filters': (self.jira.get_filters, ),
         'aliases': (lambda: [{
             "name": k,
             "description": v
         } for k, v in list(Config(section='alias').items()).items()], )
     }
     func, arguments = mappers[self.args.type][0], mappers[
         self.args.type][1:]
     _ = []
     _k = {}
     for earg in arguments:
         if isinstance(earg, tuple):
             if getattr(self.args, earg[0]):
                 _k.update({earg[0]: getattr(self.args, earg[0])})
             else:
                 _k[earg[0]] = earg[1]
         else:
             if not getattr(self.args, earg):
                 raise UsageError("'--%s' is required for listing '%s'" %
                                  (earg, self.args.type))
             _.append(getattr(self.args, earg))
     found = False
     data = func(*_, **_k)
     data_dict = OrderedDict()
     if type(data) == type([]):
         for item in data:
             data_dict[item['name']] = item
     else:
         data_dict = data
     for item in list(data_dict.values()):
         found = True
         val = item
         if type(item) == type({}):
             val = colorfunc(item['name'], 'white')
             if 'key' in item and item['key']:
                 val += " [" + colorfunc(item['key'], 'magenta') + "]"
             if 'description' in item and item['description']:
                 val += " [" + colorfunc(item['description'], 'green') + "]"
         print_output(colorfunc(val, 'white'))
     if not found:
         raise UsageWarning("No %s found." % self.args.type)
Beispiel #10
0
 def eval(self):
     extras = {}
     if self.args.extra_fields:
         extras = self.extract_extras()
     if not self.args.issue_project:
         raise UsageError("project must be specified when creating an issue")
     if not (self.args.issue_parent or self.args.issue_type):
         self.args.issue_type = "bug"
     if (
         self.args.issue_type
         and not self.args.issue_type.lower()
         in self.jira.get_issue_types().keys() + self.jira.get_subtask_issue_types().keys()
     ):
         raise UsageError(
             "invalid issue type: %s (try using jira-cli "
             "list issue_types or jira-cli list subtask_types)" % self.args.issue_type
         )
     if self.args.issue_parent:
         if not self.args.issue_type:
             self.args.issue_type = "sub-task"
         if not self.args.issue_type in self.jira.get_subtask_issue_types():
             raise UsageError(
                 "issues created with parents must be one of {%s}" % ",".join(self.jira.get_subtask_issue_types())
             )
     components = {}
     if self.args.issue_components:
         valid_components = dict((k["name"], k["id"]) for k in self.jira.get_components(self.args.issue_project))
         if not set(self.args.issue_components).issubset(valid_components):
             raise UsageError(
                 "components for project %s should be one of {%s}"
                 % (self.args.issue_project, ",".join(valid_components))
             )
         else:
             components = {k: valid_components[k] for k in self.args.issue_components}
     description = self.args.issue_description or get_text_from_editor()
     print_output(
         self.jira.format_issue(
             self.jira.create_issue(
                 self.args.issue_project,
                 self.args.issue_type,
                 self.args.title,
                 description,
                 self.args.issue_priority,
                 self.args.issue_parent,
                 self.args.issue_assignee,
                 self.args.issue_reporter,
                 self.args.labels,
                 components,
                 **extras
             )
         )
     )
Beispiel #11
0
 def eval(self):
     extras = {}
     if self.args.extra_fields:
         extras = self.extract_extras()
     if not self.args.issue_project:
         raise UsageError(
             'project must be specified when creating an issue')
     if not (self.args.issue_parent or self.args.issue_type):
         self.args.issue_type = 'bug'
     if self.args.issue_type and not self.args.issue_type.lower() in list(
             self.jira.get_issue_types().keys()) + list(
                 self.jira.get_subtask_issue_types().keys()):
         raise UsageError(
             "invalid issue type: %s (try using jira-cli "
             "list issue_types or jira-cli list subtask_types)" %
             self.args.issue_type)
     if self.args.issue_parent:
         if not self.args.issue_type:
             self.args.issue_type = 'sub-task'
         if self.args.issue_type not in self.jira.get_subtask_issue_types():
             raise UsageError(
                 "issues created with parents must be one of {%s}" %
                 ",".join(self.jira.get_subtask_issue_types()))
     components = {}
     if self.args.issue_components:
         valid_components = dict(
             (k["name"], k["id"])
             for k in self.jira.get_components(self.args.issue_project))
         if not set(self.args.issue_components).issubset(valid_components):
             raise UsageError(
                 "components for project %s should be one of {%s}" %
                 (self.args.issue_project, ",".join(valid_components)))
         else:
             components = {
                 k: valid_components[k]
                 for k in self.args.issue_components
             }
     if self.args.issue_description is not None:
         description = self.args.issue_description
     else:
         description = get_text_from_editor()
     print_output(
         self.jira.format_issue(
             self.jira.create_issue(
                 self.args.issue_project, self.args.issue_type,
                 self.args.title, description, self.args.issue_priority,
                 self.args.issue_parent, self.args.issue_assignee,
                 self.args.issue_reporter, self.args.labels, components,
                 **extras)))
Beispiel #12
0
 def eval(self):
     extras = {}
     if self.args.extra_fields:
         try:
             for item in self.args.extra_fields:
                 key, value = item.split("=")
                 if key in extras:
                     if not isinstance(extras[key], list):
                         v = [extras[key]]
                         extras[key] = v
                     extras[key].append(value)
                 else:
                     extras[key] = value
         except Exception:
             raise UsageWarning("Unknown extra fields %s" % (self.args.extra_fields))
         self.jira.update_issue(
             self.args.issue,
             **extras
         )
     if self.args.issue_comment:
         self.jira.add_comment(
             self.args.issue, self.args.issue_comment if isinstance(self.args.issue_comment, basestring) else get_text_from_editor()
         )
         print_output(self.jira.format_issue(self.jira.get_issue(self.args.issue), comments_only=True))
     elif self.args.issue_priority:
         self.jira.update_issue(
             self.args.issue,
             priority=self.jira.get_priorities()[self.args.issue_priority]["id"]
         )
     elif self.args.issue_components:
         components = dict(
             (k["name"], k["id"]) for k in self.jira.get_components(
                 self.args.issue.split("-")[0]
             )
         )
         current_components = set(k["name"] for k in self.jira.get_issue(self.args.issue)["components"])
         if not set(self.args.issue_components).issubset(current_components):
             new_components = current_components.union(self.args.issue_components)
             self.jira.update_issue(self.args.issue,
                                    components=[components[k] for k in new_components]
             )
             print_output(colorfunc(
                 'component(s): %s added to %s' % (
                     ",".join(self.args.issue_components), self.args.issue), 'green'
             ))
         else:
             raise UsageWarning("component(s):[%s] already exist in %s" % (
                 ",".join(self.args.issue_components), self.args.issue)
             )
     elif self.args.issue_transition:
         self.jira.transition_issue(self.args.issue, self.args.issue_transition.lower())
         print_output(colorfunc(
             '%s transitioned to "%s"' % (self.args.issue, self.args.issue_transition), 'green'
         ))
     elif self.args.issue_assignee:
         self.jira.assign_issue(self.args.issue, self.args.issue_assignee)
         print_output(colorfunc(
             '%s assigned to %s' % (self.args.issue, self.args.issue_assignee), 'green'
         ))
Beispiel #13
0
    def eval(self):
        if self.args.search_freetext:
            issues = self.jira.search_issues(self.args.search_freetext,
                                             project=self.args.project)
        elif self.args.search_jql:
            issues = self.jira.search_issues_jql(self.args.search_jql)
        elif self.args.filter:
            issues = self.jira.get_issues_by_filter(*self.args.filter)
        else:
            issues = [
                issue for issue in
                [self.jira.get_issue(jira) for jira in self.args.jira_ids]
                if issue is not None
            ]

        for issue in issues:
            # get the time estimate values

            if "student" in issue["labels"]:
                print_output(u"{} is a student task, skipping...\n".format(
                    issue["key"]))
                continue

            estimate = self.spent_time_or_estimate(issue, quiet=True)
            if estimate is None:
                print_error(u"{} has no time estimate\n".format(issue["key"]),
                            severity=WARNING)
                continue

            # get the epic of this issue (warning if none)
            bookkeeping_story = self.get_parent_story(issue)
            if bookkeeping_story is None:
                print_error(u"{} has no parent story. Assignee: {}\n".format(
                    issue["key"], issue["assignee"]),
                            severity=WARNING)
                continue

            # check if the issue in question was already mentioned in the comments
            if self.issue_already_substracted(issue, bookkeeping_story):
                print_output(
                    u"{} already mentioned in the comments of {}\n".format(
                        issue["key"], bookkeeping_story["key"]))
            else:
                self.adjust_story_timetracking(
                    bookkeeping_story,
                    issue,
                    dry=self.args.dry,
                    verbose=(self.args.verbosity > 0))
Beispiel #14
0
 def eval(self):
     mappers = {
         "issue_types": (self.jira.get_issue_types,),
         "subtask_types": (self.jira.get_subtask_issue_types,),
         "projects": (self.jira.get_projects,),
         "priorities": (self.jira.get_priorities,),
         "statuses": (self.jira.get_statuses,),
         "resolutions": (self.jira.get_resolutions,),
         "components": (self.jira.get_components, "project"),
         "versions": (self.jira.list_versions, "project"),
         "transitions": (self.jira.get_available_transitions, "issue"),
         "filters": (self.jira.get_filters,),
     }
     func, arguments = mappers[self.args.type][0], mappers[self.args.type][1:]
     _ = []
     _k = {}
     for earg in arguments:
         if isinstance(earg, tuple):
             if getattr(self.args, earg[0]):
                 _k.update({earg[0]: getattr(self.args, earg[0])})
             else:
                 _k[earg[0]] = earg[1]
         else:
             if not getattr(self.args, earg):
                 raise UsageError("'--%s' is required for listing '%s'" % (earg, self.args.type))
             _.append(getattr(self.args, earg))
     found = False
     data = func(*_, **_k)
     data_dict = OrderedDict()
     if type(data) == type([]):
         for item in data:
             data_dict[item["name"]] = item
     else:
         data_dict = data
     for item in data_dict.values():
         found = True
         val = item
         if type(item) == type({}):
             val = colorfunc(item["name"], "white")
             if "key" in item and item["key"]:
                 val += " [" + colorfunc(item["key"], "magenta") + "]"
             if "description" in item and item["description"]:
                 val += " [" + colorfunc(item["description"], "green") + "]"
         print_output(colorfunc(val, "white"))
     if not found:
         raise UsageWarning("No %s found." % self.args.type)
Beispiel #15
0
def cli(args=sys.argv[1:]):
    parser = build_parser()

    try:
        config = Config()
        pre_opts, pre_args = None, None
        try:
            pre_opts, pre_args = fake_parse(args)
        except StopIteration:
            pre_opts, pre_args = None, None
            if not ("--v2" in args or config.v2):
                return old_main()
        except SystemExit:
            pass
        if (
            not (pre_opts or pre_args) or (pre_opts and pre_opts.v2)
            and not (pre_opts and ("configure" in pre_args or "clear_cache" in pre_args))
        ):
            post_args = parser.parse_args(args)
            jira = initialize(
                config, post_args.jira_url, post_args.username, post_args.password,
                persist=not (post_args.username or post_args.jira_url),
                protocol=post_args.protocol or config.protocol
            )
            return post_args.cmd(jira, post_args).execute()
        else:
            if "configure" in pre_args:
                config.reset()
                initialize(config, "", "", "", True)
            elif "clear_cache" in pre_args:
                clear_cache()
                print_output(colorfunc("jira-cli cache cleared", "green"))
            return

    except KeyboardInterrupt:
        print_error("aborted", severity=WARNING)
    except UsageWarning as e:
        print_error(str(e), severity=WARNING)
    except (JiraCliError, UsageError) as e:
        print_error(str(e))
    except (WebFault) as e:
        print_error(JiraCliError(e))
    except (JIRAError) as e:
        print_error(JiraCliError(e))
    except NotImplementedError as e:
        print_error(e)
Beispiel #16
0
 def eval(self):
     mappers = {
         "issue_types": (self.jira.get_issue_types,),
         'subtask_types': (self.jira.get_subtask_issue_types,),
         'projects': (self.jira.get_projects,),
         'priorities': (self.jira.get_priorities,),
         'statuses': (self.jira.get_statuses,),
         'resolutions': (self.jira.get_resolutions,),
         'components': (self.jira.get_components, 'project'),
         'transitions': (self.jira.get_available_transitions, 'issue'),
         'filters': (self.jira.get_filters,)
     }
     func, arguments = mappers[self.args.type][0], mappers[self.args.type][1:]
     _ = []
     _k = {}
     for earg in arguments:
         if isinstance(earg, tuple):
             if getattr(self.args, earg[0]):
                 _k.update({earg[0]: getattr(self.args, earg[0])})
             else:
                 _k[earg[0]] = earg[1]
         else:
             if not getattr(self.args, earg):
                 raise UsageError("'--%s' is required for listing '%s'" % (earg, self.args.type))
             _.append(getattr(self.args, earg))
     found = False
     data = func(*_, **_k)
     data_dict = {}
     if type(data) == type([]):
         for item in data:
             data_dict[item['name']] = item
     else:
         data_dict = data
     for item in data_dict.values():
         found = True
         val = item
         if type(item) == type({}):
             val = colorfunc(item['name'], 'white')
             if 'key' in item and item['key']:
                 val += " [" + colorfunc(item['key'], 'magenta') + "]"
             if 'description' in item and item['description']:
                 val += " [" + colorfunc(item['description'], 'green') + "]"
         print_output(colorfunc(val, 'white'))
     if not found:
         raise UsageWarning("No %s found." % self.args.type)
Beispiel #17
0
    def adjust_story_timetracking(self, story, issue, dry=True, verbose=True):
        timetracking = story["timetracking"]
        estimate = self.spent_time_or_estimate(issue)
        estimate_human_readable = self.secs_to_human_readable(estimate)
        issue = self.jira.get_issue(issue["key"], raw=True)
        message = str(u"{}: {}: reduced by {}".format(
            issue.fields.assignee.displayName, issue.key,
            estimate_human_readable))

        new_original_raw = timetracking.originalEstimateSeconds - estimate
        new_remaining_raw = timetracking.remainingEstimateSeconds - estimate

        if new_original_raw < 0 or new_remaining_raw < 0:
            print_error(
                u"Story {} full. Estimate would become negative, skipping\n".
                format(story["key"]),
                severity=WARNING)
            return

        new_original = self.secs_to_human_readable(new_original_raw)
        new_remaining = self.secs_to_human_readable(new_remaining_raw)

        if verbose:
            msg = u"Adjusting estimate of story [{}]: {}".format(
                story["key"], story["summary"])
            msg += u"\nby issue [{}]: {}".format(issue.key,
                                                 issue.fields.summary)
            print_output(colorfunc(msg, "blue"))
            print_output(u"{}: {} - {} = {}".format(
                colorfunc("Original Estimate",
                          "white"), timetracking.originalEstimate,
                estimate_human_readable, new_original))
            print_output(u"{}: {} - {} = {}".format(
                colorfunc("Remaning Estimate",
                          "white"), timetracking.remainingEstimate,
                estimate_human_readable, new_remaining))
            print_output("comment: {}".format(colorfunc(message, "white")))
            print("")

        if not dry:
            # fields = {
            #    "timetracking": {"originalEstimate": "3w 2d 1h", "remainingEstimate": "3w 2d 1h"}}
            story = self.jira.get_issue(story["key"], raw=True)
            story.update(
                fields={
                    "timetracking": {
                        "originalEstimate": new_original,
                        "remainingEstimate": new_remaining
                    }
                })
            self.jira.add_comment(story, message)
Beispiel #18
0
    def eval(self):
        if self.args.oneline:
            mode = -1
        elif self.args.verbosity > 1:
            mode = self.args.verbosity
        else:
            mode = 0
        if self.args.search_freetext:
            issues = self.jira.search_issues(self.args.search_freetext, project=self.args.project)
        elif self.args.search_jql:
            issues = self.jira.search_issues_jql(self.args.search_jql)
        elif self.args.filter:
            issues = self.jira.get_issues_by_filter(*self.args.filter)
        else:
            issues = filter(lambda issue: issue is not None, [self.jira.get_issue(jira) for jira in self.args.jira_ids])

        for issue in issues:
            print_output(
                self.jira.format_issue(
                    issue, mode=mode, formatter=self.args.format, comments_only=self.args.comments_only
                )
            )
Beispiel #19
0
 def eval(self):
     if not self.args.issue_project:
         raise UsageError('project must be specified when creating an issue')
     if not (self.args.issue_parent or self.args.issue_type):
         self.args.issue_type = 'bug'
     if self.args.issue_type and not self.args.issue_type in self.jira.get_issue_types().keys() + self.jira.get_subtask_issue_types().keys():
         raise UsageError(
             "invalid issue type: %s (try using jira-cli "
             "list issue_types or jira-cli list subtask_types)" % self.args.issue_type
         )
     if self.args.issue_parent:
         if not self.args.issue_type:
             self.args.issue_type = 'sub-task'
         if not self.args.issue_type in self.jira.get_subtask_issue_types():
             raise UsageError(
                 "issues created with parents must be one of {%s}" % ",".join(self.jira.get_subtask_issue_types())
             )
     description = self.args.issue_description or get_text_from_editor()
     print_output(self.jira.format_issue(
         self.jira.create_issue(self.args.issue_project, self.args.issue_type, self.args.title, description,
                            self.args.issue_priority, self.args.issue_parent)
     ))
Beispiel #20
0
 def eval(self):
     if self.args.issue_comment:
         self.jira.add_comment(self.args.issue, get_text_from_editor())
         print_output(
             self.jira.format_issue(self.jira.get_issue(self.args.issue),
                                    comments_only=True))
     elif self.args.issue_priority:
         self.jira.update_issue(self.args.issue,
                                priority=self.jira.get_priorities()[
                                    self.args.issue_priority]["id"])
     elif self.args.issue_components:
         components = dict((k["name"], k["id"])
                           for k in self.jira.get_components(
                               self.args.issue.split("-")[0]))
         current_components = set(
             k["name"]
             for k in self.jira.get_issue(self.args.issue)["components"])
         if not set(
                 self.args.issue_components).issubset(current_components):
             new_components = current_components.union(
                 self.args.issue_components)
             self.jira.update_issue(
                 self.args.issue,
                 components=[components[k] for k in new_components])
             print_output(
                 colorfunc(
                     'component(s): %s added to %s' % (",".join(
                         self.args.issue_components), self.args.issue),
                     'green'))
         else:
             raise UsageWarning(
                 "component(s):[%s] already exist in %s" %
                 (",".join(self.args.issue_components), self.args.issue))
     elif self.args.issue_transition:
         self.jira.transition_issue(self.args.issue,
                                    self.args.issue_transition.lower())
         print_output(
             colorfunc(
                 '%s transitioned to "%s"' %
                 (self.args.issue, self.args.issue_transition), 'green'))
     elif self.args.issue_assignee:
         self.jira.update_issue(self.args.issue,
                                assignee=self.args.issue_assignee)
         print_output(
             colorfunc(
                 '%s assigned to %s' %
                 (self.args.issue, self.args.issue_assignee), 'green'))
Beispiel #21
0
 def eval(self):
     if self.args.issue_comment:
         self.jira.add_comment(
             self.args.issue, self.args.issue_comment if isinstance(self.args.issue_comment, basestring) else get_text_from_editor()
         )
         print_output(self.jira.format_issue(self.jira.get_issue(self.args.issue), comments_only=True))
     elif self.args.issue_priority:
         self.jira.update_issue(
             self.args.issue,
             priority=self.jira.get_priorities()[self.args.issue_priority]["id"]
         )
     elif self.args.issue_components:
         components = dict(
             (k["name"], k["id"]) for k in self.jira.get_components(
                 self.args.issue.split("-")[0]
             )
         )
         current_components = set(k["name"] for k in self.jira.get_issue(self.args.issue)["components"])
         if not set(self.args.issue_components).issubset(current_components):
             new_components = current_components.union(self.args.issue_components)
             self.jira.update_issue(self.args.issue,
                                    components=[components[k] for k in new_components]
             )
             print_output(colorfunc(
                 'component(s): %s added to %s' % (
                     ",".join(self.args.issue_components), self.args.issue), 'green'
             ))
         else:
             raise UsageWarning("component(s):[%s] already exist in %s" % (
                 ",".join(self.args.issue_components), self.args.issue)
             )
     elif self.args.issue_transition:
         self.jira.transition_issue(self.args.issue, self.args.issue_transition.lower())
         print_output(colorfunc(
             '%s transitioned to "%s"' % (self.args.issue, self.args.issue_transition), 'green'
         ))
     elif self.args.issue_assignee:
         self.jira.update_issue(self.args.issue, assignee=self.args.issue_assignee)
         print_output(colorfunc(
             '%s assigned to %s' % (self.args.issue, self.args.issue_assignee), 'green'
         ))
Beispiel #22
0
 def eval(self):
     if self.args.extra_fields:
         extras = self.extract_extras()
         self.jira.update_issue(self.args.issue, **extras)
     if self.args.issue_comment:
         self.jira.add_comment(
             self.args.issue,
             self.args.issue_comment if isinstance(self.args.issue_comment, basestring) else get_text_from_editor(),
         )
         print_output(self.jira.format_issue(self.jira.get_issue(self.args.issue), comments_only=True))
     elif self.args.issue_priority:
         self.jira.update_issue(self.args.issue, priority=self.jira.get_priorities()[self.args.issue_priority]["id"])
     elif self.args.issue_components:
         components = dict((k["name"], k["id"]) for k in self.jira.get_components(self.args.issue.split("-")[0]))
         current_components = set(k["name"] for k in self.jira.get_issue(self.args.issue)["components"])
         if not set(self.args.issue_components).issubset(current_components):
             new_components = current_components.union(self.args.issue_components)
             self.jira.update_issue(self.args.issue, components=[components[k] for k in new_components])
             print_output(
                 colorfunc(
                     "component(s): %s added to %s" % (",".join(self.args.issue_components), self.args.issue),
                     "green",
                 )
             )
         else:
             raise UsageWarning(
                 "component(s):[%s] already exist in %s" % (",".join(self.args.issue_components), self.args.issue)
             )
     elif self.args.issue_transition:
         self.jira.transition_issue(self.args.issue, self.args.issue_transition.lower(), self.args.resolution)
         print_output(colorfunc('%s transitioned to "%s"' % (self.args.issue, self.args.issue_transition), "green"))
     elif self.args.issue_assignee:
         self.jira.assign_issue(self.args.issue, self.args.issue_assignee)
         print_output(colorfunc("%s assigned to %s" % (self.args.issue, self.args.issue_assignee), "green"))
     elif self.args.labels:
         self.jira.add_labels(self.args.issue, self.args.labels, True)
         print_output(colorfunc("%s labelled with %s" % (self.args.issue, ",".join(self.args.labels)), "green"))
     if self.args.affects_version:
         self.jira.add_versions(self.args.issue, self.args.affects_version, "affects")
         print_output(
             colorfunc(
                 "Added affected version(s) %s to %s" % (",".join(self.args.affects_version), self.args.issue),
                 "green",
             )
         )
     if self.args.remove_affects_version:
         self.jira.remove_versions(self.args.issue, self.args.remove_affects_version, "affects")
         print_output(
             colorfunc(
                 "Removed affected version(s) %s from %s"
                 % (",".join(self.args.remove_affects_version), self.args.issue),
                 "blue",
             )
         )
     if self.args.fix_version:
         self.jira.add_versions(self.args.issue, self.args.fix_version, "fix")
         print_output(
             colorfunc(
                 "Added fixed version(s) %s to %s" % (",".join(self.args.fix_version), self.args.issue), "green"
             )
         )
     if self.args.remove_fix_version:
         self.jira.remove_versions(self.args.issue, self.args.remove_fix_version, "fix")
         print_output(
             colorfunc(
                 "Removed fixed version(s) %s from %s" % (",".join(self.args.remove_fix_version), self.args.issue),
                 "blue",
             )
         )
Beispiel #23
0
 def eval(self):
     if self.args.extra_fields:
         extras = self.extract_extras()
         self.jira.update_issue(self.args.issue, **extras)
     if self.args.issue_comment:
         self.jira.add_comment(
             self.args.issue, self.args.issue_comment if isinstance(
                 self.args.issue_comment, basestring) else
             get_text_from_editor())
         print_output(
             self.jira.format_issue(self.jira.get_issue(self.args.issue),
                                    comments_only=True))
     elif self.args.issue_priority:
         self.jira.update_issue(self.args.issue,
                                priority=self.jira.get_priorities()[
                                    self.args.issue_priority]["id"])
     elif self.args.issue_components:
         components = dict((k["name"], k["id"])
                           for k in self.jira.get_components(
                               self.args.issue.split("-")[0]))
         current_components = set(
             k["name"]
             for k in self.jira.get_issue(self.args.issue)["components"])
         if not set(
                 self.args.issue_components).issubset(current_components):
             new_components = current_components.union(
                 self.args.issue_components)
             self.jira.update_issue(
                 self.args.issue,
                 components=[components[k] for k in new_components])
             print_output(
                 colorfunc(
                     'component(s): %s added to %s' % (",".join(
                         self.args.issue_components), self.args.issue),
                     'green'))
         else:
             raise UsageWarning(
                 "component(s):[%s] already exist in %s" %
                 (",".join(self.args.issue_components), self.args.issue))
     elif self.args.issue_transition:
         self.jira.transition_issue(self.args.issue,
                                    self.args.issue_transition.lower(),
                                    self.args.resolution)
         print_output(
             colorfunc(
                 '%s transitioned to "%s"' %
                 (self.args.issue, self.args.issue_transition), 'green'))
     elif self.args.issue_assignee:
         self.jira.assign_issue(self.args.issue, self.args.issue_assignee)
         print_output(
             colorfunc(
                 '%s assigned to %s' %
                 (self.args.issue, self.args.issue_assignee), 'green'))
     elif self.args.labels:
         self.jira.add_labels(self.args.issue, self.args.labels, True)
         print_output(
             colorfunc(
                 '%s labelled with %s' %
                 (self.args.issue, ",".join(self.args.labels)), 'green'))
     if self.args.affects_version:
         self.jira.add_versions(self.args.issue, self.args.affects_version,
                                'affects')
         print_output(
             colorfunc(
                 'Added affected version(s) %s to %s' %
                 (",".join(self.args.affects_version), self.args.issue),
                 'green'))
     if self.args.remove_affects_version:
         self.jira.remove_versions(self.args.issue,
                                   self.args.remove_affects_version,
                                   'affects')
         print_output(
             colorfunc(
                 'Removed affected version(s) %s from %s' % (",".join(
                     self.args.remove_affects_version), self.args.issue),
                 'blue'))
     if self.args.fix_version:
         self.jira.add_versions(self.args.issue, self.args.fix_version,
                                'fix')
         print_output(
             colorfunc(
                 'Added fixed version(s) %s to %s' %
                 (",".join(self.args.fix_version), self.args.issue),
                 'green'))
     if self.args.remove_fix_version:
         self.jira.remove_versions(self.args.issue,
                                   self.args.remove_fix_version, 'fix')
         print_output(
             colorfunc(
                 'Removed fixed version(s) %s from %s' %
                 (",".join(self.args.remove_fix_version), self.args.issue),
                 'blue'))
Beispiel #24
0
def cli(args=sys.argv[1:]):
    alias_config = Config(section='alias')
    if set(alias_config.items().keys()).intersection(args):
        for alias, target in alias_config.items().items():
            if args[0] == alias:
                args = shlex.split(target) + args[1:]
                break
    parser = build_parser()
    try:
        config = Config()
        pre_opts, pre_args = None, None
        try:
            pre_opts, pre_args = fake_parse(args)
        except StopIteration:
            pre_opts, pre_args = None, None
            if "--v1" in args or config.v1:
                if '--v1' in sys.argv:
                    print_error(
                        "Use of the v1 interface is no longer supported. Please refer to jiracli.readthedocs.io",
                        WARNING)
                    sys.argv.remove("--v1")
                return old_main()
        except SystemExit:
            pass
        if pre_opts and pre_opts.version:
            print(__version__)
            return
        if (not (pre_opts or pre_args)
                or (pre_opts and not (pre_opts.v1 or config.v1)) and
                not (pre_opts and
                     ("configure" in pre_args or "clear_cache" in pre_args))):
            post_args = parser.parse_args(args)
            jira = initialize(
                config,
                post_args.jira_url,
                post_args.username,
                post_args.password,
                persist=not (post_args.username or post_args.jira_url),
                protocol=post_args.protocol or config.protocol or 'rest')
            return post_args.cmd(jira, post_args).execute()
        else:
            if "configure" in pre_args:
                config.reset()
                initialize(config,
                           "",
                           "",
                           "",
                           True,
                           protocol=pre_opts.protocol or config.protocol
                           or 'soap')
            elif "clear_cache" in pre_args:
                clear_cache()
                print_output(colorfunc("jira-cli cache cleared", "green"))
            return

    except KeyboardInterrupt:
        print_error("aborted", severity=WARNING)
    except UsageWarning as e:
        print_error(str(e), severity=WARNING)
    except (JiraCliError, UsageError) as e:
        print_error(str(e))
    except (WebFault) as e:
        print_error(JiraCliError(e))
    except (JIRAError) as e:
        print_error(JiraCliError(e))
    except NotImplementedError as e:
        print_error(e)