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