当前位置: 首页>>代码示例>>Python>>正文


Python JIRA.transition_issue方法代码示例

本文整理汇总了Python中jira.JIRA.transition_issue方法的典型用法代码示例。如果您正苦于以下问题:Python JIRA.transition_issue方法的具体用法?Python JIRA.transition_issue怎么用?Python JIRA.transition_issue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jira.JIRA的用法示例。


在下文中一共展示了JIRA.transition_issue方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update_jira_story

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
def update_jira_story(story_id, transition_id, comment=None, **kwargs):
    try:
        jira = JIRA("https://thezebra.atlassian.net", basic_auth=(os.environ['username'], os.environ['password']))
        issue = jira.issue(story_id)
        allowed_transitions = {t['id'] for t in jira.transitions(issue)}
        if str(transition_id) not in allowed_transitions:
            app.logger.warn("Story %s cannot transition to %s" % (story_id, transition_id))
        else:
            jira.transition_issue(issue, transition_id)
            if comment:
                jira.add_comment(issue, comment)
    except Exception as ex:
        app.logger.error(ex)
开发者ID:insurancezebra,项目名称:phabira,代码行数:15,代码来源:phabira.py

示例2: JiraApi

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
class JiraApi():

  def __init__(self, instance=None):
    self.instance = instance

  @staticmethod
  def get_datetime_now():
    return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.0+0000")


  def connect(self):
    options = {'server': app.config['JIRA_HOSTNAME'],'verify':False}
    self.instance = JIRA(options,
                basic_auth=(app.config['JIRA_USERNAME'], app.config['JIRA_PASSWORD']))

  @staticmethod
  def ticket_link(issue):
    return '<a href="{}/browse/{}">{}</a>'.format(app.config['JIRA_HOSTNAME'], issue.key, issue.key)

  def resolve(self, issue):
    self.instance.transition_issue(
      issue,
      app.config['JIRA_RESOLVE_TRANSITION_ID'],
      assignee={'name': app.config['JIRA_USERNAME']},
      resolution={'id': app.config['JIRA_RESOLVE_STATE_ID']})

  def defect_for_exception(self, summary_title, e):
    return self.instance.create_issue(
      project='IPGBD',
      summary='[auto-{}] Problem: {}'.format(current_user.username, summary_title),
      description="Exception: {}".format(e),
      customfield_13842=JiraApi.get_datetime_now(),
      customfield_13838= {
        "self": "https://jira.rim.net/rest/api/2/customFieldOption/16680",
        "value": "No",
        "id": "16680"
      },
      customfield_13831 =  [
      {
        "self": "https://jira.rim.net/rest/api/2/customFieldOption/16592",
        "value": "Quality",
        "id": "16592"
      },
      {
        "self": "https://jira.rim.net/rest/api/2/customFieldOption/16594",
        "value": "Risk Avoidance",
        "id": "16594"
      }],
      issuetype={'name': 'Defect'})
开发者ID:healtynet,项目名称:lifeguard,代码行数:51,代码来源:__init__.py

示例3: update_tickets_from_git

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]

#.........这里部分代码省略.........
        self.vprint('-'*80)
        self.vprint('current.keys:', current.keys())

