Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame^] | 1 | # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style |
| 3 | # license that can be found in the LICENSE file or at |
| 4 | # https://developers.google.com/open-source/licenses/bsd |
| 5 | |
| 6 | """Convert Monorail PB objects to API PB objects""" |
| 7 | |
| 8 | from __future__ import division |
| 9 | from __future__ import print_function |
| 10 | from __future__ import absolute_import |
| 11 | |
| 12 | import datetime |
| 13 | import logging |
| 14 | import time |
| 15 | |
| 16 | from six import string_types |
| 17 | |
| 18 | from businesslogic import work_env |
| 19 | from framework import exceptions |
| 20 | from framework import framework_constants |
| 21 | from framework import framework_helpers |
| 22 | from framework import framework_views |
| 23 | from framework import permissions |
| 24 | from framework import timestr |
| 25 | from proto import api_pb2_v1 |
| 26 | from proto import project_pb2 |
| 27 | from proto import tracker_pb2 |
| 28 | from services import project_svc |
| 29 | from tracker import field_helpers |
| 30 | from tracker import tracker_bizobj |
| 31 | from tracker import tracker_helpers |
| 32 | |
| 33 | |
| 34 | def convert_project(project, config, role, templates): |
| 35 | """Convert Monorail Project PB to API ProjectWrapper PB.""" |
| 36 | |
| 37 | return api_pb2_v1.ProjectWrapper( |
| 38 | kind='monorail#project', |
| 39 | name=project.project_name, |
| 40 | externalId=project.project_name, |
| 41 | htmlLink='/p/%s/' % project.project_name, |
| 42 | summary=project.summary, |
| 43 | description=project.description, |
| 44 | role=role, |
| 45 | issuesConfig=convert_project_config(config, templates)) |
| 46 | |
| 47 | |
| 48 | def convert_project_config(config, templates): |
| 49 | """Convert Monorail ProjectIssueConfig PB to API ProjectIssueConfig PB.""" |
| 50 | |
| 51 | return api_pb2_v1.ProjectIssueConfig( |
| 52 | kind='monorail#projectIssueConfig', |
| 53 | restrictToKnown=config.restrict_to_known, |
| 54 | defaultColumns=config.default_col_spec.split(), |
| 55 | defaultSorting=config.default_sort_spec.split(), |
| 56 | statuses=[convert_status(s) for s in config.well_known_statuses], |
| 57 | labels=[convert_label(l) for l in config.well_known_labels], |
| 58 | prompts=[convert_template(t) for t in templates], |
| 59 | defaultPromptForMembers=config.default_template_for_developers, |
| 60 | defaultPromptForNonMembers=config.default_template_for_users) |
| 61 | |
| 62 | |
| 63 | def convert_status(status): |
| 64 | """Convert Monorail StatusDef PB to API Status PB.""" |
| 65 | |
| 66 | return api_pb2_v1.Status( |
| 67 | status=status.status, |
| 68 | meansOpen=status.means_open, |
| 69 | description=status.status_docstring) |
| 70 | |
| 71 | |
| 72 | def convert_label(label): |
| 73 | """Convert Monorail LabelDef PB to API Label PB.""" |
| 74 | |
| 75 | return api_pb2_v1.Label( |
| 76 | label=label.label, |
| 77 | description=label.label_docstring) |
| 78 | |
| 79 | |
| 80 | def convert_template(template): |
| 81 | """Convert Monorail TemplateDef PB to API Prompt PB.""" |
| 82 | |
| 83 | return api_pb2_v1.Prompt( |
| 84 | name=template.name, |
| 85 | title=template.summary, |
| 86 | description=template.content, |
| 87 | titleMustBeEdited=template.summary_must_be_edited, |
| 88 | status=template.status, |
| 89 | labels=template.labels, |
| 90 | membersOnly=template.members_only, |
| 91 | defaultToMember=template.owner_defaults_to_member, |
| 92 | componentRequired=template.component_required) |
| 93 | |
| 94 | |
| 95 | def convert_person(user_id, cnxn, services, trap_exception=False): |
| 96 | """Convert user id to API AtomPerson PB or None if user_id is None.""" |
| 97 | |
| 98 | if not user_id: |
| 99 | # convert_person should handle 'converting' optional user values, |
| 100 | # like issue.owner, where user_id may be None. |
| 101 | return None |
| 102 | if user_id == framework_constants.DELETED_USER_ID: |
| 103 | return api_pb2_v1.AtomPerson( |
| 104 | kind='monorail#issuePerson', |
| 105 | name=framework_constants.DELETED_USER_NAME) |
| 106 | try: |
| 107 | user = services.user.GetUser(cnxn, user_id) |
| 108 | except exceptions.NoSuchUserException as ex: |
| 109 | if trap_exception: |
| 110 | logging.warning(str(ex)) |
| 111 | return None |
| 112 | else: |
| 113 | raise ex |
| 114 | |
| 115 | days_ago = None |
| 116 | if user.last_visit_timestamp: |
| 117 | secs_ago = int(time.time()) - user.last_visit_timestamp |
| 118 | days_ago = secs_ago // framework_constants.SECS_PER_DAY |
| 119 | return api_pb2_v1.AtomPerson( |
| 120 | kind='monorail#issuePerson', |
| 121 | name=user.email, |
| 122 | htmlLink='https://%s/u/%d' % (framework_helpers.GetHostPort(), user_id), |
| 123 | last_visit_days_ago=days_ago, |
| 124 | email_bouncing=bool(user.email_bounce_timestamp), |
| 125 | vacation_message=user.vacation_message) |
| 126 | |
| 127 | |
| 128 | def convert_issue_ids(issue_ids, mar, services): |
| 129 | """Convert global issue ids to API IssueRef PB.""" |
| 130 | |
| 131 | # missed issue ids are filtered out. |
| 132 | issues = services.issue.GetIssues(mar.cnxn, issue_ids) |
| 133 | result = [] |
| 134 | for issue in issues: |
| 135 | issue_ref = api_pb2_v1.IssueRef( |
| 136 | issueId=issue.local_id, |
| 137 | projectId=issue.project_name, |
| 138 | kind='monorail#issueRef') |
| 139 | result.append(issue_ref) |
| 140 | return result |
| 141 | |
| 142 | |
| 143 | def convert_issueref_pbs(issueref_pbs, mar, services): |
| 144 | """Convert API IssueRef PBs to global issue ids.""" |
| 145 | |
| 146 | if issueref_pbs: |
| 147 | result = [] |
| 148 | for ir in issueref_pbs: |
| 149 | project_id = mar.project_id |
| 150 | if ir.projectId: |
| 151 | project = services.project.GetProjectByName( |
| 152 | mar.cnxn, ir.projectId) |
| 153 | if project: |
| 154 | project_id = project.project_id |
| 155 | try: |
| 156 | issue = services.issue.GetIssueByLocalID( |
| 157 | mar.cnxn, project_id, ir.issueId) |
| 158 | result.append(issue.issue_id) |
| 159 | except exceptions.NoSuchIssueException: |
| 160 | logging.warning( |
| 161 | 'Issue (%s:%d) does not exist.' % (ir.projectId, ir.issueId)) |
| 162 | return result |
| 163 | else: |
| 164 | return None |
| 165 | |
| 166 | |
| 167 | def convert_approvals(cnxn, approval_values, services, config, phases): |
| 168 | """Convert an Issue's Monorail ApprovalValue PBs to API Approval""" |
| 169 | fds_by_id = {fd.field_id: fd for fd in config.field_defs} |
| 170 | phases_by_id = {phase.phase_id: phase for phase in phases} |
| 171 | approvals = [] |
| 172 | for av in approval_values: |
| 173 | approval_fd = fds_by_id.get(av.approval_id) |
| 174 | if approval_fd is None: |
| 175 | logging.warning( |
| 176 | 'Approval (%d) does not exist' % av.approval_id) |
| 177 | continue |
| 178 | if approval_fd.field_type is not tracker_pb2.FieldTypes.APPROVAL_TYPE: |
| 179 | logging.warning( |
| 180 | 'field %s has unexpected field_type: %s' % ( |
| 181 | approval_fd.field_name, approval_fd.field_type.name)) |
| 182 | continue |
| 183 | |
| 184 | approval = api_pb2_v1.Approval() |
| 185 | approval.approvalName = approval_fd.field_name |
| 186 | approvers = [convert_person(approver_id, cnxn, services) |
| 187 | for approver_id in av.approver_ids] |
| 188 | approval.approvers = [approver for approver in approvers if approver] |
| 189 | |
| 190 | approval.status = api_pb2_v1.ApprovalStatus(av.status.number) |
| 191 | if av.setter_id: |
| 192 | approval.setter = convert_person(av.setter_id, cnxn, services) |
| 193 | if av.set_on: |
| 194 | approval.setOn = datetime.datetime.fromtimestamp(av.set_on) |
| 195 | if av.phase_id: |
| 196 | try: |
| 197 | approval.phaseName = phases_by_id[av.phase_id].name |
| 198 | except KeyError: |
| 199 | logging.warning('phase %d not found in given phases list' % av.phase_id) |
| 200 | approvals.append(approval) |
| 201 | return approvals |
| 202 | |
| 203 | |
| 204 | def convert_phases(phases): |
| 205 | """Convert an Issue's Monorail Phase PBs to API Phase.""" |
| 206 | converted_phases = [] |
| 207 | for idx, phase in enumerate(phases): |
| 208 | if not phase.name: |
| 209 | try: |
| 210 | logging.warning( |
| 211 | 'Phase %d has no name, skipping conversion.' % phase.phase_id) |
| 212 | except TypeError: |
| 213 | logging.warning( |
| 214 | 'Phase #%d (%s) has no name or id, skipping conversion.' % ( |
| 215 | idx, phase)) |
| 216 | continue |
| 217 | converted = api_pb2_v1.Phase(phaseName=phase.name, rank=phase.rank) |
| 218 | converted_phases.append(converted) |
| 219 | return converted_phases |
| 220 | |
| 221 | |
| 222 | def convert_issue(cls, issue, mar, services): |
| 223 | """Convert Monorail Issue PB to API IssuesGetInsertResponse.""" |
| 224 | |
| 225 | config = services.config.GetProjectConfig(mar.cnxn, issue.project_id) |
| 226 | granted_perms = tracker_bizobj.GetGrantedPerms( |
| 227 | issue, mar.auth.effective_ids, config) |
| 228 | issue_project = services.project.GetProject(mar.cnxn, issue.project_id) |
| 229 | component_list = [] |
| 230 | for cd in config.component_defs: |
| 231 | cid = cd.component_id |
| 232 | if cid in issue.component_ids: |
| 233 | component_list.append(cd.path) |
| 234 | cc_list = [convert_person(p, mar.cnxn, services) for p in issue.cc_ids] |
| 235 | cc_list = [p for p in cc_list if p is not None] |
| 236 | field_values_list = [] |
| 237 | fds_by_id = { |
| 238 | fd.field_id: fd for fd in config.field_defs} |
| 239 | phases_by_id = {phase.phase_id: phase for phase in issue.phases} |
| 240 | for fv in issue.field_values: |
| 241 | fd = fds_by_id.get(fv.field_id) |
| 242 | if not fd: |
| 243 | logging.warning('Custom field %d of project %s does not exist', |
| 244 | fv.field_id, issue_project.project_name) |
| 245 | continue |
| 246 | val = None |
| 247 | if fv.user_id: |
| 248 | val = _get_user_email( |
| 249 | services.user, mar.cnxn, fv.user_id) |
| 250 | else: |
| 251 | val = tracker_bizobj.GetFieldValue(fv, {}) |
| 252 | if not isinstance(val, string_types): |
| 253 | val = str(val) |
| 254 | new_fv = api_pb2_v1.FieldValue( |
| 255 | fieldName=fd.field_name, |
| 256 | fieldValue=val, |
| 257 | derived=fv.derived) |
| 258 | if fd.approval_id: # Attach parent approval name |
| 259 | approval_fd = fds_by_id.get(fd.approval_id) |
| 260 | if not approval_fd: |
| 261 | logging.warning('Parent approval field %d of field %s does not exist', |
| 262 | fd.approval_id, fd.field_name) |
| 263 | else: |
| 264 | new_fv.approvalName = approval_fd.field_name |
| 265 | elif fv.phase_id: # Attach phase name |
| 266 | phase = phases_by_id.get(fv.phase_id) |
| 267 | if not phase: |
| 268 | logging.warning('Phase %d for field %s does not exist', |
| 269 | fv.phase_id, fd.field_name) |
| 270 | else: |
| 271 | new_fv.phaseName = phase.name |
| 272 | field_values_list.append(new_fv) |
| 273 | approval_values_list = convert_approvals( |
| 274 | mar.cnxn, issue.approval_values, services, config, issue.phases) |
| 275 | phases_list = convert_phases(issue.phases) |
| 276 | with work_env.WorkEnv(mar, services) as we: |
| 277 | starred = we.IsIssueStarred(issue) |
| 278 | resp = cls( |
| 279 | kind='monorail#issue', |
| 280 | id=issue.local_id, |
| 281 | title=issue.summary, |
| 282 | summary=issue.summary, |
| 283 | projectId=issue_project.project_name, |
| 284 | stars=issue.star_count, |
| 285 | starred=starred, |
| 286 | status=issue.status, |
| 287 | state=(api_pb2_v1.IssueState.open if |
| 288 | tracker_helpers.MeansOpenInProject( |
| 289 | tracker_bizobj.GetStatus(issue), config) |
| 290 | else api_pb2_v1.IssueState.closed), |
| 291 | labels=issue.labels, |
| 292 | components=component_list, |
| 293 | author=convert_person(issue.reporter_id, mar.cnxn, services), |
| 294 | owner=convert_person(issue.owner_id, mar.cnxn, services), |
| 295 | cc=cc_list, |
| 296 | updated=datetime.datetime.fromtimestamp(issue.modified_timestamp), |
| 297 | published=datetime.datetime.fromtimestamp(issue.opened_timestamp), |
| 298 | blockedOn=convert_issue_ids(issue.blocked_on_iids, mar, services), |
| 299 | blocking=convert_issue_ids(issue.blocking_iids, mar, services), |
| 300 | canComment=permissions.CanCommentIssue( |
| 301 | mar.auth.effective_ids, mar.perms, issue_project, issue, |
| 302 | granted_perms=granted_perms), |
| 303 | canEdit=permissions.CanEditIssue( |
| 304 | mar.auth.effective_ids, mar.perms, issue_project, issue, |
| 305 | granted_perms=granted_perms), |
| 306 | fieldValues=field_values_list, |
| 307 | approvalValues=approval_values_list, |
| 308 | phases=phases_list |
| 309 | ) |
| 310 | if issue.closed_timestamp > 0: |
| 311 | resp.closed = datetime.datetime.fromtimestamp(issue.closed_timestamp) |
| 312 | if issue.merged_into: |
| 313 | resp.mergedInto=convert_issue_ids([issue.merged_into], mar, services)[0] |
| 314 | if issue.owner_modified_timestamp: |
| 315 | resp.owner_modified = datetime.datetime.fromtimestamp( |
| 316 | issue.owner_modified_timestamp) |
| 317 | if issue.status_modified_timestamp: |
| 318 | resp.status_modified = datetime.datetime.fromtimestamp( |
| 319 | issue.status_modified_timestamp) |
| 320 | if issue.component_modified_timestamp: |
| 321 | resp.component_modified = datetime.datetime.fromtimestamp( |
| 322 | issue.component_modified_timestamp) |
| 323 | return resp |
| 324 | |
| 325 | |
| 326 | def convert_comment(issue, comment, mar, services, granted_perms): |
| 327 | """Convert Monorail IssueComment PB to API IssueCommentWrapper.""" |
| 328 | |
| 329 | perms = permissions.UpdateIssuePermissions( |
| 330 | mar.perms, mar.project, issue, mar.auth.effective_ids, |
| 331 | granted_perms=granted_perms) |
| 332 | commenter = services.user.GetUser(mar.cnxn, comment.user_id) |
| 333 | can_delete = permissions.CanDeleteComment( |
| 334 | comment, commenter, mar.auth.user_id, perms) |
| 335 | |
| 336 | return api_pb2_v1.IssueCommentWrapper( |
| 337 | attachments=[convert_attachment(a) for a in comment.attachments], |
| 338 | author=convert_person(comment.user_id, mar.cnxn, services, |
| 339 | trap_exception=True), |
| 340 | canDelete=can_delete, |
| 341 | content=comment.content, |
| 342 | deletedBy=convert_person(comment.deleted_by, mar.cnxn, services, |
| 343 | trap_exception=True), |
| 344 | id=comment.sequence, |
| 345 | published=datetime.datetime.fromtimestamp(comment.timestamp), |
| 346 | updates=convert_amendments(issue, comment.amendments, mar, services), |
| 347 | kind='monorail#issueComment', |
| 348 | is_description=comment.is_description) |
| 349 | |
| 350 | def convert_approval_comment(issue, comment, mar, services, granted_perms): |
| 351 | perms = permissions.UpdateIssuePermissions( |
| 352 | mar.perms, mar.project, issue, mar.auth.effective_ids, |
| 353 | granted_perms=granted_perms) |
| 354 | commenter = services.user.GetUser(mar.cnxn, comment.user_id) |
| 355 | can_delete = permissions.CanDeleteComment( |
| 356 | comment, commenter, mar.auth.user_id, perms) |
| 357 | |
| 358 | return api_pb2_v1.ApprovalCommentWrapper( |
| 359 | attachments=[convert_attachment(a) for a in comment.attachments], |
| 360 | author=convert_person( |
| 361 | comment.user_id, mar.cnxn, services, trap_exception=True), |
| 362 | canDelete=can_delete, |
| 363 | content=comment.content, |
| 364 | deletedBy=convert_person(comment.deleted_by, mar.cnxn, services, |
| 365 | trap_exception=True), |
| 366 | id=comment.sequence, |
| 367 | published=datetime.datetime.fromtimestamp(comment.timestamp), |
| 368 | approvalUpdates=convert_approval_amendments( |
| 369 | comment.amendments, mar, services), |
| 370 | kind='monorail#approvalComment', |
| 371 | is_description=comment.is_description) |
| 372 | |
| 373 | |
| 374 | def convert_attachment(attachment): |
| 375 | """Convert Monorail Attachment PB to API Attachment.""" |
| 376 | |
| 377 | return api_pb2_v1.Attachment( |
| 378 | attachmentId=attachment.attachment_id, |
| 379 | fileName=attachment.filename, |
| 380 | fileSize=attachment.filesize, |
| 381 | mimetype=attachment.mimetype, |
| 382 | isDeleted=attachment.deleted) |
| 383 | |
| 384 | |
| 385 | def convert_amendments(issue, amendments, mar, services): |
| 386 | """Convert a list of Monorail Amendment PBs to API Update.""" |
| 387 | amendments_user_ids = tracker_bizobj.UsersInvolvedInAmendments(amendments) |
| 388 | users_by_id = framework_views.MakeAllUserViews( |
| 389 | mar.cnxn, services.user, amendments_user_ids) |
| 390 | framework_views.RevealAllEmailsToMembers( |
| 391 | mar.cnxn, services, mar.auth, users_by_id, mar.project) |
| 392 | |
| 393 | result = api_pb2_v1.Update(kind='monorail#issueCommentUpdate') |
| 394 | for amendment in amendments: |
| 395 | if amendment.field == tracker_pb2.FieldID.SUMMARY: |
| 396 | result.summary = amendment.newvalue |
| 397 | elif amendment.field == tracker_pb2.FieldID.STATUS: |
| 398 | result.status = amendment.newvalue |
| 399 | elif amendment.field == tracker_pb2.FieldID.OWNER: |
| 400 | if len(amendment.added_user_ids) == 0: |
| 401 | result.owner = framework_constants.NO_USER_NAME |
| 402 | else: |
| 403 | result.owner = _get_user_email( |
| 404 | services.user, mar.cnxn, amendment.added_user_ids[0]) |
| 405 | elif amendment.field == tracker_pb2.FieldID.LABELS: |
| 406 | result.labels = amendment.newvalue.split() |
| 407 | elif amendment.field == tracker_pb2.FieldID.CC: |
| 408 | for user_id in amendment.added_user_ids: |
| 409 | user_email = _get_user_email( |
| 410 | services.user, mar.cnxn, user_id) |
| 411 | result.cc.append(user_email) |
| 412 | for user_id in amendment.removed_user_ids: |
| 413 | user_email = _get_user_email( |
| 414 | services.user, mar.cnxn, user_id) |
| 415 | result.cc.append('-%s' % user_email) |
| 416 | elif amendment.field == tracker_pb2.FieldID.BLOCKEDON: |
| 417 | result.blockedOn = _append_project( |
| 418 | amendment.newvalue, issue.project_name) |
| 419 | elif amendment.field == tracker_pb2.FieldID.BLOCKING: |
| 420 | result.blocking = _append_project( |
| 421 | amendment.newvalue, issue.project_name) |
| 422 | elif amendment.field == tracker_pb2.FieldID.MERGEDINTO: |
| 423 | result.mergedInto = amendment.newvalue |
| 424 | elif amendment.field == tracker_pb2.FieldID.COMPONENTS: |
| 425 | result.components = amendment.newvalue.split() |
| 426 | elif amendment.field == tracker_pb2.FieldID.CUSTOM: |
| 427 | fv = api_pb2_v1.FieldValue() |
| 428 | fv.fieldName = amendment.custom_field_name |
| 429 | fv.fieldValue = tracker_bizobj.AmendmentString(amendment, users_by_id) |
| 430 | result.fieldValues.append(fv) |
| 431 | |
| 432 | return result |
| 433 | |
| 434 | |
| 435 | def convert_approval_amendments(amendments, mar, services): |
| 436 | """Convert a list of Monorail Amendment PBs API ApprovalUpdate.""" |
| 437 | amendments_user_ids = tracker_bizobj.UsersInvolvedInAmendments(amendments) |
| 438 | users_by_id = framework_views.MakeAllUserViews( |
| 439 | mar.cnxn, services.user, amendments_user_ids) |
| 440 | framework_views.RevealAllEmailsToMembers( |
| 441 | mar.cnxn, services, mar.auth, users_by_id, mar.project) |
| 442 | |
| 443 | result = api_pb2_v1.ApprovalUpdate(kind='monorail#approvalCommentUpdate') |
| 444 | for amendment in amendments: |
| 445 | if amendment.field == tracker_pb2.FieldID.CUSTOM: |
| 446 | if amendment.custom_field_name == 'Status': |
| 447 | status_number = tracker_pb2.ApprovalStatus( |
| 448 | amendment.newvalue.upper()).number |
| 449 | result.status = api_pb2_v1.ApprovalStatus(status_number).name |
| 450 | elif amendment.custom_field_name == 'Approvers': |
| 451 | for user_id in amendment.added_user_ids: |
| 452 | user_email = _get_user_email( |
| 453 | services.user, mar.cnxn, user_id) |
| 454 | result.approvers.append(user_email) |
| 455 | for user_id in amendment.removed_user_ids: |
| 456 | user_email = _get_user_email( |
| 457 | services.user, mar.cnxn, user_id) |
| 458 | result.approvers.append('-%s' % user_email) |
| 459 | else: |
| 460 | fv = api_pb2_v1.FieldValue() |
| 461 | fv.fieldName = amendment.custom_field_name |
| 462 | fv.fieldValue = tracker_bizobj.AmendmentString(amendment, users_by_id) |
| 463 | # TODO(jojwang): monorail:4229, add approvalName field to FieldValue |
| 464 | result.fieldValues.append(fv) |
| 465 | |
| 466 | return result |
| 467 | |
| 468 | |
| 469 | def _get_user_email(user_service, cnxn, user_id): |
| 470 | """Get user email.""" |
| 471 | |
| 472 | if user_id == framework_constants.DELETED_USER_ID: |
| 473 | return framework_constants.DELETED_USER_NAME |
| 474 | if not user_id: |
| 475 | # _get_user_email should handle getting emails for optional user values, |
| 476 | # like issue.owner where user_id may be None. |
| 477 | return framework_constants.NO_USER_NAME |
| 478 | try: |
| 479 | user_email = user_service.LookupUserEmail( |
| 480 | cnxn, user_id) |
| 481 | except exceptions.NoSuchUserException: |
| 482 | user_email = framework_constants.USER_NOT_FOUND_NAME |
| 483 | return user_email |
| 484 | |
| 485 | |
| 486 | def _append_project(issue_ids, project_name): |
| 487 | """Append project name to convert <id> to <project>:<id> format.""" |
| 488 | |
| 489 | result = [] |
| 490 | id_list = issue_ids.split() |
| 491 | for id_str in id_list: |
| 492 | if ':' in id_str: |
| 493 | result.append(id_str) |
| 494 | # '-' means this issue is being removed |
| 495 | elif id_str.startswith('-'): |
| 496 | result.append('-%s:%s' % (project_name, id_str[1:])) |
| 497 | else: |
| 498 | result.append('%s:%s' % (project_name, id_str)) |
| 499 | return result |
| 500 | |
| 501 | |
| 502 | def split_remove_add(item_list): |
| 503 | """Split one list of items into two: items to add and items to remove.""" |
| 504 | |
| 505 | list_to_add = [] |
| 506 | list_to_remove = [] |
| 507 | |
| 508 | for item in item_list: |
| 509 | if item.startswith('-'): |
| 510 | list_to_remove.append(item[1:]) |
| 511 | else: |
| 512 | list_to_add.append(item) |
| 513 | |
| 514 | return list_to_add, list_to_remove |
| 515 | |
| 516 | |
| 517 | # TODO(sheyang): batch the SQL queries to fetch projects/issues. |
| 518 | def issue_global_ids(project_local_id_pairs, project_id, mar, services): |
| 519 | """Find global issues ids given <project_name>:<issue_local_id> pairs.""" |
| 520 | |
| 521 | result = [] |
| 522 | for pair in project_local_id_pairs: |
| 523 | issue_project_id = None |
| 524 | local_id = None |
| 525 | if ':' in pair: |
| 526 | pair_ary = pair.split(':') |
| 527 | project_name = pair_ary[0] |
| 528 | local_id = int(pair_ary[1]) |
| 529 | project = services.project.GetProjectByName(mar.cnxn, project_name) |
| 530 | if not project: |
| 531 | raise exceptions.NoSuchProjectException( |
| 532 | 'Project %s does not exist' % project_name) |
| 533 | issue_project_id = project.project_id |
| 534 | else: |
| 535 | issue_project_id = project_id |
| 536 | local_id = int(pair) |
| 537 | result.append( |
| 538 | services.issue.LookupIssueID(mar.cnxn, issue_project_id, local_id)) |
| 539 | |
| 540 | return result |
| 541 | |
| 542 | |
| 543 | def convert_group_settings(group_name, setting): |
| 544 | """Convert UserGroupSettings to UserGroupSettingsWrapper.""" |
| 545 | return api_pb2_v1.UserGroupSettingsWrapper( |
| 546 | groupName=group_name, |
| 547 | who_can_view_members=setting.who_can_view_members, |
| 548 | ext_group_type=setting.ext_group_type, |
| 549 | last_sync_time=setting.last_sync_time) |
| 550 | |
| 551 | |
| 552 | def convert_component_def(cd, mar, services): |
| 553 | """Convert ComponentDef PB to Component PB.""" |
| 554 | project_name = services.project.LookupProjectNames( |
| 555 | mar.cnxn, [cd.project_id])[cd.project_id] |
| 556 | user_ids = set() |
| 557 | user_ids.update( |
| 558 | cd.admin_ids + cd.cc_ids + [cd.creator_id] + [cd.modifier_id]) |
| 559 | user_names_dict = services.user.LookupUserEmails(mar.cnxn, list(user_ids)) |
| 560 | component = api_pb2_v1.Component( |
| 561 | componentId=cd.component_id, |
| 562 | projectName=project_name, |
| 563 | componentPath=cd.path, |
| 564 | description=cd.docstring, |
| 565 | admin=sorted([user_names_dict[uid] for uid in cd.admin_ids]), |
| 566 | cc=sorted([user_names_dict[uid] for uid in cd.cc_ids]), |
| 567 | deprecated=cd.deprecated) |
| 568 | if cd.created: |
| 569 | component.created = datetime.datetime.fromtimestamp(cd.created) |
| 570 | component.creator = user_names_dict[cd.creator_id] |
| 571 | if cd.modified: |
| 572 | component.modified = datetime.datetime.fromtimestamp(cd.modified) |
| 573 | component.modifier = user_names_dict[cd.modifier_id] |
| 574 | return component |
| 575 | |
| 576 | |
| 577 | def convert_component_ids(config, component_names): |
| 578 | """Convert a list of component names to ids.""" |
| 579 | component_names_lower = [name.lower() for name in component_names] |
| 580 | result = [] |
| 581 | for cd in config.component_defs: |
| 582 | cpath = cd.path |
| 583 | if cpath.lower() in component_names_lower: |
| 584 | result.append(cd.component_id) |
| 585 | return result |
| 586 | |
| 587 | |
| 588 | def convert_field_values(field_values, mar, services): |
| 589 | """Convert user passed in field value list to FieldValue PB, or labels.""" |
| 590 | fv_list_add = [] |
| 591 | fv_list_remove = [] |
| 592 | fv_list_clear = [] |
| 593 | label_list_add = [] |
| 594 | label_list_remove = [] |
| 595 | field_name_dict = { |
| 596 | fd.field_name: fd for fd in mar.config.field_defs} |
| 597 | |
| 598 | for fv in field_values: |
| 599 | field_def = field_name_dict.get(fv.fieldName) |
| 600 | if not field_def: |
| 601 | logging.warning('Custom field %s of does not exist', fv.fieldName) |
| 602 | continue |
| 603 | |
| 604 | if fv.operator == api_pb2_v1.FieldValueOperator.clear: |
| 605 | fv_list_clear.append(field_def.field_id) |
| 606 | continue |
| 607 | |
| 608 | # Enum fields are stored as labels |
| 609 | if field_def.field_type == tracker_pb2.FieldTypes.ENUM_TYPE: |
| 610 | raw_val = '%s-%s' % (fv.fieldName, fv.fieldValue) |
| 611 | if fv.operator == api_pb2_v1.FieldValueOperator.remove: |
| 612 | label_list_remove.append(raw_val) |
| 613 | elif fv.operator == api_pb2_v1.FieldValueOperator.add: |
| 614 | label_list_add.append(raw_val) |
| 615 | else: # pragma: no cover |
| 616 | logging.warning('Unsupported field value operater %s', fv.operator) |
| 617 | else: |
| 618 | new_fv = field_helpers.ParseOneFieldValue( |
| 619 | mar.cnxn, services.user, field_def, fv.fieldValue) |
| 620 | if fv.operator == api_pb2_v1.FieldValueOperator.remove: |
| 621 | fv_list_remove.append(new_fv) |
| 622 | elif fv.operator == api_pb2_v1.FieldValueOperator.add: |
| 623 | fv_list_add.append(new_fv) |
| 624 | else: # pragma: no cover |
| 625 | logging.warning('Unsupported field value operater %s', fv.operator) |
| 626 | |
| 627 | return (fv_list_add, fv_list_remove, fv_list_clear, |
| 628 | label_list_add, label_list_remove) |