#         try:
#             last_commit = last['GITTRACKER']['current_commit']
#         except KeyError:
#             return
#         current_commit = current['GITTRACKER']['current_commit']

        # Find all tickets deployed between last deployment and now.
        tickets = self.get_tickets_between_commits(current_commit, last_commit)
        self.vprint('tickets:', tickets)

        # Update all tickets in Jira.
        jira = JIRA({
            'server': self.env.server
        }, basic_auth=(self.env.basic_auth_username, self.env.basic_auth_password))
        for ticket in tickets:

            # Mention this Jira updated.
            r.env.role = r.genv.ROLE.lower()
            comment = r.format(self.env.ticket_update_message_template)
            print('Commenting on ticket %s: %s' % (ticket, comment))
            if not self.dryrun:
                jira.add_comment(ticket, comment)

            # Update ticket status.
            recheck = False
            while 1:
                print('Looking up jira ticket %s...' % ticket)
                issue = jira.issue(ticket)
                self.vprint('Ticket %s retrieved.' % ticket)
                transition_to_id = dict((t['name'], t['id']) for t in jira.transitions(issue))
                self.vprint('%i allowable transitions found:' % len(transition_to_id))
                if self.verbose:
                    pprint(transition_to_id)
                self.vprint('issue.fields.status.id:', issue.fields.status.id)
                self.vprint('issue.fields.status.name:', issue.fields.status.name)
                jira_status_id = issue.fields.status.name.title()
                self.vprint('jira_status_id:', jira_status_id)
                next_transition_name = self.env.deploy_workflow.get(jira_status_id)
                self.vprint('next_transition_name:', next_transition_name)
                next_transition_id = transition_to_id.get(next_transition_name)
                self.vprint('next_transition_id:', next_transition_id)
                if next_transition_name:
                    if issue.fields.assignee:
                        if issue.fields.assignee.raw:
                            assignee_name = issue.fields.assignee.name
                        else:
                            # Get assignee name directly
                            # https://community.atlassian.com/t5/Jira-questions/Jira-in-Python-issue-fields-reporter-name-
                            # errors-with-TypeError/qaq-p/937924
                            assignee_name = issue.fields.assignee._session['name']
                    else:
                        assignee_name = None

                    # Get new assignee by status
                    new_assignee = self.env.assignee_by_status.get(
                        #issue.fields.status.name.title(),
                        next_transition_name,
                        assignee_name,
                    )

                    # If assigning to reporter, get reporter name.
                    if new_assignee == 'reporter':
                        if issue.fields.reporter.raw:
                            new_assignee = issue.fields.reporter.name
                        else:
                            # Get reporter name directly
                            # https://community.atlassian.com/t5/Jira-questions/Jira-in-Python-issue-fields-reporter-name-
                            # errors-with-TypeError/qaq-p/937924
                            new_assignee = issue.fields.reporter._session['name']

                    print('Updating ticket %s to status %s (%s) and assigning it to %s.' % (ticket, next_transition_name, next_transition_id, new_assignee))
                    if not self.dryrun:

                        if next_transition_id:
                            try:
                                jira.transition_issue(issue, next_transition_id)
                                recheck = True
                            except AttributeError as e:
                                print('Unable to transition ticket %s to %s: %s' % (ticket, next_transition_name, e), file=sys.stderr)
                                traceback.print_exc()

                        # Note assignment should happen after transition, since the assignment may
                        # effect remove transitions that we need.
                        try:
                            if new_assignee:
                                print('Assigning ticket %s to %s.' % (ticket, new_assignee))
                                jira.assign_issue(issue, new_assignee)
                            else:
                                print('No new assignee found.')
                        except JIRAError as e:
                            print('Unable to reassign ticket %s to %s: %s' % (ticket, new_assignee, e), file=sys.stderr)
                else:
                    recheck = False
                    print('No transitions found for ticket %s currently in status "%s".' % (ticket, issue.fields.status.name))

                if not recheck:
                    break
开发者ID:chrisspen,项目名称:burlap,代码行数:104,代码来源:jirahelper.py

示例4: reopened_task

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
def reopened_task(branch):
    jira = JIRA(options, basic_auth=(JIRA_USERNAME, PASSWORD))
    issue = jira.issue(branch)
    jira.transition_issue(issue, u'Reopened')
    jira.add_comment(branch, 'Autotest fail')
开发者ID:geo2tag,项目名称:geo2tag,代码行数:7,代码来源:find_unsuccessfull_build.py

示例5: __init__

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
class JiraCI:
    resolution_state = {"fixed": "1", "wont fixed": "2", "duplicate": "3", "incomplete": "4", "cannot reproduce": "5",
                        "not a bug": "6", "done": "7"}

    def __init__(self, jira_url, login, password):
        if version_info[1] <= 6:
            options = jira_url
        else:
            options = {"server": jira_url}
        self.jira = JIRA(options, basic_auth=(login, password))

    @staticmethod
    def debug_jira(text):
        stdout.write("[DEBUG JIRA]: {0}\n".format(text))

    def check_issue_exist(self, issue_id):
        try:
            self.jira.issue(issue_id)
        except JIRAError as e:
            print "[-] : {0} - {1}".format(issue_id, e.text)
            return False
        else:
            return True

    def check_issue_state(self, issue_id, issue_state):
        jira_issue = self.jira.issue(issue_id)
        if jira_issue.fields.status.name.lower() == issue_state.lower():
            return True
        else:
            return False

    def add_comment(self, issue_id, comment, formatting=False):
        jira_issue = self.jira.issue(issue_id)
        if formatting:
            comment = "{code}" + comment + "{code}"
        if not self.check_comment_exist(issue_id, comment):
            self.jira.add_comment(jira_issue, comment)
            self.debug_jira("Comment (for {0}) : {1} added".format(issue_id, comment.rstrip()))
        else:
            self.debug_jira("Comment (for {0}) : {1} already exist".format(issue_id, comment.rstrip()))

    def assign_issue(self, issue_id, assigned_user):
        jira_issue = self.jira.issue(issue_id)
        jira_issue.update(assignee={"name": assigned_user})

    def add_link(self, issue_id, title, url):
        url_object = {"url": url, "title": title}
        if not self.check_link_exist(issue_id, title, url):
            self.jira.add_remote_link(issue_id, url_object)
            self.debug_jira("Link (for {0}) : {1} added".format(issue_id, url))
        else:
            self.debug_jira("Link (for {0}) : {1} already exist".format(issue_id, url))

    def resolve_issue_to_reporter(self, issue_id):
        reporter = self.get_reporter_issue(issue_id)
        self.jira.transition_issue(issue_id, "5", resolution={"id": self.resolution_state["fixed"]})
        self.assign_issue(issue_id, reporter)

    def get_reporter_issue(self, issue_id):
        jira_issue = self.jira.issue(issue_id)
        return jira_issue.fields.reporter.name

    def check_comment_exist(self, issue_id, new_comment):
        comments = [c.body for c in self.jira.comments(issue_id)]
        if new_comment in comments:
            return True
        return False

    def check_link_exist(self, issue_id, title, url):
        links = [l.raw["object"] for l in self.jira.remote_links(issue_id)]
        for link in links:
            if link["title"] == title and link["url"] == url:
                return True
        return False

    def resolve_from_git(self, issue_id, short_commit_message, title_url, package_url):
        if self.check_issue_exist(issue_id):
            if not self.check_issue_state(issue_id, "resolved"):
                self.resolve_issue_to_reporter(issue_id)
                self.debug_jira("Issue {0} already resolve".format(issue_id))
            else:
                self.debug_jira("Issue {0} resolved".format(issue_id))
            self.add_link(issue_id, title_url, package_url)
            self.add_comment(issue_id, short_commit_message, formatting=True)

    def refer_from_git(self, issue_id, commit_message):
        if self.check_issue_exist(issue_id):
            self.add_comment(issue_id, commit_message, formatting=True)
开发者ID:nenf,项目名称:gitlab-webhook,代码行数:90,代码来源:jira_ci.py

示例6: open

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
    with open(r"test_cred.dat", "wb") as f:
        username = raw_input("Please enter username: ")
        password = raw_input("Please enter password: ")
        credentials = {username: password}
        pickle.dump(credentials, f)

if credentials:
    for key in credentials:
        username = key
        password = credentials[key]

options = {
    'server': URL2,
    'verify': False
}

ticket = JIRA(options, basic_auth=(username, password))

WO_num = 'WO-266574'

current_issue = ticket.issue(WO_num)

ticket.transition_issue(current_issue, transition = '101') #WORKS. YEAH MF'ERRRR. Closes the ticket
print "here"
"""
current_issue = ticket.issue(WO_num)
close_issue = ticket.transitions(current_issue)
print close_issue
print [(t['id'], t['name']) for t in close_issue]
"""
开发者ID:Chewie23,项目名称:fury-train,代码行数:32,代码来源:close_issue.py

示例7: Jira

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
class Jira(object):
    """
    jira operation class
    """
    def __init__(self, **args):
        """
        Init JIRA connection
        """
        self.server = settings.CASELINK_JIRA['SERVER']
        self.username = settings.CASELINK_JIRA['USER']
        self.password = settings.CASELINK_JIRA['PASSWORD']
        self.verify = False  # TODO: move to settings
        self._jira = JIRA(options={
            'server': self.server,
            'verify': self.verify,
        }, basic_auth=(self.username, self.password))

    def search_issues(self, project_name, jql_str, fields=None):
        """
        Search issue under the project and return result
        """
        jql_str = "project = " + project_name + " and " + jql_str
        return self.jira_.search_issues(jql_str, maxResults=-1, fields=fields)

    def add_comment(self, issue, comment):
        """
        Add comments in the issue
        """
        if isinstance(issue, (str, unicode)):
            issue = self._jira.issue(issue)
        return self._jira.add_comment(issue, comment)

    def transition_issue(self, issue, status):
        """
        Transition issue status to another
        """
        self.jira_.transition_issue(issue, status)

    def get_watchers(self, issue):
        """
        Get a watchers Resource from the server for an issue
        """
        watcher_data = self.jira_.watchers(issue)
        return [str(w.key) for w in watcher_data.watchers]

    def add_watcher(self, issue, watchers):
        """
        Append an issue's watchers list
        """
        new_watchers = []
        if isinstance(watchers, str):
            new_watchers.append(watchers)
        elif isinstance(watchers, list):
            new_watchers = watchers
        for watcher in new_watchers:
            self.jira_.add_watcher(issue, watcher)

    def remove_watcher(self, issue, watchers):
        """
        Remove watchers from an issue's watchers list
        """
        del_watchers = []
        if isinstance(watchers, str):
            del_watchers.append(watchers)
        elif isinstance(watchers, list):
            del_watchers = watchers
        for watcher in del_watchers:
            self.jira_.remove_watcher(issue, watcher)

    def create_issue(self, issue_dict):
        """
        Create Issue and apply some default properties
        """
        dict_ = {
            'project': {
                'key': 'LIBVIRTAT',
            },
            'summary': None,
            'description': None,
            'priority': {
                'name': 'Major',
            },
            'assignee': {
                'name': None
            },
        }

        parent_issue = issue_dict.pop('parent_issue', None) or settings.CASELINK_JIRA['DEFAULT_PARENT_ISSUE']
        assignee = issue_dict.pop('assignee', None) or settings.CASELINK_JIRA['DEFAULT_ASSIGNEE']

        dict_.update({
            'assignee': {
                'name': assignee
            }
        })

        if parent_issue:
            dict_.update({
                'parent': {
                    'id': parent_issue
#.........这里部分代码省略.........
开发者ID:ryncsn,项目名称:caselink,代码行数:103,代码来源:jira.py

示例8: JiraAPI

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]

#.........这里部分代码省略.........
                    self.logger.debug("Checked ticket {} is already closed".format(ticket_obj))
                    self.logger.info("Ticket {} is closed".format(ticket_obj))
                    return True
        self.logger.debug("Checked ticket {} is already open".format(ticket_obj))
        return False


    def is_risk_accepted(self, ticket_obj):
        if ticket_obj is not None:
            if ticket_obj.raw['fields'].get('labels') is not None:
                labels = ticket_obj.raw['fields'].get('labels')
                if "risk_accepted" in labels:
                    self.logger.warn("Ticket {} accepted risk, will be ignored".format(ticket_obj))
                    return True
                elif "server_decomission" in labels:
                    self.logger.warn("Ticket {} server decomissioned, will be ignored".format(ticket_obj))
                    return True
        self.logger.info("Ticket {} risk has not been accepted".format(ticket_obj))
        return False

    def reopen_ticket(self, ticketid):
        self.logger.debug("Ticket {} exists, REOPEN requested".format(ticketid))
        # this will reopen a ticket by ticketid
        ticket_obj = self.jira.issue(ticketid)
        
        if self.is_ticket_resolved(ticket_obj):
            if not self.is_risk_accepted(ticket_obj):
                try:
                    if self.is_ticket_reopenable(ticket_obj):
                        comment = '''This ticket has been reopened due to the vulnerability not having been fixed (if multiple assets are affected, all need to be fixed; if the server is down, lastest known vulnerability might be the one reported).
                        In the case of the team accepting the risk and wanting to close the ticket, please add the label "*risk_accepted*" to the ticket before closing it.
                        If server has been decomissioned, please add the label "*server_decomission*" to the ticket before closing it.
                        If you have further doubts, please contact the Security Team.'''
                        error = self.jira.transition_issue(issue=ticketid, transition=self.JIRA_REOPEN_ISSUE, comment = comment)
                        self.logger.info("Ticket {} reopened successfully".format(ticketid))
                        self.add_label(ticketid, 'reopened')
                        return 1
                except Exception as e:
                    # continue with ticket data so that a new ticket is created in place of the "lost" one
                    self.logger.error("error reopening ticket {}: {}".format(ticketid, e))
                    return 0
        return 0

    def close_ticket(self, ticketid, resolution, comment):
        # this will close a ticket by ticketid
        self.logger.debug("Ticket {} exists, CLOSE requested".format(ticketid))
        ticket_obj = self.jira.issue(ticketid)
        if not self.is_ticket_resolved(ticket_obj):
            try:
                if self.is_ticket_closeable(ticket_obj):
                    #need to add the label before closing the ticket
                    self.add_label(ticketid, 'closed')
                    error = self.jira.transition_issue(issue=ticketid, transition=self.JIRA_CLOSE_ISSUE, comment = comment, resolution = {"name": resolution })
                    self.logger.info("Ticket {} closed successfully".format(ticketid))
                    return 1
            except Exception as e:
                # continue with ticket data so that a new ticket is created in place of the "lost" one
                self.logger.error("error closing ticket {}: {}".format(ticketid, e))
                return 0
                
        return 0

    def close_obsolete_tickets(self):
        # Close tickets older than 12 months, vulnerabilities not solved will get created a new ticket 
        self.logger.info("Closing obsolete tickets older than {} months".format(self.max_time_tracking))
        jql = "labels=vulnerability_management AND created <startOfMonth(-{}) and resolution=Unresolved".format(self.max_time_tracking)
开发者ID:sry309,项目名称:VulnWhisperer,代码行数:70,代码来源:jira_api.py

示例9: JiraApi

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
class JiraApi():

  str_jira_scheduled = "%Y-%m-%dT%H:%M:%S.0%z"

  def __init__(self,
               instance=None,
               approver_instance=None):
    self.instance = instance
    self.approver_instance = approver_instance

  @staticmethod
  def next_immediate_window_dates():
    tz = pytz.timezone(app.config['CM_TZ'])
    now_utc = datetime.utcnow()
    now_tz = tz.localize(now_utc)
    start = None
    if now_tz.hour <= app.config['CM_DEADLINE_HOUR']  and now_tz.minute < app.config['CM_DEADLINE_MIN']:
      start = tz.localize(datetime(now_tz.year, now_tz.month, now_tz.day, app.config['CM_SAME_DAY_START_HOUR']))
    else:
      delay_hours = timedelta(hours=app.config['CM_DEADLINE_MISSED_DELAY_HOURS'])
      start_day = now_tz + delay_hours
      start = tz.localize(datetime(
        start_day.year, start_day.month, start_day.day, app.config['CM_DEADLINE_MISSED_START_HOUR']))
    end = start + timedelta(hours=app.config['CM_WINDOW_LEN_HOURS'])
    return start.strftime(JiraApi.str_jira_scheduled), \
           end.strftime(JiraApi.str_jira_scheduled)

  @staticmethod
  def get_datetime_now():
    tz = pytz.timezone(app.config['CM_TZ'])
    now = pytz.utc.localize(datetime.utcnow()).astimezone(tz)
    return now.strftime(JiraApi.str_jira_scheduled)

  def connect(self):
    options = {'server': app.config['JIRA_HOSTNAME'], 'verify': False, 'check_update': False}
    self.instance = JIRA(options,
                basic_auth=(app.config['JIRA_USERNAME'], app.config['JIRA_PASSWORD']))
    self.approver_instance = JIRA(options,
                basic_auth=(app.config['JIRA_APPROVER_USERNAME'], app.config['JIRA_APPROVER_PASSWORD']))

  @staticmethod
  def ticket_link(issue):
    return '<a href="{}/browse/{}">{}</a>'.format(app.config['JIRA_HOSTNAME'], issue.key, issue.key)

  def resolve(self, issue):
    self.instance.transition_issue(
      issue,
      app.config['JIRA_RESOLVE_TRANSITION_ID'],
      assignee={'name': app.config['JIRA_USERNAME']},
      resolution={'id': app.config['JIRA_RESOLVE_STATE_ID']})

  def defect_for_exception(self, summary_title, e):
    return self.instance.create_issue(
      project=app.config['JIRA_PROJECT'],
      summary='[auto-{}] Problem: {}'.format(current_user.username, summary_title),
      description="Exception: {}".format(e),
      customfield_13842=JiraApi.get_datetime_now(),
      customfield_13838= {"value": "No"},
      customfield_13831 =  [
        {"value": "Quality"},
        {"value": "Risk Avoidance"}
      ],
      issuetype={'name': 'Defect'})
开发者ID:blackberry,项目名称:lifeguard,代码行数:65,代码来源:__init__.py

示例10: __init__

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]

#.........这里部分代码省略.........
    Return:
      A list of issues
    """
    try:
      issues = self.jira.search_issues("project={0} AND summary ~ '{1}'".format(self.project, summary))
    except Exception:
      raise
    return issues


  def get_issue_by_key(self, key):
    """
    Find issue by using the key (e.g BEAM-1234)
    Args:
      key
    Return:
      issue
    """
    try:
      issue = self.jira.issue(key)
    except Exception:
      raise
    return issue


  def create_issue(self, summary, components, description, issuetype='Bug', assignee=None, parent_key=None):
    """
    Create a new issue
    Args:
      summary - Issue title
      components - A list of components
      description (optional) - A string that describes the issue
      issuetype (optional) - Bug, Improvement, New Feature, Sub-task, Task, Wish, etc.
      assignee (optional) - A string of JIRA user name
      parent_key (optional) - The parent issue key is required when creating a subtask.
    Return:
      Issue created
    """
    fields = {
      'project': {'key': self.project},
      'summary': summary,
      'description': description,
      'issuetype': {'name': issuetype},
      'components': [],
    }
    for component in components:
      fields['components'].append({'name': component})
    if assignee is not None:
      fields['assignee'] = {'name': assignee}
    if parent_key is not None:
      fields['parent'] = {'key': parent_key}
      fields['issuetype'] = {'name': 'Sub-task'}
    try:
      new_issue = self.jira.create_issue(fields = fields)
    except Exception:
      raise
    return new_issue


  def update_issue(self, issue, summary=None, components=None, description=None, assignee=None, notify=True):
    """
    Create a new issue
    Args:
      issue - Jira issue object
      summary (optional) - Issue title
      components (optional) - A list of components
      description (optional) - A string that describes the issue
      assignee (optional) - A string of JIRA user name
      notify - Query parameter notifyUsers. If true send the email with notification that the issue was updated to users that watch it.
               Admin or project admin permissions are required to disable the notification.
    Return:
      Issue created
    """
    fields={}
    if summary:
      fields['summary'] = summary
    if description:
      fields['description'] = description
    if assignee:
      fields['assignee'] = {'name': assignee}
    if components:
      fields['components'] = []
      for component in components:
        fields['components'].append({'name': component})
    try:
      issue.update(fields=fields, notify=notify)
    except Exception:
      raise


  def reopen_issue(self, issue):
    """
    Reopen an issue
    Args:
      issue - Jira issue object
    """
    try:
      self.jira.transition_issue(issue.key, 3)
    except:
      raise
开发者ID:charlesccychen,项目名称:incubator-beam,代码行数:104,代码来源:jira_client.py

示例11: jira_client

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]

#.........这里部分代码省略.........
            if "bot-analyzed" not in jira_issue.fields.labels:
                print("Updating issue description: \n" + "\n".join(new_lines))
                jira_issue.update(
                    description=jira_issue.fields.description + "\n".join(new_lines))
            else:
                print("Skipping issue update, since issue is already tagged with 'bot-analyzed'")
        except JIRAError as e:
            print("Error updating JIRA: " + str(e))


# jira.resolutions()
# <JIRA Resolution: name='Fixed', id='1'>
# <JIRA Resolution: name="Won't Fix", id='2'>
# <JIRA Resolution: name='Duplicate', id='3'>
# <JIRA Resolution: name='Incomplete', id='4'>
# <JIRA Resolution: name='Cannot Reproduce', id='5'>
# <JIRA Resolution: name='Works as Designed', id='6'>
# <JIRA Resolution: name='Gone away', id='7'>
# <JIRA Resolution: name='Community Answered', id='8'>
# <JIRA Resolution: name='Done', id='9'>

# Issue link Types
# <JIRA IssueLinkType: name='Backports', id='10420'>
# <JIRA IssueLinkType: name='Depends', id='10011'>
# <JIRA IssueLinkType: name='Documented', id='10320'>
# <JIRA IssueLinkType: name='Duplicate', id='10010'>
# <JIRA IssueLinkType: name='Gantt Dependency', id='10020'>
# <JIRA IssueLinkType: name='Gantt End to End', id='10423'>
# <JIRA IssueLinkType: name='Gantt End to Start', id='10421'>
# <JIRA IssueLinkType: name='Gantt Start to End', id='10424'>
# <JIRA IssueLinkType: name='Gantt Start to Start', id='10422'>
# <JIRA IssueLinkType: name='Related', id='10012'>
# <JIRA IssueLinkType: name='Tested', id='10220'>

    def close_as_duplicate(self, issue, duplicate_issue):

        with self._lock:
            src_issue = self.jira.issue(issue)
            dest_issue = self.jira.issue(duplicate_issue)

            # Add duplicate link
            self.jira.create_issue_link(
                type='Duplicate', inwardIssue=issue, outwardIssue=duplicate_issue)

            # Update affectsVersions, Buildvariants, etc.
            title_parsing_regex = re.compile("(Timed Out|Failures?):"
                                             " (?P<suite_name>.*?)"
                                             " on"
                                             " (?P<variant_prefix>[^\(\[]+)"
                                             "(?P<variant_suffix>"
                                             " (?:"
                                             "\(Clang 3\.7/libc\+\+\)|"
                                             "\(No Journal\)|"
                                             "\(inMemory\)|"
                                             "\(ephemeralForTest\)|"
                                             "\(Unoptimized\))(?: DEBUG)?)?"
                                             " (?:\("
                                             "(?P<test_names>(.*?(\.js|CheckReplDBHash)(, )?)*)"
                                             "\))? ?\[MongoDB \("
                                             "(?P<version>.*?)"
                                             "\) @ [0-9A-Za-z]+\]")

            parsed_title = title_parsing_regex.match(src_issue.fields.summary)
            if parsed_title is not None:
                # Update the failing variants.
                variant = parsed_title.group("variant_prefix").rstrip()
                if parsed_title.group("variant_suffix") is not None:
                    variant += parsed_title.group("variant_suffix").rstrip()

                self.add_affected_variant(dest_issue, variant)

                # Update the failing tasks.
                self.add_failing_task(dest_issue, parsed_title.group("suite_name"))

                # Update the affected versions.
                self.add_affected_version(dest_issue, parsed_title.group("version"))

            # Close - id 2
            # Duplicate issue is 3
            self.jira.transition_issue(src_issue, '2', resolution={'id': '3'})

            mongo_client.remove_issue(issue)

    def close_as_goneaway(self, issue):
        with self._lock:
            src_issue = self.jira.issue(issue)

            # Close - id 2
            # Gone away is 7
            self.jira.transition_issue(
                src_issue, '2', comment="Transient machine issue.", resolution={'id': '7'})

            mongo_client.remove_issue(issue)

    def get_bfg_issue(self, issue_number):
        if not issue_number.startswith("BFG-") and not issue_number.startswith("BF-"):
            issue_number = "BFG-" + issue_number
        with self._lock:
            src_issue = self.jira.issue(issue_number)
        return src_issue
开发者ID:markbenvenuto,项目名称:buildbaron,代码行数:104,代码来源:jira_client.py

示例12: update_tickets_from_git

# 需要导入模块: from jira import JIRA [as 别名]
# 或者: from jira.JIRA import transition_issue [as 别名]
def update_tickets_from_git(last=None, current=None):
    """
    Run during a deployment.
    Looks at all commits between now and the last deployment.
    Finds all ticket numbers and updates their status in Jira.
    """
    from jira import JIRA, JIRAError
    from burlap.deploy import get_last_current_diffs
    from burlap.git import gittracker
    
    get_current_commit = gittracker.get_current_commit
    GITTRACKER = gittracker.name.upper()
    
    dryrun = common.get_dryrun()
    verbose = common.get_verbose()
    
    # Ensure this is only run once per role.
    if env.host_string != env.hosts[-1]:
        return
    
    if not env.jira_update_from_git:
        return
    
    if not env.jira_ticket_pattern:
        return
    
    if not env.jira_basic_auth_username or not env.jira_basic_auth_password:
        return
    
    # During a deployment, we should be given these, but for testing,
    # lookup the diffs dynamically.
    if not last or not current:
        last, current = get_last_current_diffs(GITTRACKER)
    
    if verbose:
        print('-'*80)
        print('last.keys:', last.keys())
        print('-'*80)
        print('current.keys:', current.keys())
    
    try:
        last_commit = last['GITTRACKER']['current_commit']
    except KeyError:
        return
    current_commit = current['GITTRACKER']['current_commit']
    
    # Find all tickets deployed between last deployment and now.
    tickets = get_tickets_between_commits(current_commit, last_commit)
    if verbose:
        print('tickets:', tickets)
    
    # Update all tickets in Jira.
    jira = JIRA({
        'server': env.jira_server
    }, basic_auth=(env.jira_basic_auth_username, env.jira_basic_auth_password))
    for ticket in tickets:
        
        # Mention this Jira updated.
        comment = env.jira_ticket_update_message_template % dict(role=env.ROLE.lower())
        print('Commenting on ticket %s: %s' % (ticket, comment))
        if not dryrun:
            jira.add_comment(ticket, comment) 
        
        # Update ticket status.
        recheck = False
        while 1:
            print('Looking up jira ticket %s...' % ticket)
            issue = jira.issue(ticket)
            print('Ticket %s retrieved.' % ticket)
            transition_to_id = dict((t['name'], t['id']) for t in jira.transitions(issue))
            print('%i allowable transitions found: %s' % (len(transition_to_id), ', '.join(transition_to_id.keys())))
            next_transition_name = env.jira_deploy_workflow.get(issue.fields.status.name.title())
            next_transition_id = transition_to_id.get(next_transition_name)
            if next_transition_name:
                new_fields = {}
                
#                 print('jira_assignee_by_status:', env.jira_assignee_by_status, issue.fields.status.name.title()
                new_assignee = env.jira_assignee_by_status.get(
                    #issue.fields.status.name.title(),
                    next_transition_name,
                    issue.fields.assignee.name,
                )
                if new_assignee == 'reporter':
                    new_assignee = issue.fields.reporter.name
#                 print('new_assignee:', new_assignee)
                    
                print('Updating ticket %s to status %s and assigning it to %s.' \
                    % (ticket, next_transition_name, new_assignee))
                if not dryrun:
                    try:
                        jira.transition_issue(
                            issue,
                            next_transition_id,
                        )
                        recheck = True
                    except AttributeError as e:
                        print('Unable to transition ticket %s to %s: %s' \
                            % (ticket, next_transition_name, e), file=sys.stderr)
                    
                    # Note assignment should happen after transition, since the assignment may
#.........这里部分代码省略.........
开发者ID:noeldvictor,项目名称:burlap,代码行数:103,代码来源:jirahelp.py


注:本文中的jira.JIRA.transition_issue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。