Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 1 | # Copyright 2020 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. |
| 4 | |
| 5 | from __future__ import print_function |
| 6 | from __future__ import division |
| 7 | from __future__ import absolute_import |
| 8 | |
| 9 | import collections |
| 10 | import itertools |
| 11 | import logging |
| 12 | import time |
| 13 | |
| 14 | from google.protobuf import timestamp_pb2 |
| 15 | |
| 16 | from api import resource_name_converters as rnc |
| 17 | from api.v3.api_proto import feature_objects_pb2 |
| 18 | from api.v3.api_proto import issues_pb2 |
| 19 | from api.v3.api_proto import issue_objects_pb2 |
| 20 | from api.v3.api_proto import project_objects_pb2 |
| 21 | from api.v3.api_proto import user_objects_pb2 |
| 22 | |
| 23 | from framework import exceptions |
| 24 | from framework import filecontent |
| 25 | from framework import framework_bizobj |
| 26 | from framework import framework_constants |
| 27 | from framework import framework_helpers |
| 28 | from proto import tracker_pb2 |
| 29 | from project import project_helpers |
| 30 | from tracker import attachment_helpers |
| 31 | from tracker import field_helpers |
| 32 | from tracker import tracker_bizobj as tbo |
| 33 | from tracker import tracker_helpers |
| 34 | |
| 35 | Choice = project_objects_pb2.FieldDef.EnumTypeSettings.Choice |
| 36 | |
| 37 | # Ingest/convert dicts for ApprovalStatus. |
| 38 | _V3_APPROVAL_STATUS = issue_objects_pb2.ApprovalValue.ApprovalStatus.Value |
| 39 | _APPROVAL_STATUS_INGEST = { |
| 40 | _V3_APPROVAL_STATUS('APPROVAL_STATUS_UNSPECIFIED'): None, |
| 41 | _V3_APPROVAL_STATUS('NOT_SET'): tracker_pb2.ApprovalStatus.NOT_SET, |
| 42 | _V3_APPROVAL_STATUS('NEEDS_REVIEW'): tracker_pb2.ApprovalStatus.NEEDS_REVIEW, |
| 43 | _V3_APPROVAL_STATUS('NA'): tracker_pb2.ApprovalStatus.NA, |
| 44 | _V3_APPROVAL_STATUS('REVIEW_REQUESTED'): |
| 45 | tracker_pb2.ApprovalStatus.REVIEW_REQUESTED, |
| 46 | _V3_APPROVAL_STATUS('REVIEW_STARTED'): |
| 47 | tracker_pb2.ApprovalStatus.REVIEW_STARTED, |
| 48 | _V3_APPROVAL_STATUS('NEED_INFO'): tracker_pb2.ApprovalStatus.NEED_INFO, |
| 49 | _V3_APPROVAL_STATUS('APPROVED'): tracker_pb2.ApprovalStatus.APPROVED, |
| 50 | _V3_APPROVAL_STATUS('NOT_APPROVED'): tracker_pb2.ApprovalStatus.NOT_APPROVED, |
| 51 | } |
| 52 | _APPROVAL_STATUS_CONVERT = { |
| 53 | val: key for key, val in _APPROVAL_STATUS_INGEST.items()} |
| 54 | |
| 55 | |
| 56 | class Converter(object): |
| 57 | """Class to manage converting objects between the API and backend layer.""" |
| 58 | |
| 59 | def __init__(self, mc, services): |
| 60 | # type: (MonorailContext, Services) -> Converter |
| 61 | """Create a Converter with the given MonorailContext and Services. |
| 62 | |
| 63 | Args: |
| 64 | mc: MonorailContext object containing the MonorailConnection to the DB |
| 65 | and the requester's AuthData object. |
| 66 | services: Services object for connections to backend services. |
| 67 | """ |
| 68 | self.cnxn = mc.cnxn |
| 69 | self.user_auth = mc.auth |
| 70 | self.services = services |
| 71 | |
| 72 | # Hotlists |
| 73 | |
| 74 | def ConvertHotlist(self, hotlist): |
| 75 | # type: (proto.feature_objects_pb2.Hotlist) |
| 76 | # -> api_proto.feature_objects_pb2.Hotlist |
| 77 | """Convert a protorpc Hotlist into a protoc Hotlist.""" |
| 78 | |
| 79 | hotlist_resource_name = rnc.ConvertHotlistName(hotlist.hotlist_id) |
| 80 | members_by_id = rnc.ConvertUserNames( |
| 81 | hotlist.owner_ids + hotlist.editor_ids) |
| 82 | default_columns = self._ComputeIssuesListColumns(hotlist.default_col_spec) |
| 83 | if hotlist.is_private: |
| 84 | hotlist_privacy = feature_objects_pb2.Hotlist.HotlistPrivacy.Value( |
| 85 | 'PRIVATE') |
| 86 | else: |
| 87 | hotlist_privacy = feature_objects_pb2.Hotlist.HotlistPrivacy.Value( |
| 88 | 'PUBLIC') |
| 89 | |
| 90 | return feature_objects_pb2.Hotlist( |
| 91 | name=hotlist_resource_name, |
| 92 | display_name=hotlist.name, |
| 93 | owner=members_by_id.get(hotlist.owner_ids[0]), |
| 94 | editors=[ |
| 95 | members_by_id.get(editor_id) for editor_id in hotlist.editor_ids |
| 96 | ], |
| 97 | summary=hotlist.summary, |
| 98 | description=hotlist.description, |
| 99 | default_columns=default_columns, |
| 100 | hotlist_privacy=hotlist_privacy) |
| 101 | |
| 102 | def ConvertHotlists(self, hotlists): |
| 103 | # type: (Sequence[proto.feature_objects_pb2.Hotlist]) |
| 104 | # -> Sequence[api_proto.feature_objects_pb2.Hotlist] |
| 105 | """Convert protorpc Hotlists into protoc Hotlists.""" |
| 106 | return [self.ConvertHotlist(hotlist) for hotlist in hotlists] |
| 107 | |
| 108 | def ConvertHotlistItems(self, hotlist_id, items): |
| 109 | # type: (int, Sequence[proto.features_pb2.HotlistItem]) -> |
| 110 | # Sequence[api_proto.feature_objects_pb2.Hotlist] |
| 111 | """Convert a Sequence of protorpc HotlistItems into a Sequence of protoc |
| 112 | HotlistItems. |
| 113 | |
| 114 | Args: |
| 115 | hotlist_id: ID of the Hotlist the items belong to. |
| 116 | items: Sequence of HotlistItem protorpc objects. |
| 117 | |
| 118 | Returns: |
| 119 | Sequence of protoc HotlistItems in the same order they are given in |
| 120 | `items`. |
| 121 | In the rare event that any issues in `items` are not found, they will be |
| 122 | omitted from the result. |
| 123 | """ |
| 124 | issue_ids = [item.issue_id for item in items] |
| 125 | # Converting HotlistItemNames and IssueNames both require looking up the |
| 126 | # issues in the hotlist. However, we want to keep the code clean and |
| 127 | # readable so we keep the two processes separate. |
| 128 | resource_names_dict = rnc.ConvertHotlistItemNames( |
| 129 | self.cnxn, hotlist_id, issue_ids, self.services) |
| 130 | issue_names_dict = rnc.ConvertIssueNames( |
| 131 | self.cnxn, issue_ids, self.services) |
| 132 | adders_by_id = rnc.ConvertUserNames([item.adder_id for item in items]) |
| 133 | |
| 134 | # Filter out items whose issues were not found. |
| 135 | found_items = [ |
| 136 | item for item in items if resource_names_dict.get(item.issue_id) and |
| 137 | issue_names_dict.get(item.issue_id) |
| 138 | ] |
| 139 | if len(items) != len(found_items): |
| 140 | found_ids = [item.issue_id for item in found_items] |
| 141 | missing_ids = [iid for iid in issue_ids if iid not in found_ids] |
| 142 | logging.info('HotlistItem issues %r not found' % missing_ids) |
| 143 | |
| 144 | # Generate user friendly ranks (0, 1, 2, 3,...) that are exposed to API |
| 145 | # clients, instead of using padded ranks (1, 11, 21, 31,...). |
| 146 | sorted_ranks = sorted(item.rank for item in found_items) |
| 147 | friendly_ranks_dict = { |
| 148 | rank: friendly_rank for friendly_rank, rank in enumerate(sorted_ranks) |
| 149 | } |
| 150 | |
| 151 | api_items = [] |
| 152 | for item in found_items: |
| 153 | api_item = feature_objects_pb2.HotlistItem( |
| 154 | name=resource_names_dict.get(item.issue_id), |
| 155 | issue=issue_names_dict.get(item.issue_id), |
| 156 | rank=friendly_ranks_dict[item.rank], |
| 157 | adder=adders_by_id.get(item.adder_id), |
| 158 | note=item.note) |
| 159 | if item.date_added: |
| 160 | api_item.create_time.FromSeconds(item.date_added) |
| 161 | api_items.append(api_item) |
| 162 | |
| 163 | return api_items |
| 164 | |
| 165 | # Issues |
| 166 | |
| 167 | def _ConvertComponentValues(self, issue): |
| 168 | # proto.tracker_pb2.Issue -> |
| 169 | # Sequence[api_proto.issue_objects_pb2.Issue.ComponentValue] |
| 170 | """Convert the status string on issue into a ComponentValue.""" |
| 171 | component_values = [] |
| 172 | component_ids = itertools.chain( |
| 173 | issue.component_ids, issue.derived_component_ids) |
| 174 | ids_to_names = rnc.ConvertComponentDefNames( |
| 175 | self.cnxn, component_ids, issue.project_id, self.services) |
| 176 | |
| 177 | for component_id in issue.component_ids: |
| 178 | if component_id in ids_to_names: |
| 179 | component_values.append( |
| 180 | issue_objects_pb2.Issue.ComponentValue( |
| 181 | component=ids_to_names[component_id], |
| 182 | derivation=issue_objects_pb2.Derivation.Value( |
| 183 | 'EXPLICIT'))) |
| 184 | for derived_component_id in issue.derived_component_ids: |
| 185 | if derived_component_id in ids_to_names: |
| 186 | component_values.append( |
| 187 | issue_objects_pb2.Issue.ComponentValue( |
| 188 | component=ids_to_names[derived_component_id], |
| 189 | derivation=issue_objects_pb2.Derivation.Value('RULE'))) |
| 190 | |
| 191 | return component_values |
| 192 | |
| 193 | def _ConvertStatusValue(self, issue): |
| 194 | # proto.tracker_pb2.Issue -> api_proto.issue_objects_pb2.Issue.StatusValue |
| 195 | """Convert the status string on issue into a StatusValue.""" |
| 196 | derivation = issue_objects_pb2.Derivation.Value( |
| 197 | 'DERIVATION_UNSPECIFIED') |
| 198 | if issue.status: |
| 199 | derivation = issue_objects_pb2.Derivation.Value('EXPLICIT') |
| 200 | else: |
| 201 | derivation = issue_objects_pb2.Derivation.Value('RULE') |
| 202 | return issue_objects_pb2.Issue.StatusValue( |
| 203 | status=issue.status or issue.derived_status, derivation=derivation) |
| 204 | |
| 205 | def _ConvertAmendments(self, amendments, user_display_names): |
| 206 | # type: (Sequence[proto.tracker_pb2.Amendment], Mapping[int, str]) -> |
| 207 | # Sequence[api_proto.issue_objects_pb2.Comment.Amendment] |
| 208 | """Convert protorpc Amendments to protoc Amendments. |
| 209 | |
| 210 | Args: |
| 211 | amendments: the amendments to convert |
| 212 | user_display_names: map from user_id to display name for all users |
| 213 | involved in the amendments. |
| 214 | |
| 215 | Returns: |
| 216 | The converted amendments. |
| 217 | """ |
| 218 | results = [] |
| 219 | for amendment in amendments: |
| 220 | field_name = tbo.GetAmendmentFieldName(amendment) |
| 221 | new_value = tbo.AmendmentString_New(amendment, user_display_names) |
| 222 | results.append( |
| 223 | issue_objects_pb2.Comment.Amendment( |
| 224 | field_name=field_name, |
| 225 | new_or_delta_value=new_value, |
| 226 | old_value=amendment.oldvalue)) |
| 227 | return results |
| 228 | |
| 229 | def _ConvertAttachments(self, attachments, project_name): |
| 230 | # type: (Sequence[proto.tracker_pb2.Attachment], str) -> |
| 231 | # Sequence[api_proto.issue_objects_pb2.Comment.Attachment] |
| 232 | """Convert protorpc Attachments to protoc Attachments.""" |
| 233 | results = [] |
| 234 | for attach in attachments: |
| 235 | if attach.deleted: |
| 236 | state = issue_objects_pb2.IssueContentState.Value('DELETED') |
| 237 | size, thumbnail_uri, view_uri, download_uri = None, None, None, None |
| 238 | else: |
| 239 | state = issue_objects_pb2.IssueContentState.Value('ACTIVE') |
| 240 | size = attach.filesize |
| 241 | download_uri = attachment_helpers.GetDownloadURL(attach.attachment_id) |
| 242 | view_uri = attachment_helpers.GetViewURL( |
| 243 | attach, download_uri, project_name) |
| 244 | thumbnail_uri = attachment_helpers.GetThumbnailURL(attach, download_uri) |
| 245 | results.append( |
| 246 | issue_objects_pb2.Comment.Attachment( |
| 247 | filename=attach.filename, |
| 248 | state=state, |
| 249 | size=size, |
| 250 | media_type=attach.mimetype, |
| 251 | thumbnail_uri=thumbnail_uri, |
| 252 | view_uri=view_uri, |
| 253 | download_uri=download_uri)) |
| 254 | return results |
| 255 | |
| 256 | def ConvertComments(self, issue_id, comments): |
| 257 | # type: (int, Sequence[proto.tracker_pb2.IssueComment]) |
| 258 | # -> Sequence[api_proto.issue_objects_pb2.Comment] |
| 259 | """Convert protorpc IssueComments from issue into protoc Comments.""" |
| 260 | issue = self.services.issue.GetIssue(self.cnxn, issue_id) |
| 261 | users_by_id = self.services.user.GetUsersByIDs( |
| 262 | self.cnxn, tbo.UsersInvolvedInCommentList(comments)) |
| 263 | (user_display_names, |
| 264 | _user_display_emails) = framework_bizobj.CreateUserDisplayNamesAndEmails( |
| 265 | self.cnxn, self.services, self.user_auth, users_by_id.values()) |
| 266 | comment_names_dict = rnc.CreateCommentNames( |
| 267 | issue.local_id, issue.project_name, |
| 268 | [comment.sequence for comment in comments]) |
| 269 | approval_ids = [ |
| 270 | comment.approval_id |
| 271 | for comment in comments |
| 272 | if comment.approval_id is not None # In case of a 0 approval_id. |
| 273 | ] |
| 274 | approval_ids_to_names = rnc.ConvertApprovalDefNames( |
| 275 | self.cnxn, approval_ids, issue.project_id, self.services) |
| 276 | |
| 277 | converted_comments = [] |
| 278 | for comment in comments: |
| 279 | if comment.is_spam: |
| 280 | state = issue_objects_pb2.IssueContentState.Value('SPAM') |
| 281 | elif comment.deleted_by: |
| 282 | state = issue_objects_pb2.IssueContentState.Value('DELETED') |
| 283 | else: |
| 284 | state = issue_objects_pb2.IssueContentState.Value('ACTIVE') |
| 285 | comment_type = issue_objects_pb2.Comment.Type.Value('COMMENT') |
| 286 | if comment.is_description: |
| 287 | comment_type = issue_objects_pb2.Comment.Type.Value('DESCRIPTION') |
| 288 | converted_attachments = self._ConvertAttachments( |
| 289 | comment.attachments, issue.project_name) |
| 290 | converted_amendments = self._ConvertAmendments( |
| 291 | comment.amendments, user_display_names) |
| 292 | converted_comment = issue_objects_pb2.Comment( |
| 293 | name=comment_names_dict[comment.sequence], |
| 294 | state=state, |
| 295 | type=comment_type, |
| 296 | create_time=timestamp_pb2.Timestamp(seconds=comment.timestamp), |
| 297 | attachments=converted_attachments, |
| 298 | amendments=converted_amendments) |
| 299 | if comment.content: |
| 300 | converted_comment.content = comment.content |
| 301 | if comment.user_id: |
| 302 | converted_comment.commenter = rnc.ConvertUserName(comment.user_id) |
| 303 | if comment.inbound_message: |
| 304 | converted_comment.inbound_message = comment.inbound_message |
| 305 | if comment.approval_id and comment.approval_id in approval_ids_to_names: |
| 306 | converted_comment.approval = approval_ids_to_names[comment.approval_id] |
| 307 | converted_comments.append(converted_comment) |
| 308 | return converted_comments |
| 309 | |
| 310 | def ConvertIssue(self, issue): |
| 311 | # type: (proto.tracker_pb2.Issue) -> api_proto.issue_objects_pb2.Issue |
| 312 | """Convert a protorpc Issue into a protoc Issue.""" |
| 313 | issues = self.ConvertIssues([issue]) |
| 314 | if len(issues) < 1: |
| 315 | raise exceptions.NoSuchIssueException() |
| 316 | if len(issues) > 1: |
| 317 | logging.warning('More than one converted issue returned: %s', issues) |
| 318 | return issues[0] |
| 319 | |
| 320 | def ConvertIssues(self, issues): |
| 321 | # type: (Sequence[proto.tracker_pb2.Issue]) -> |
| 322 | # Sequence[api_proto.issue_objects_pb2.Issue] |
| 323 | """Convert protorpc Issues into protoc Issues.""" |
| 324 | issue_ids = [issue.issue_id for issue in issues] |
| 325 | issue_names_dict = rnc.ConvertIssueNames( |
| 326 | self.cnxn, issue_ids, self.services) |
| 327 | found_issues = [ |
| 328 | issue for issue in issues if issue.issue_id in issue_names_dict |
| 329 | ] |
| 330 | converted_issues = [] |
| 331 | for issue in found_issues: |
| 332 | status = self._ConvertStatusValue(issue) |
| 333 | content_state = issue_objects_pb2.IssueContentState.Value( |
| 334 | 'STATE_UNSPECIFIED') |
| 335 | if issue.is_spam: |
| 336 | content_state = issue_objects_pb2.IssueContentState.Value('SPAM') |
| 337 | elif issue.deleted: |
| 338 | content_state = issue_objects_pb2.IssueContentState.Value('DELETED') |
| 339 | else: |
| 340 | content_state = issue_objects_pb2.IssueContentState.Value('ACTIVE') |
| 341 | |
| 342 | owner = None |
| 343 | # Explicit values override values derived from rules. |
| 344 | if issue.owner_id: |
| 345 | owner = issue_objects_pb2.Issue.UserValue( |
| 346 | derivation=issue_objects_pb2.Derivation.Value('EXPLICIT'), |
| 347 | user=rnc.ConvertUserName(issue.owner_id)) |
| 348 | elif issue.derived_owner_id: |
| 349 | owner = issue_objects_pb2.Issue.UserValue( |
| 350 | derivation=issue_objects_pb2.Derivation.Value('RULE'), |
| 351 | user=rnc.ConvertUserName(issue.derived_owner_id)) |
| 352 | |
| 353 | cc_users = [] |
| 354 | for cc_user_id in issue.cc_ids: |
| 355 | cc_users.append( |
| 356 | issue_objects_pb2.Issue.UserValue( |
| 357 | derivation=issue_objects_pb2.Derivation.Value('EXPLICIT'), |
| 358 | user=rnc.ConvertUserName(cc_user_id))) |
| 359 | for derived_cc_user_id in issue.derived_cc_ids: |
| 360 | cc_users.append( |
| 361 | issue_objects_pb2.Issue.UserValue( |
| 362 | derivation=issue_objects_pb2.Derivation.Value('RULE'), |
| 363 | user=rnc.ConvertUserName(derived_cc_user_id))) |
| 364 | |
| 365 | labels = self.ConvertLabels( |
| 366 | issue.labels, issue.derived_labels, issue.project_id) |
| 367 | components = self._ConvertComponentValues(issue) |
| 368 | non_approval_fvs = self._GetNonApprovalFieldValues( |
| 369 | issue.field_values, issue.project_id) |
| 370 | field_values = self.ConvertFieldValues( |
| 371 | non_approval_fvs, issue.project_id, issue.phases) |
| 372 | field_values.extend( |
| 373 | self.ConvertEnumFieldValues( |
| 374 | issue.labels, issue.derived_labels, issue.project_id)) |
| 375 | related_issue_ids = ( |
| 376 | [issue.merged_into] + issue.blocked_on_iids + issue.blocking_iids) |
| 377 | issue_names_by_ids = rnc.ConvertIssueNames( |
| 378 | self.cnxn, related_issue_ids, self.services) |
| 379 | merged_into_issue_ref = None |
| 380 | if issue.merged_into and issue.merged_into in issue_names_by_ids: |
| 381 | merged_into_issue_ref = issue_objects_pb2.IssueRef( |
| 382 | issue=issue_names_by_ids[issue.merged_into]) |
| 383 | if issue.merged_into_external: |
| 384 | merged_into_issue_ref = issue_objects_pb2.IssueRef( |
| 385 | ext_identifier=issue.merged_into_external) |
| 386 | |
| 387 | blocked_on_issue_refs = [ |
| 388 | issue_objects_pb2.IssueRef(issue=issue_names_by_ids[iid]) |
| 389 | for iid in issue.blocked_on_iids |
| 390 | if iid in issue_names_by_ids |
| 391 | ] |
| 392 | blocked_on_issue_refs.extend( |
| 393 | issue_objects_pb2.IssueRef( |
| 394 | ext_identifier=blocked_on.ext_issue_identifier) |
| 395 | for blocked_on in issue.dangling_blocked_on_refs) |
| 396 | |
| 397 | blocking_issue_refs = [ |
| 398 | issue_objects_pb2.IssueRef(issue=issue_names_by_ids[iid]) |
| 399 | for iid in issue.blocking_iids |
| 400 | if iid in issue_names_by_ids |
| 401 | ] |
| 402 | blocking_issue_refs.extend( |
| 403 | issue_objects_pb2.IssueRef( |
| 404 | ext_identifier=blocking.ext_issue_identifier) |
| 405 | for blocking in issue.dangling_blocking_refs) |
| 406 | # All other timestamps were set when the issue was created. |
| 407 | close_time = None |
| 408 | if issue.closed_timestamp: |
| 409 | close_time = timestamp_pb2.Timestamp(seconds=issue.closed_timestamp) |
| 410 | |
| 411 | phases = self._ComputePhases(issue.phases) |
| 412 | |
| 413 | result = issue_objects_pb2.Issue( |
| 414 | name=issue_names_dict[issue.issue_id], |
| 415 | summary=issue.summary, |
| 416 | state=content_state, |
| 417 | status=status, |
| 418 | reporter=rnc.ConvertUserName(issue.reporter_id), |
| 419 | owner=owner, |
| 420 | cc_users=cc_users, |
| 421 | labels=labels, |
| 422 | components=components, |
| 423 | field_values=field_values, |
| 424 | merged_into_issue_ref=merged_into_issue_ref, |
| 425 | blocked_on_issue_refs=blocked_on_issue_refs, |
| 426 | blocking_issue_refs=blocking_issue_refs, |
| 427 | create_time=timestamp_pb2.Timestamp(seconds=issue.opened_timestamp), |
| 428 | close_time=close_time, |
| 429 | modify_time=timestamp_pb2.Timestamp(seconds=issue.modified_timestamp), |
| 430 | component_modify_time=timestamp_pb2.Timestamp( |
| 431 | seconds=issue.component_modified_timestamp), |
| 432 | status_modify_time=timestamp_pb2.Timestamp( |
| 433 | seconds=issue.status_modified_timestamp), |
| 434 | owner_modify_time=timestamp_pb2.Timestamp( |
| 435 | seconds=issue.owner_modified_timestamp), |
| 436 | star_count=issue.star_count, |
| 437 | phases=phases) |
| 438 | # TODO(crbug.com/monorail/5857): Set attachment_count unconditionally |
| 439 | # after the underlying source of negative attachment counts has been |
| 440 | # resolved and database has been repaired. |
| 441 | if issue.attachment_count >= 0: |
| 442 | result.attachment_count = issue.attachment_count |
| 443 | converted_issues.append(result) |
| 444 | return converted_issues |
| 445 | |
| 446 | def IngestAttachmentUploads(self, attachment_uploads): |
| 447 | # type: (Sequence[api_proto.issues_pb2.AttachmentUpload] -> |
| 448 | # Sequence[framework_helpers.AttachmentUpload]) |
| 449 | """Ingests protoc AttachmentUploads into framework_helpers.AttachUploads.""" |
| 450 | ingested_uploads = [] |
| 451 | with exceptions.ErrorAggregator(exceptions.InputException) as err_agg: |
| 452 | for up in attachment_uploads: |
| 453 | if not up.filename or not up.content: |
| 454 | err_agg.AddErrorMessage( |
| 455 | 'Uploaded atachment missing filename or content') |
| 456 | mimetype = filecontent.GuessContentTypeFromFilename(up.filename) |
| 457 | ingested_uploads.append( |
| 458 | framework_helpers.AttachmentUpload( |
| 459 | up.filename, up.content, mimetype)) |
| 460 | |
| 461 | return ingested_uploads |
| 462 | |
| 463 | def IngestIssueDeltas(self, issue_deltas): |
| 464 | # type: (Sequence[api_proto.issues_pb2.IssueDelta]) -> |
| 465 | # Sequence[Tuple[int, proto.tracker_pb2.IssueDelta]] |
| 466 | """Ingests protoc IssueDeltas, into protorpc IssueDeltas. |
| 467 | |
| 468 | Args: |
| 469 | issue_deltas: the protoc IssueDeltas to ingest. |
| 470 | |
| 471 | Returns: |
| 472 | A list of (issue_id, tracker_pb2.IssueDelta) tuples that contain |
| 473 | values found in issue_deltas, ignoring all OUTPUT_ONLY and masked |
| 474 | fields. |
| 475 | |
| 476 | Raises: |
| 477 | InputException: if any fields in the approval_deltas were invalid. |
| 478 | NoSuchProjectException: if any parent projects are not found. |
| 479 | NoSuchIssueException: if any issues are not found. |
| 480 | NoSuchComponentException: if any components are not found. |
| 481 | """ |
| 482 | issue_names = [delta.issue.name for delta in issue_deltas] |
| 483 | issue_ids = rnc.IngestIssueNames(self.cnxn, issue_names, self.services) |
| 484 | issues_dict, misses = self.services.issue.GetIssuesDict( |
| 485 | self.cnxn, issue_ids) |
| 486 | if misses: |
| 487 | logging.info( |
| 488 | 'Issues not found for supposedly valid issue_ids: %r' % misses) |
| 489 | raise ValueError('Could not fetch some issues.') |
| 490 | configs_by_pid = self.services.config.GetProjectConfigs( |
| 491 | self.cnxn, {issue.project_id for issue in issues_dict.values()}) |
| 492 | |
| 493 | with exceptions.ErrorAggregator(exceptions.InputException) as err_agg: |
| 494 | for api_delta in issue_deltas: |
| 495 | if not api_delta.HasField('update_mask'): |
| 496 | err_agg.AddErrorMessage( |
| 497 | '`update_mask` must be set for {} delta.', api_delta.issue.name) |
| 498 | elif not api_delta.update_mask.IsValidForDescriptor( |
| 499 | issue_objects_pb2.Issue.DESCRIPTOR): |
| 500 | err_agg.AddErrorMessage( |
| 501 | 'Invalid `update_mask` for {} delta.', api_delta.issue.name) |
| 502 | |
| 503 | ingested = [] |
| 504 | for iid, api_delta in zip(issue_ids, issue_deltas): |
| 505 | delta = tracker_pb2.IssueDelta() |
| 506 | |
| 507 | # Check non-repeated fields before MergeMessage because in an object |
| 508 | # where fields are not set and with a FieldMask applied, there is no |
| 509 | # way to tell if empty fields were explicitly listed or not listed |
| 510 | # in the FieldMask. |
| 511 | paths_set = set(api_delta.update_mask.paths) |
| 512 | if (not paths_set.isdisjoint({'status', 'status.status'}) and |
| 513 | api_delta.issue.status.status): |
| 514 | delta.status = api_delta.issue.status.status |
| 515 | elif 'status.status' in paths_set and not api_delta.issue.status.status: |
| 516 | delta.status = '' |
| 517 | |
| 518 | if (not paths_set.isdisjoint({'owner', 'owner.user'}) and |
| 519 | api_delta.issue.owner.user): |
| 520 | delta.owner_id = rnc.IngestUserName( |
| 521 | self.cnxn, api_delta.issue.owner.user, self.services) |
| 522 | elif 'owner.user' in paths_set and not api_delta.issue.owner.user: |
| 523 | delta.owner_id = framework_constants.NO_USER_SPECIFIED |
| 524 | |
| 525 | if 'summary' in paths_set: |
| 526 | if api_delta.issue.summary: |
| 527 | delta.summary = api_delta.issue.summary |
| 528 | else: |
| 529 | delta.summary = '' |
| 530 | |
| 531 | merge_ref = api_delta.issue.merged_into_issue_ref |
| 532 | if 'merged_into_issue_ref' in paths_set: |
| 533 | if (api_delta.issue.merged_into_issue_ref.issue or |
| 534 | api_delta.issue.merged_into_issue_ref.ext_identifier): |
| 535 | ingested_ref = self._IngestIssueRef(merge_ref) |
| 536 | if isinstance(ingested_ref, tracker_pb2.DanglingIssueRef): |
| 537 | delta.merged_into_external = ingested_ref.ext_issue_identifier |
| 538 | else: |
| 539 | delta.merged_into = ingested_ref |
| 540 | elif 'merged_into_issue_ref.issue' in paths_set: |
| 541 | if api_delta.issue.merged_into_issue_ref.issue: |
| 542 | delta.merged_into = self._IngestIssueRef(merge_ref) |
| 543 | else: |
| 544 | delta.merged_into = 0 |
| 545 | elif 'merged_into_issue_ref.ext_identifier' in paths_set: |
| 546 | if api_delta.issue.merged_into_issue_ref.ext_identifier: |
| 547 | ingested_ref = self._IngestIssueRef(merge_ref) |
| 548 | delta.merged_into_external = ingested_ref.ext_issue_identifier |
| 549 | else: |
| 550 | delta.merged_into_external = '' |
| 551 | |
| 552 | filtered_api_issue = issue_objects_pb2.Issue() |
| 553 | api_delta.update_mask.MergeMessage( |
| 554 | api_delta.issue, |
| 555 | filtered_api_issue, |
| 556 | replace_message_field=True, |
| 557 | replace_repeated_field=True) |
| 558 | |
| 559 | cc_names = [name for name in api_delta.ccs_remove] + [ |
| 560 | user_value.user for user_value in filtered_api_issue.cc_users |
| 561 | ] |
| 562 | cc_ids = rnc.IngestUserNames(self.cnxn, cc_names, self.services) |
| 563 | delta.cc_ids_remove = cc_ids[:len(api_delta.ccs_remove)] |
| 564 | delta.cc_ids_add = cc_ids[len(api_delta.ccs_remove):] |
| 565 | |
| 566 | comp_names = [component for component in api_delta.components_remove] + [ |
| 567 | c_value.component for c_value in filtered_api_issue.components |
| 568 | ] |
| 569 | project_comp_ids = rnc.IngestComponentDefNames( |
| 570 | self.cnxn, comp_names, self.services) |
| 571 | comp_ids = [comp_id for (_pid, comp_id) in project_comp_ids] |
| 572 | delta.comp_ids_remove = comp_ids[:len(api_delta.components_remove)] |
| 573 | delta.comp_ids_add = comp_ids[len(api_delta.components_remove):] |
| 574 | |
| 575 | # Added to delta below, after ShiftEnumFieldsIntoLabels. |
| 576 | labels_add = [value.label for value in filtered_api_issue.labels] |
| 577 | labels_remove = [label for label in api_delta.labels_remove] |
| 578 | |
| 579 | config = configs_by_pid[issues_dict[iid].project_id] |
| 580 | fvs_add, add_enums = self._IngestFieldValues( |
| 581 | filtered_api_issue.field_values, config) |
| 582 | fvs_remove, remove_enums = self._IngestFieldValues( |
| 583 | api_delta.field_vals_remove, config) |
| 584 | field_helpers.ShiftEnumFieldsIntoLabels( |
| 585 | labels_add, labels_remove, add_enums, remove_enums, config) |
| 586 | delta.field_vals_add = fvs_add |
| 587 | delta.field_vals_remove = fvs_remove |
| 588 | delta.labels_add = labels_add |
| 589 | delta.labels_remove = labels_remove |
| 590 | assert len(add_enums) == 0 # ShiftEnumFieldsIntoLabels clears all enums. |
| 591 | assert len(remove_enums) == 0 |
| 592 | |
| 593 | blocked_on_iids_rm, blocked_on_dangling_rm = self._IngestIssueRefs( |
| 594 | api_delta.blocked_on_issues_remove) |
| 595 | delta.blocked_on_remove = blocked_on_iids_rm |
| 596 | delta.ext_blocked_on_remove = [ |
| 597 | ref.ext_issue_identifier for ref in blocked_on_dangling_rm |
| 598 | ] |
| 599 | |
| 600 | blocked_on_iids_add, blocked_on_dangling_add = self._IngestIssueRefs( |
| 601 | filtered_api_issue.blocked_on_issue_refs) |
| 602 | delta.blocked_on_add = blocked_on_iids_add |
| 603 | delta.ext_blocked_on_add = [ |
| 604 | ref.ext_issue_identifier for ref in blocked_on_dangling_add |
| 605 | ] |
| 606 | |
| 607 | blocking_iids_rm, blocking_dangling_rm = self._IngestIssueRefs( |
| 608 | api_delta.blocking_issues_remove) |
| 609 | delta.blocking_remove = blocking_iids_rm |
| 610 | delta.ext_blocking_remove = [ |
| 611 | ref.ext_issue_identifier for ref in blocking_dangling_rm |
| 612 | ] |
| 613 | |
| 614 | blocking_iids_add, blocking_dangling_add = self._IngestIssueRefs( |
| 615 | filtered_api_issue.blocking_issue_refs) |
| 616 | delta.blocking_add = blocking_iids_add |
| 617 | delta.ext_blocking_add = [ |
| 618 | ref.ext_issue_identifier for ref in blocking_dangling_add |
| 619 | ] |
| 620 | |
| 621 | ingested.append((iid, delta)) |
| 622 | |
| 623 | return ingested |
| 624 | |
| 625 | def IngestApprovalDeltas(self, approval_deltas, setter_id): |
| 626 | # type: (Sequence[api_proto.issues_pb2.ApprovalDelta], int) -> |
| 627 | # Sequence[Tuple[int, int, proto.tracker_pb2.ApprovalDelta]] |
| 628 | """Ingests protoc ApprovalDeltas into protorpc ApprovalDeltas. |
| 629 | |
| 630 | Args: |
| 631 | approval_deltas: the protoc ApprovalDeltas to ingest. |
| 632 | setter_id: The ID for the user setting the deltas. |
| 633 | |
| 634 | Returns: |
| 635 | Sequence of (issue_id, approval_id, ApprovalDelta) tuples in the order |
| 636 | provided. The ApprovalDeltas ignore all OUTPUT_ONLY and masked fields. |
| 637 | The tuples are "delta_specifications;" they identify one requested change. |
| 638 | |
| 639 | Raises: |
| 640 | InputException: if any fields in the approval_delta protos were invalid. |
| 641 | NoSuchProjectException: if the parent project of any ApprovalValue isn't |
| 642 | found. |
| 643 | NoSuchIssueException: if the issue of any ApprovalValue isn't found. |
| 644 | NoSuchUserException: if any user value was provided with an invalid email. |
| 645 | Note that users specified by ID are not checked for existence. |
| 646 | """ |
| 647 | delta_specifications = [] |
| 648 | set_on = int(time.time()) # Use the same timestamp for all deltas. |
| 649 | for approval_delta in approval_deltas: |
| 650 | approval_name = approval_delta.approval_value.name |
| 651 | # TODO(crbug/monorail/8173): Aggregate errors. |
| 652 | project_id, issue_id, approval_id = rnc.IngestApprovalValueName( |
| 653 | self.cnxn, approval_name, self.services) |
| 654 | |
| 655 | if not approval_delta.HasField('update_mask'): |
| 656 | raise exceptions.InputException( |
| 657 | '`update_mask` must be set for %s delta.' % approval_name) |
| 658 | elif not approval_delta.update_mask.IsValidForDescriptor( |
| 659 | issue_objects_pb2.ApprovalValue.DESCRIPTOR): |
| 660 | raise exceptions.InputException( |
| 661 | 'Invalid `update_mask` for %s delta.' % approval_name) |
| 662 | filtered_value = issue_objects_pb2.ApprovalValue() |
| 663 | approval_delta.update_mask.MergeMessage( |
| 664 | approval_delta.approval_value, |
| 665 | filtered_value, |
| 666 | replace_message_field=True, |
| 667 | replace_repeated_field=True) |
| 668 | status = _APPROVAL_STATUS_INGEST[filtered_value.status] |
| 669 | # Approvers |
| 670 | # No autocreate. |
| 671 | # A user may try to remove all existing approvers [a, b] and add another |
| 672 | # approver [c]. If they mis-type `c` and we auto-create `c` instead of |
| 673 | # raising error, this would cause the ApprovalValue to be editable by no |
| 674 | # one but site admins. |
| 675 | approver_ids_add = rnc.IngestUserNames( |
| 676 | self.cnxn, filtered_value.approvers, self.services, autocreate=False) |
| 677 | approver_ids_remove = rnc.IngestUserNames( |
| 678 | self.cnxn, |
| 679 | approval_delta.approvers_remove, |
| 680 | self.services, |
| 681 | autocreate=False) |
| 682 | |
| 683 | # Field Values. |
| 684 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 685 | approval_fds_by_id = { |
| 686 | fd.field_id: fd |
| 687 | for fd in config.field_defs |
| 688 | if fd.field_type is tracker_pb2.FieldTypes.APPROVAL_TYPE |
| 689 | } |
| 690 | if approval_id not in approval_fds_by_id: |
| 691 | raise exceptions.InputException( |
| 692 | 'Approval not found in project for %s' % approval_name) |
| 693 | |
| 694 | sub_fvs_add, add_enums = self._IngestFieldValues( |
| 695 | filtered_value.field_values, config, approval_id_filter=approval_id) |
| 696 | sub_fvs_remove, remove_enums = self._IngestFieldValues( |
| 697 | approval_delta.field_vals_remove, |
| 698 | config, |
| 699 | approval_id_filter=approval_id) |
| 700 | labels_add = [] |
| 701 | labels_remove = [] |
| 702 | field_helpers.ShiftEnumFieldsIntoLabels( |
| 703 | labels_add, labels_remove, add_enums, remove_enums, config) |
| 704 | assert len(add_enums) == 0 # ShiftEnumFieldsIntoLabels clears all enums. |
| 705 | assert len(remove_enums) == 0 |
| 706 | delta = tbo.MakeApprovalDelta( |
| 707 | status, |
| 708 | setter_id, |
| 709 | approver_ids_add, |
| 710 | approver_ids_remove, |
| 711 | sub_fvs_add, |
| 712 | sub_fvs_remove, [], |
| 713 | labels_add, |
| 714 | labels_remove, |
| 715 | set_on=set_on) |
| 716 | delta_specifications.append((issue_id, approval_id, delta)) |
| 717 | return delta_specifications |
| 718 | |
| 719 | def IngestIssue(self, issue, project_id): |
| 720 | # type: (api_proto.issue_objects_pb2.Issue, int) -> proto.tracker_pb2.Issue |
| 721 | """Ingest a protoc Issue into a protorpc Issue. |
| 722 | |
| 723 | Args: |
| 724 | issue: the protoc issue to ingest. |
| 725 | project_id: The project into which we're ingesting `issue`. |
| 726 | |
| 727 | Returns: |
| 728 | protorpc version of issue, ignoring all OUTPUT_ONLY fields. |
| 729 | |
| 730 | Raises: |
| 731 | InputException: if any fields in the 'issue' proto were invalid. |
| 732 | NoSuchProjectException: if 'project_id' is not found. |
| 733 | """ |
| 734 | # Get config first. We can't ingest the issue if the project isn't found. |
| 735 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 736 | ingestedDict = { |
| 737 | 'project_id': project_id, |
| 738 | 'summary': issue.summary |
| 739 | } |
| 740 | with exceptions.ErrorAggregator(exceptions.InputException) as err_agg: |
| 741 | self._ExtractOwner(issue, ingestedDict, err_agg) |
| 742 | |
| 743 | # Extract ccs. |
| 744 | try: |
| 745 | ingestedDict['cc_ids'] = rnc.IngestUserNames( |
| 746 | self.cnxn, [cc.user for cc in issue.cc_users], self.services, |
| 747 | autocreate=True) |
| 748 | except exceptions.InputException as e: |
| 749 | err_agg.AddErrorMessage('Error ingesting cc_users: {}', e) |
| 750 | |
| 751 | # Extract status. |
| 752 | if issue.HasField('status') and issue.status.status: |
| 753 | ingestedDict['status'] = issue.status.status |
| 754 | else: |
| 755 | err_agg.AddErrorMessage('Status is required when creating an issue') |
| 756 | |
| 757 | # Extract components. |
| 758 | try: |
| 759 | project_comp_ids = rnc.IngestComponentDefNames( |
| 760 | self.cnxn, [cv.component for cv in issue.components], self.services) |
| 761 | ingestedDict['component_ids'] = [ |
| 762 | comp_id for (_pid, comp_id) in project_comp_ids] |
| 763 | except (exceptions.InputException, exceptions.NoSuchProjectException, |
| 764 | exceptions.NoSuchComponentException) as e: |
| 765 | err_agg.AddErrorMessage('Error ingesting components: {}', e) |
| 766 | |
| 767 | # Extract labels and field values. |
| 768 | ingestedDict['labels'] = [lv.label for lv in issue.labels] |
| 769 | try: |
| 770 | ingestedDict['field_values'], enums = self._IngestFieldValues( |
| 771 | issue.field_values, config) |
| 772 | field_helpers.ShiftEnumFieldsIntoLabels( |
| 773 | ingestedDict['labels'], [], enums, [], config) |
| 774 | assert len( |
| 775 | enums) == 0 # ShiftEnumFieldsIntoLabels must clear all enums. |
| 776 | except exceptions.InputException as e: |
| 777 | err_agg.AddErrorMessage(e.message) |
| 778 | |
| 779 | # Ingest merged, blocking/blocked_on. |
| 780 | self._ExtractIssueRefs(issue, ingestedDict, err_agg) |
| 781 | return tracker_pb2.Issue(**ingestedDict) |
| 782 | |
| 783 | def _IngestFieldValues(self, field_values, config, approval_id_filter=None): |
| 784 | # type: (Sequence[api_proto.issue_objects.FieldValue], |
| 785 | # proto.tracker_pb2.ProjectIssueConfig, Optional[int]) -> |
| 786 | # Tuple[Sequence[proto.tracker_pb2.FieldValue], |
| 787 | # Mapping[int, Sequence[str]]] |
| 788 | """Returns protorpc FieldValues for the given protoc FieldValues. |
| 789 | |
| 790 | Raises exceptions if any field could not be parsed for any reasons such as |
| 791 | unsupported field type, non-existent field, field from different |
| 792 | projects, or fields with mismatched parent approvals. |
| 793 | |
| 794 | Args: |
| 795 | field_values: protoc FieldValues to ingest. |
| 796 | config: ProjectIssueConfig for the FieldValues we're ingesting. |
| 797 | approval_id_filter: an approval_id, including any FieldValues that does |
| 798 | not have this approval as a parent will trigger InputException. |
| 799 | |
| 800 | Returns: |
| 801 | A pair 1) Ingested FieldValues. 2) A mapping of field ids to values |
| 802 | for ENUM_TYPE fields in 'field_values.' |
| 803 | |
| 804 | Raises: |
| 805 | InputException: if any fields_values could not be parsed for any reasons |
| 806 | such as unsupported field type, non-existent field, or field from |
| 807 | different projects. |
| 808 | """ |
| 809 | fds_by_id = {fd.field_id: fd for fd in config.field_defs} |
| 810 | enums = {} |
| 811 | ingestedFieldValues = [] |
| 812 | with exceptions.ErrorAggregator(exceptions.InputException) as err_agg: |
| 813 | for fv in field_values: |
| 814 | try: |
| 815 | project_id, fd_id = rnc.IngestFieldDefName( |
| 816 | self.cnxn, fv.field, self.services) |
| 817 | fd = fds_by_id[fd_id] |
| 818 | # Raise if field does not belong to approval_id_filter (if provided). |
| 819 | if (approval_id_filter is not None and |
| 820 | fd.approval_id != approval_id_filter): |
| 821 | approval_name = rnc.ConvertApprovalDefNames( |
| 822 | self.cnxn, [approval_id_filter], project_id, |
| 823 | self.services)[approval_id_filter] |
| 824 | err_agg.AddErrorMessage( |
| 825 | 'Field {} does not belong to approval {}', fv.field, |
| 826 | approval_name) |
| 827 | continue |
| 828 | if fd.field_type == tracker_pb2.FieldTypes.ENUM_TYPE: |
| 829 | enums.setdefault(fd_id, []).append(fv.value) |
| 830 | else: |
| 831 | ingestedFieldValues.append(self._IngestFieldValue(fv, fd)) |
| 832 | except (exceptions.InputException, exceptions.NoSuchProjectException, |
| 833 | exceptions.NoSuchFieldDefException, ValueError) as e: |
| 834 | err_agg.AddErrorMessage( |
| 835 | 'Could not ingest value ({}) for FieldDef ({}): {}', fv.value, |
| 836 | fv.field, e) |
| 837 | except exceptions.NoSuchUserException as e: |
| 838 | err_agg.AddErrorMessage( |
| 839 | 'User ({}) not found when ingesting user field: {}', fv.value, |
| 840 | fv.field) |
| 841 | except KeyError as e: |
| 842 | err_agg.AddErrorMessage('Field {} is not in this project', fv.field) |
| 843 | return ingestedFieldValues, enums |
| 844 | |
| 845 | def _IngestFieldValue(self, field_value, field_def): |
| 846 | # type: (api_proto.issue_objects.FieldValue, proto.tracker_pb2.FieldDef) -> |
| 847 | # proto.tracker_pb2.FieldValue |
| 848 | """Ingest a protoc FieldValue into a protorpc FieldValue. |
| 849 | |
| 850 | Args: |
| 851 | field_value: protoc FieldValue to ingest. |
| 852 | field_def: protorpc FieldDef associated with 'field_value'. |
| 853 | BOOL_TYPE and APPROVAL_TYPE are ignored. |
| 854 | Enum values are not allowed. They must be ingested as labels. |
| 855 | |
| 856 | Returns: |
| 857 | Ingested protorpc FieldValue. |
| 858 | |
| 859 | Raises: |
| 860 | InputException if 'field_def' is USER_TYPE and 'field_value' does not |
| 861 | have a valid formatted resource name. |
| 862 | NoSuchUserException if specified user in field does not exist. |
| 863 | ValueError if 'field_value' could not be parsed for 'field_def'. |
| 864 | """ |
| 865 | assert field_def.field_type != tracker_pb2.FieldTypes.ENUM_TYPE |
| 866 | if field_def.field_type == tracker_pb2.FieldTypes.USER_TYPE: |
| 867 | return self._ParseOneUserFieldValue(field_value.value, field_def.field_id) |
| 868 | fv = field_helpers.ParseOneFieldValue( |
| 869 | self.cnxn, self.services.user, field_def, field_value.value) |
| 870 | # ParseOneFieldValue currently ignores parsing errors, although it has TODOs |
| 871 | # to raise them. |
| 872 | if not fv: |
| 873 | raise ValueError('Could not parse %s' % field_value.value) |
| 874 | return fv |
| 875 | |
| 876 | def _ParseOneUserFieldValue(self, value, field_id): |
| 877 | # type: (str, int) -> proto.tracker_pb2.FieldValue |
| 878 | """Replacement for the obsolete user parsing in ParseOneFieldValue.""" |
| 879 | user_id = rnc.IngestUserName(self.cnxn, value, self.services) |
| 880 | return tbo.MakeFieldValue(field_id, None, None, user_id, None, None, False) |
| 881 | |
| 882 | def _ExtractOwner(self, issue, ingestedDict, err_agg): |
| 883 | # type: (api_proto.issue_objects_pb2.Issue, Dict[str, Any], ErrorAggregator) |
| 884 | # -> None |
| 885 | """Fills 'owner' into `ingestedDict`, if it can be extracted.""" |
| 886 | if issue.HasField('owner'): |
| 887 | try: |
| 888 | # Unlike for cc's, we require owner be an existing user, thus call we |
| 889 | # do not autocreate. |
| 890 | ingestedDict['owner_id'] = rnc.IngestUserName( |
| 891 | self.cnxn, issue.owner.user, self.services, autocreate=False) |
| 892 | except exceptions.InputException as e: |
| 893 | err_agg.AddErrorMessage( |
| 894 | 'Error ingesting owner ({}): {}', issue.owner.user, e) |
| 895 | except exceptions.NoSuchUserException as e: |
| 896 | err_agg.AddErrorMessage( |
| 897 | 'User ({}) not found when ingesting owner', e) |
| 898 | else: |
| 899 | ingestedDict['owner_id'] = framework_constants.NO_USER_SPECIFIED |
| 900 | |
| 901 | def _ExtractIssueRefs(self, issue, ingestedDict, err_agg): |
| 902 | # type: (api_proto.issue_objects_pb2.Issue, Dict[str, Any], ErrorAggregator) |
| 903 | # -> None |
| 904 | """Fills issue relationships into `ingestedDict` from `issue`.""" |
| 905 | if issue.HasField('merged_into_issue_ref'): |
| 906 | try: |
| 907 | merged_into_ref = self._IngestIssueRef(issue.merged_into_issue_ref) |
| 908 | if isinstance(merged_into_ref, tracker_pb2.DanglingIssueRef): |
| 909 | ingestedDict['merged_into_external'] = ( |
| 910 | merged_into_ref.ext_issue_identifier) |
| 911 | else: |
| 912 | ingestedDict['merged_into'] = merged_into_ref |
| 913 | except exceptions.InputException as e: |
| 914 | err_agg.AddErrorMessage( |
| 915 | 'Error ingesting ref {}: {}', issue.merged_into_issue_ref, e) |
| 916 | try: |
| 917 | iids, dangling_refs = self._IngestIssueRefs(issue.blocked_on_issue_refs) |
| 918 | ingestedDict['blocked_on_iids'] = iids |
| 919 | ingestedDict['dangling_blocked_on_refs'] = dangling_refs |
| 920 | except exceptions.InputException as e: |
| 921 | err_agg.AddErrorMessage(e.message) |
| 922 | try: |
| 923 | iids, dangling_refs = self._IngestIssueRefs(issue.blocking_issue_refs) |
| 924 | ingestedDict['blocking_iids'] = iids |
| 925 | ingestedDict['dangling_blocking_refs'] = dangling_refs |
| 926 | except exceptions.InputException as e: |
| 927 | err_agg.AddErrorMessage(e.message) |
| 928 | |
| 929 | def _IngestIssueRefs(self, issue_refs): |
| 930 | # type: (api_proto.issue_objects.IssueRf) -> |
| 931 | # Tuple[Sequence[int], Sequence[tracker_pb2.DanglingIssueRef]] |
| 932 | """Given protoc IssueRefs, returns issue_ids and DanglingIssueRefs.""" |
| 933 | issue_ids = [] |
| 934 | external_refs = [] |
| 935 | with exceptions.ErrorAggregator(exceptions.InputException) as err_agg: |
| 936 | for ref in issue_refs: |
| 937 | try: |
| 938 | ingested_ref = self._IngestIssueRef(ref) |
| 939 | if isinstance(ingested_ref, tracker_pb2.DanglingIssueRef): |
| 940 | external_refs.append(ingested_ref) |
| 941 | else: |
| 942 | issue_ids.append(ingested_ref) |
| 943 | except (exceptions.InputException, exceptions.NoSuchIssueException, |
| 944 | exceptions.NoSuchProjectException) as e: |
| 945 | err_agg.AddErrorMessage('Error ingesting ref {}: {}', ref, e) |
| 946 | |
| 947 | return issue_ids, external_refs |
| 948 | |
| 949 | def _IngestIssueRef(self, issue_ref): |
| 950 | # type: (api_proto.issue_objects.IssueRef) -> |
| 951 | # Union[int, tracker_pb2.DanglingIssueRef] |
| 952 | """Given a protoc IssueRef, returns an issue id or DanglingIssueRef.""" |
| 953 | if issue_ref.issue and issue_ref.ext_identifier: |
| 954 | raise exceptions.InputException( |
| 955 | 'IssueRefs MUST NOT have both `issue` and `ext_identifier`') |
| 956 | if issue_ref.issue: |
| 957 | return rnc.IngestIssueName(self.cnxn, issue_ref.issue, self.services) |
| 958 | if issue_ref.ext_identifier: |
| 959 | # TODO(crbug.com/monorail/7208): Handle ingestion/conversion of CodeSite |
| 960 | # refs. We may be able to avoid ever needing to ingest them. |
| 961 | return tracker_pb2.DanglingIssueRef( |
| 962 | ext_issue_identifier=issue_ref.ext_identifier |
| 963 | ) |
| 964 | raise exceptions.InputException( |
| 965 | 'IssueRefs MUST have one of `issue` and `ext_identifier`') |
| 966 | |
| 967 | def IngestIssuesListColumns(self, issues_list_columns): |
| 968 | # type: (Sequence[proto.issue_objects_pb2.IssuesListColumn] -> str |
| 969 | """Ingest a list of protoc IssueListColumns and returns a string.""" |
| 970 | return ' '.join([col.column for col in issues_list_columns]) |
| 971 | |
| 972 | def _ComputeIssuesListColumns(self, columns): |
| 973 | # type: (string) -> Sequence[api_proto.issue_objects_pb2.IssuesListColumn] |
| 974 | """Convert string representation of columns to protoc IssuesListColumns""" |
| 975 | return [ |
| 976 | issue_objects_pb2.IssuesListColumn(column=col) |
| 977 | for col in columns.split() |
| 978 | ] |
| 979 | |
| 980 | def IngestNotifyType(self, notify): |
| 981 | # type: (issue_pb.NotifyType) -> bool |
| 982 | """Ingest a NotifyType to boolean.""" |
| 983 | if (notify == issues_pb2.NotifyType.Value('NOTIFY_TYPE_UNSPECIFIED') or |
| 984 | notify == issues_pb2.NotifyType.Value('EMAIL')): |
| 985 | return True |
| 986 | elif notify == issues_pb2.NotifyType.Value('NO_NOTIFICATION'): |
| 987 | return False |
| 988 | |
| 989 | # Users |
| 990 | |
| 991 | def ConvertUser(self, user): |
| 992 | # type: (protorpc.User) -> api_proto.user_objects_pb2.User |
| 993 | """Convert a protorpc User into a protoc User. |
| 994 | |
| 995 | Args: |
| 996 | user: protorpc User object. |
| 997 | |
| 998 | Returns: |
| 999 | The protoc User object. |
| 1000 | """ |
| 1001 | return self.ConvertUsers([user.user_id])[user.user_id] |
| 1002 | |
| 1003 | |
| 1004 | # TODO(crbug/monorail/7238): Make this take in a full User object and |
| 1005 | # return a Sequence, rather than a map, after hotlist users are converted. |
| 1006 | def ConvertUsers(self, user_ids): |
| 1007 | # type: (Sequence[int]) -> Map(int, api_proto.user_objects_pb2.User) |
| 1008 | """Convert list of protorpc Users into list of protoc Users. |
| 1009 | |
| 1010 | Args: |
| 1011 | user_ids: List of User IDs. |
| 1012 | |
| 1013 | Returns: |
| 1014 | Dict of User IDs to User protos for given user_ids that could be found. |
| 1015 | """ |
| 1016 | user_ids_to_names = {} |
| 1017 | |
| 1018 | # Get display names |
| 1019 | users_by_id = self.services.user.GetUsersByIDs(self.cnxn, user_ids) |
| 1020 | (display_names_by_id, |
| 1021 | display_emails_by_id) = framework_bizobj.CreateUserDisplayNamesAndEmails( |
| 1022 | self.cnxn, self.services, self.user_auth, users_by_id.values()) |
| 1023 | |
| 1024 | for user_id, user in users_by_id.items(): |
| 1025 | name = rnc.ConvertUserNames([user_id]).get(user_id) |
| 1026 | |
| 1027 | display_name = display_names_by_id.get(user_id) |
| 1028 | display_email = display_emails_by_id.get(user_id) |
| 1029 | availability = framework_helpers.GetUserAvailability(user) |
| 1030 | availability_message, _availability_status = availability |
Adrià Vilanova MartÃnez | ac4a644 | 2022-05-15 19:05:13 +0200 | [diff] [blame^] | 1031 | last_visit_timestamp = user.last_visit_timestamp |
Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 1032 | |
| 1033 | user_ids_to_names[user_id] = user_objects_pb2.User( |
| 1034 | name=name, |
| 1035 | display_name=display_name, |
| 1036 | email=display_email, |
Adrià Vilanova MartÃnez | ac4a644 | 2022-05-15 19:05:13 +0200 | [diff] [blame^] | 1037 | availability_message=availability_message, |
| 1038 | last_visit_timestamp=last_visit_timestamp) |
Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 1039 | |
| 1040 | return user_ids_to_names |
| 1041 | |
| 1042 | def ConvertProjectStars(self, user_id, projects): |
| 1043 | # type: (int, Collection[protorpc.Project]) -> |
| 1044 | # Collection[api_proto.user_objects_pb2.ProjectStar] |
| 1045 | """Convert list of protorpc Projects into protoc ProjectStars. |
| 1046 | |
| 1047 | Args: |
| 1048 | user_id: The user the ProjectStar is associated with. |
| 1049 | projects: All starred projects. |
| 1050 | |
| 1051 | Returns: |
| 1052 | List of ProjectStar messages. |
| 1053 | """ |
| 1054 | api_project_stars = [] |
| 1055 | for proj in projects: |
| 1056 | name = rnc.ConvertProjectStarName( |
| 1057 | self.cnxn, user_id, proj.project_id, self.services) |
| 1058 | star = user_objects_pb2.ProjectStar(name=name) |
| 1059 | api_project_stars.append(star) |
| 1060 | return api_project_stars |
| 1061 | |
| 1062 | # Field Defs |
| 1063 | |
| 1064 | def ConvertFieldDefs(self, field_defs, project_id): |
| 1065 | # type: (Sequence[proto.tracker_pb2.FieldDef], int) -> |
| 1066 | # Sequence[api_proto.project_objects_pb2.FieldDef] |
| 1067 | """Convert sequence of protorpc FieldDefs to protoc FieldDefs. |
| 1068 | |
| 1069 | Args: |
| 1070 | field_defs: List of protorpc FieldDefs |
| 1071 | project_id: ID of the Project that is ancestor to all given |
| 1072 | `field_defs`. |
| 1073 | |
| 1074 | Returns: |
| 1075 | Sequence of protoc FieldDef in the same order they are given in |
| 1076 | `field_defs`. In the event any field_def or the referenced approval_id |
| 1077 | in `field_defs` is not found, they will be omitted from the result. |
| 1078 | """ |
| 1079 | field_ids = [fd.field_id for fd in field_defs] |
| 1080 | resource_names_dict = rnc.ConvertFieldDefNames( |
| 1081 | self.cnxn, field_ids, project_id, self.services) |
| 1082 | parent_approval_ids = [ |
| 1083 | fd.approval_id for fd in field_defs if fd.approval_id is not None |
| 1084 | ] |
| 1085 | approval_names_dict = rnc.ConvertApprovalDefNames( |
| 1086 | self.cnxn, parent_approval_ids, project_id, self.services) |
| 1087 | |
| 1088 | api_fds = [] |
| 1089 | for fd in field_defs: |
| 1090 | # Skip over approval fields, they have their separate ApprovalDef |
| 1091 | if fd.field_type == tracker_pb2.FieldTypes.APPROVAL_TYPE: |
| 1092 | continue |
| 1093 | if fd.field_id not in resource_names_dict: |
| 1094 | continue |
| 1095 | |
| 1096 | name = resource_names_dict.get(fd.field_id) |
| 1097 | display_name = fd.field_name |
| 1098 | docstring = fd.docstring |
| 1099 | field_type = self._ConvertFieldDefType(fd.field_type) |
| 1100 | applicable_issue_type = fd.applicable_type |
| 1101 | admins = rnc.ConvertUserNames(fd.admin_ids).values() |
| 1102 | editors = rnc.ConvertUserNames(fd.editor_ids).values() |
| 1103 | traits = self._ComputeFieldDefTraits(fd) |
| 1104 | approval_parent = approval_names_dict.get(fd.approval_id) |
| 1105 | |
| 1106 | enum_settings = None |
| 1107 | if field_type == project_objects_pb2.FieldDef.Type.Value('ENUM'): |
| 1108 | enum_settings = project_objects_pb2.FieldDef.EnumTypeSettings( |
| 1109 | choices=self._GetEnumFieldChoices(fd)) |
| 1110 | |
| 1111 | int_settings = None |
| 1112 | if field_type == project_objects_pb2.FieldDef.Type.Value('INT'): |
| 1113 | int_settings = project_objects_pb2.FieldDef.IntTypeSettings( |
| 1114 | min_value=fd.min_value, max_value=fd.max_value) |
| 1115 | |
| 1116 | str_settings = None |
| 1117 | if field_type == project_objects_pb2.FieldDef.Type.Value('STR'): |
| 1118 | str_settings = project_objects_pb2.FieldDef.StrTypeSettings( |
| 1119 | regex=fd.regex) |
| 1120 | |
| 1121 | user_settings = None |
| 1122 | if field_type == project_objects_pb2.FieldDef.Type.Value('USER'): |
| 1123 | user_settings = project_objects_pb2.FieldDef.UserTypeSettings( |
| 1124 | role_requirements=self._ConvertRoleRequirements(fd.needs_member), |
| 1125 | notify_triggers=self._ConvertNotifyTriggers(fd.notify_on), |
| 1126 | grants_perm=fd.grants_perm, |
| 1127 | needs_perm=fd.needs_perm) |
| 1128 | |
| 1129 | date_settings = None |
| 1130 | if field_type == project_objects_pb2.FieldDef.Type.Value('DATE'): |
| 1131 | date_settings = project_objects_pb2.FieldDef.DateTypeSettings( |
| 1132 | date_action=self._ConvertDateAction(fd.date_action)) |
| 1133 | |
| 1134 | api_fd = project_objects_pb2.FieldDef( |
| 1135 | name=name, |
| 1136 | display_name=display_name, |
| 1137 | docstring=docstring, |
| 1138 | type=field_type, |
| 1139 | applicable_issue_type=applicable_issue_type, |
| 1140 | admins=admins, |
| 1141 | traits=traits, |
| 1142 | approval_parent=approval_parent, |
| 1143 | enum_settings=enum_settings, |
| 1144 | int_settings=int_settings, |
| 1145 | str_settings=str_settings, |
| 1146 | user_settings=user_settings, |
| 1147 | date_settings=date_settings, |
| 1148 | editors=editors) |
| 1149 | api_fds.append(api_fd) |
| 1150 | return api_fds |
| 1151 | |
| 1152 | def _ConvertDateAction(self, date_action): |
| 1153 | # type: (proto.tracker_pb2.DateAction) -> |
| 1154 | # api_proto.project_objects_pb2.FieldDef.DateTypeSettings.DateAction |
| 1155 | """Convert protorpc DateAction to protoc |
| 1156 | FieldDef.DateTypeSettings.DateAction""" |
| 1157 | if date_action == tracker_pb2.DateAction.NO_ACTION: |
| 1158 | return project_objects_pb2.FieldDef.DateTypeSettings.DateAction.Value( |
| 1159 | 'NO_ACTION') |
| 1160 | elif date_action == tracker_pb2.DateAction.PING_OWNER_ONLY: |
| 1161 | return project_objects_pb2.FieldDef.DateTypeSettings.DateAction.Value( |
| 1162 | 'NOTIFY_OWNER') |
| 1163 | elif date_action == tracker_pb2.DateAction.PING_PARTICIPANTS: |
| 1164 | return project_objects_pb2.FieldDef.DateTypeSettings.DateAction.Value( |
| 1165 | 'NOTIFY_PARTICIPANTS') |
| 1166 | else: |
| 1167 | raise ValueError('Unsupported DateAction Value') |
| 1168 | |
| 1169 | def _ConvertRoleRequirements(self, needs_member): |
| 1170 | # type: (bool) -> |
| 1171 | # api_proto.project_objects_pb2.FieldDef. |
| 1172 | # UserTypeSettings.RoleRequirements |
| 1173 | """Convert protorpc RoleRequirements to protoc |
| 1174 | FieldDef.UserTypeSettings.RoleRequirements""" |
| 1175 | |
| 1176 | proto_user_settings = project_objects_pb2.FieldDef.UserTypeSettings |
| 1177 | if needs_member: |
| 1178 | return proto_user_settings.RoleRequirements.Value('PROJECT_MEMBER') |
| 1179 | else: |
| 1180 | return proto_user_settings.RoleRequirements.Value('NO_ROLE_REQUIREMENT') |
| 1181 | |
| 1182 | def _ConvertNotifyTriggers(self, notify_trigger): |
| 1183 | # type: (proto.tracker_pb2.NotifyTriggers) -> |
| 1184 | # api_proto.project_objects_pb2.FieldDef.UserTypeSettings.NotifyTriggers |
| 1185 | """Convert protorpc NotifyTriggers to protoc |
| 1186 | FieldDef.UserTypeSettings.NotifyTriggers""" |
| 1187 | if notify_trigger == tracker_pb2.NotifyTriggers.NEVER: |
| 1188 | return project_objects_pb2.FieldDef.UserTypeSettings.NotifyTriggers.Value( |
| 1189 | 'NEVER') |
| 1190 | elif notify_trigger == tracker_pb2.NotifyTriggers.ANY_COMMENT: |
| 1191 | return project_objects_pb2.FieldDef.UserTypeSettings.NotifyTriggers.Value( |
| 1192 | 'ANY_COMMENT') |
| 1193 | else: |
| 1194 | raise ValueError('Unsupported NotifyTriggers Value') |
| 1195 | |
| 1196 | def _ConvertFieldDefType(self, field_type): |
| 1197 | # type: (proto.tracker_pb2.FieldTypes) -> |
| 1198 | # api_proto.project_objects_pb2.FieldDef.Type |
| 1199 | """Convert protorpc FieldType to protoc FieldDef.Type |
| 1200 | |
| 1201 | Args: |
| 1202 | field_type: protorpc FieldType |
| 1203 | |
| 1204 | Returns: |
| 1205 | Corresponding protoc FieldDef.Type |
| 1206 | |
| 1207 | Raises: |
| 1208 | ValueError if input `field_type` has no suitable supported FieldDef.Type, |
| 1209 | or input `field_type` is not a recognized enum option. |
| 1210 | """ |
| 1211 | if field_type == tracker_pb2.FieldTypes.ENUM_TYPE: |
| 1212 | return project_objects_pb2.FieldDef.Type.Value('ENUM') |
| 1213 | elif field_type == tracker_pb2.FieldTypes.INT_TYPE: |
| 1214 | return project_objects_pb2.FieldDef.Type.Value('INT') |
| 1215 | elif field_type == tracker_pb2.FieldTypes.STR_TYPE: |
| 1216 | return project_objects_pb2.FieldDef.Type.Value('STR') |
| 1217 | elif field_type == tracker_pb2.FieldTypes.USER_TYPE: |
| 1218 | return project_objects_pb2.FieldDef.Type.Value('USER') |
| 1219 | elif field_type == tracker_pb2.FieldTypes.DATE_TYPE: |
| 1220 | return project_objects_pb2.FieldDef.Type.Value('DATE') |
| 1221 | elif field_type == tracker_pb2.FieldTypes.URL_TYPE: |
| 1222 | return project_objects_pb2.FieldDef.Type.Value('URL') |
| 1223 | else: |
| 1224 | raise ValueError( |
| 1225 | 'Unsupported tracker_pb2.FieldType enum. Boolean types ' |
| 1226 | 'are unsupported and approval types are found in ApprovalDefs') |
| 1227 | |
| 1228 | def _ComputeFieldDefTraits(self, field_def): |
| 1229 | # type: (proto.tracker_pb2.FieldDef) -> |
| 1230 | # Sequence[api_proto.project_objects_pb2.FieldDef.Traits] |
| 1231 | """Compute sequence of FieldDef.Traits for a given protorpc FieldDef.""" |
| 1232 | trait_protos = [] |
| 1233 | if field_def.is_required: |
| 1234 | trait_protos.append(project_objects_pb2.FieldDef.Traits.Value('REQUIRED')) |
| 1235 | if field_def.is_niche: |
| 1236 | trait_protos.append( |
| 1237 | project_objects_pb2.FieldDef.Traits.Value('DEFAULT_HIDDEN')) |
| 1238 | if field_def.is_multivalued: |
| 1239 | trait_protos.append( |
| 1240 | project_objects_pb2.FieldDef.Traits.Value('MULTIVALUED')) |
| 1241 | if field_def.is_phase_field: |
| 1242 | trait_protos.append(project_objects_pb2.FieldDef.Traits.Value('PHASE')) |
| 1243 | if field_def.is_restricted_field: |
| 1244 | trait_protos.append( |
| 1245 | project_objects_pb2.FieldDef.Traits.Value('RESTRICTED')) |
| 1246 | return trait_protos |
| 1247 | |
| 1248 | def _GetEnumFieldChoices(self, field_def): |
| 1249 | # type: (proto.tracker_pb2.FieldDef) -> |
| 1250 | # Sequence[Choice] |
| 1251 | """Get sequence of choices for an enum field |
| 1252 | |
| 1253 | Args: |
| 1254 | field_def: protorpc FieldDef |
| 1255 | |
| 1256 | Returns: |
| 1257 | Sequence of valid Choices for enum field `field_def`. |
| 1258 | |
| 1259 | Raises: |
| 1260 | ValueError if input `field_def` is not an enum type field. |
| 1261 | """ |
| 1262 | if field_def.field_type != tracker_pb2.FieldTypes.ENUM_TYPE: |
| 1263 | raise ValueError('Cannot get value from label for non-enum-type field') |
| 1264 | |
| 1265 | config = self.services.config.GetProjectConfig( |
| 1266 | self.cnxn, field_def.project_id) |
| 1267 | value_docstr_tuples = tracker_helpers._GetEnumFieldValuesAndDocstrings( |
| 1268 | field_def, config) |
| 1269 | |
| 1270 | return [ |
| 1271 | Choice(value=value, docstring=docstring) |
| 1272 | for value, docstring in value_docstr_tuples |
| 1273 | ] |
| 1274 | |
| 1275 | # Field Values |
| 1276 | |
| 1277 | def _GetNonApprovalFieldValues(self, field_values, project_id): |
| 1278 | # type: (Sequence[proto.tracker_pb2.FieldValue], int) -> |
| 1279 | # Sequence[proto.tracker_pb2.FieldValue] |
| 1280 | """Filter out field values that belong to an approval field.""" |
| 1281 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 1282 | approval_fd_ids = set( |
| 1283 | [fd.field_id for fd in config.field_defs if fd.approval_id]) |
| 1284 | |
| 1285 | return [fv for fv in field_values if fv.field_id not in approval_fd_ids] |
| 1286 | |
| 1287 | def ConvertFieldValues(self, field_values, project_id, phases): |
| 1288 | # type: (Sequence[proto.tracker_pb2.FieldValue], int, |
| 1289 | # Sequence[proto.tracker_pb2.Phase]) -> |
| 1290 | # Sequence[api_proto.issue_objects_pb2.FieldValue] |
| 1291 | """Convert sequence of field_values to protoc FieldValues. |
| 1292 | |
| 1293 | This method does not handle enum_type fields. |
| 1294 | |
| 1295 | Args: |
| 1296 | field_values: List of FieldValues |
| 1297 | project_id: ID of the Project that is ancestor to all given |
| 1298 | `field_values`. |
| 1299 | phases: List of Phases |
| 1300 | |
| 1301 | Returns: |
| 1302 | Sequence of protoc FieldValues in the same order they are given in |
| 1303 | `field_values`. In the event any field_values in `field_values` are not |
| 1304 | found, they will be omitted from the result. |
| 1305 | """ |
| 1306 | phase_names_by_id = {phase.phase_id: phase.name for phase in phases} |
| 1307 | field_ids = [fv.field_id for fv in field_values] |
| 1308 | resource_names_dict = rnc.ConvertFieldDefNames( |
| 1309 | self.cnxn, field_ids, project_id, self.services) |
| 1310 | |
| 1311 | api_fvs = [] |
| 1312 | for fv in field_values: |
| 1313 | if fv.field_id not in resource_names_dict: |
| 1314 | continue |
| 1315 | |
| 1316 | name = resource_names_dict.get(fv.field_id) |
| 1317 | value = self._ComputeFieldValueString(fv) |
| 1318 | derivation = self._ComputeFieldValueDerivation(fv) |
| 1319 | phase = phase_names_by_id.get(fv.phase_id) |
| 1320 | api_item = issue_objects_pb2.FieldValue( |
| 1321 | field=name, value=value, derivation=derivation, phase=phase) |
| 1322 | api_fvs.append(api_item) |
| 1323 | |
| 1324 | return api_fvs |
| 1325 | |
| 1326 | def _ComputeFieldValueString(self, field_value): |
| 1327 | # type: (proto.tracker_pb2.FieldValue) -> str |
| 1328 | """Convert a FieldValue's value to a string.""" |
| 1329 | if field_value is None: |
| 1330 | raise exceptions.InputException('No FieldValue specified') |
| 1331 | elif field_value.int_value is not None: |
| 1332 | return str(field_value.int_value) |
| 1333 | elif field_value.str_value is not None: |
| 1334 | return field_value.str_value |
| 1335 | elif field_value.user_id is not None: |
| 1336 | return rnc.ConvertUserNames([field_value.user_id |
| 1337 | ]).get(field_value.user_id) |
| 1338 | elif field_value.date_value is not None: |
| 1339 | return str(field_value.date_value) |
| 1340 | elif field_value.url_value is not None: |
| 1341 | return field_value.url_value |
| 1342 | else: |
| 1343 | raise exceptions.InputException('FieldValue must have at least one value') |
| 1344 | |
| 1345 | def _ComputeFieldValueDerivation(self, field_value): |
| 1346 | # type: (proto.tracker_pb2.FieldValue) -> |
| 1347 | # api_proto.issue_objects_pb2.Issue.Derivation |
| 1348 | """Convert a FieldValue's 'derived' to a protoc Issue.Derivation. |
| 1349 | |
| 1350 | Args: |
| 1351 | field_value: protorpc FieldValue |
| 1352 | |
| 1353 | Returns: |
| 1354 | Issue.Derivation of given `field_value` |
| 1355 | """ |
| 1356 | if field_value.derived: |
| 1357 | return issue_objects_pb2.Derivation.Value('RULE') |
| 1358 | else: |
| 1359 | return issue_objects_pb2.Derivation.Value('EXPLICIT') |
| 1360 | |
| 1361 | # Approval Def |
| 1362 | |
| 1363 | def ConvertApprovalDefs(self, approval_defs, project_id): |
| 1364 | # type: (Sequence[proto.tracker_pb2.ApprovalDef], int) -> |
| 1365 | # Sequence[api_proto.project_objects_pb2.ApprovalDef] |
| 1366 | """Convert sequence of protorpc ApprovalDefs to protoc ApprovalDefs. |
| 1367 | |
| 1368 | Args: |
| 1369 | approval_defs: List of protorpc ApprovalDefs |
| 1370 | project_id: ID of the Project the approval_defs belong to. |
| 1371 | |
| 1372 | Returns: |
| 1373 | Sequence of protoc ApprovalDefs in the same order they are given in |
| 1374 | in `approval_defs`. In the event any approval_def in `approval_defs` |
| 1375 | are not found, they will be omitted from the result. |
| 1376 | """ |
| 1377 | approval_ids = set([ad.approval_id for ad in approval_defs]) |
| 1378 | resource_names_dict = rnc.ConvertApprovalDefNames( |
| 1379 | self.cnxn, approval_ids, project_id, self.services) |
| 1380 | |
| 1381 | # Get matching field defs, needed to fill out protoc ApprovalDefs |
| 1382 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 1383 | fd_by_id = {} |
| 1384 | for fd in config.field_defs: |
| 1385 | if (fd.field_type == tracker_pb2.FieldTypes.APPROVAL_TYPE and |
| 1386 | fd.field_id in approval_ids): |
| 1387 | fd_by_id[fd.field_id] = fd |
| 1388 | |
| 1389 | all_users = tbo.UsersInvolvedInApprovalDefs( |
| 1390 | approval_defs, fd_by_id.values()) |
| 1391 | user_resource_names_dict = rnc.ConvertUserNames(all_users) |
| 1392 | |
| 1393 | api_ads = [] |
| 1394 | for ad in approval_defs: |
| 1395 | if (ad.approval_id not in resource_names_dict or |
| 1396 | ad.approval_id not in fd_by_id): |
| 1397 | continue |
| 1398 | matching_fd = fd_by_id.get(ad.approval_id) |
| 1399 | name = resource_names_dict.get(ad.approval_id) |
| 1400 | display_name = matching_fd.field_name |
| 1401 | docstring = matching_fd.docstring |
| 1402 | survey = ad.survey |
| 1403 | approvers = [ |
| 1404 | user_resource_names_dict.get(approver_id) |
| 1405 | for approver_id in ad.approver_ids |
| 1406 | ] |
| 1407 | admins = [ |
| 1408 | user_resource_names_dict.get(admin_id) |
| 1409 | for admin_id in matching_fd.admin_ids |
| 1410 | ] |
| 1411 | |
| 1412 | api_ad = project_objects_pb2.ApprovalDef( |
| 1413 | name=name, |
| 1414 | display_name=display_name, |
| 1415 | docstring=docstring, |
| 1416 | survey=survey, |
| 1417 | approvers=approvers, |
| 1418 | admins=admins) |
| 1419 | api_ads.append(api_ad) |
| 1420 | return api_ads |
| 1421 | |
| 1422 | def ConvertApprovalValues(self, approval_values, field_values, phases, |
| 1423 | issue_id=None, project_id=None): |
| 1424 | # type: (Sequence[proto.tracker_pb2.ApprovalValue], |
| 1425 | # Sequence[proto.tracker_pb2.FieldValue], |
| 1426 | # Sequence[proto.tracker_pb2.Phase], Optional[int], Optional[int]) -> |
| 1427 | # Sequence[api_proto.issue_objects_pb2.ApprovalValue] |
| 1428 | """Convert sequence of approval_values to protoc ApprovalValues. |
| 1429 | |
| 1430 | `approval_values` may belong to a template or an issue. If they belong to a |
| 1431 | template, `project_id` should be given for the project the template is in. |
| 1432 | If these are issue `approval_values` `issue_id` should be given`. |
| 1433 | So, one of `issue_id` or `project_id` must be provided. |
| 1434 | If both are given, we ignore `project_id` and assume the `approval_values` |
| 1435 | belong to an issue. |
| 1436 | |
| 1437 | Args: |
| 1438 | approval_values: List of ApprovalValues. |
| 1439 | field_values: List of FieldValues that may belong to the approval_values. |
| 1440 | phases: List of Phases that may be associated with the approval_values. |
| 1441 | issue_id: ID of the Issue that the `approval_values` belong to. |
| 1442 | project_id: ID of the Project that the `approval_values` |
| 1443 | template belongs to. |
| 1444 | |
| 1445 | Returns: |
| 1446 | Sequence of protoc ApprovalValues in the same order they are given in |
| 1447 | in `approval_values`. In the event any approval definitions in |
| 1448 | `approval_values` are not found, they will be omitted from the result. |
| 1449 | |
| 1450 | Raises: |
| 1451 | InputException if neither `issue_id` nor `project_id` is given. |
| 1452 | """ |
| 1453 | |
| 1454 | approval_ids = [av.approval_id for av in approval_values] |
| 1455 | resource_names_dict = {} |
| 1456 | if issue_id is not None: |
| 1457 | # Only issue approval_values have resource names. |
| 1458 | resource_names_dict = rnc.ConvertApprovalValueNames( |
| 1459 | self.cnxn, issue_id, self.services) |
| 1460 | project_id = self.services.issue.GetIssue(self.cnxn, issue_id).project_id |
| 1461 | elif project_id is None: |
| 1462 | raise exceptions.InputException( |
| 1463 | 'One `issue_id` or `project_id` must be given.') |
| 1464 | |
| 1465 | phase_names_by_id = {phase.phase_id: phase.name for phase in phases} |
| 1466 | ad_names_dict = rnc.ConvertApprovalDefNames( |
| 1467 | self.cnxn, approval_ids, project_id, self.services) |
| 1468 | |
| 1469 | # Organize the field values by the approval values they are |
| 1470 | # associated with. |
| 1471 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 1472 | fds_by_id = {fd.field_id: fd for fd in config.field_defs} |
| 1473 | fvs_by_parent_approvals = collections.defaultdict(list) |
| 1474 | for fv in field_values: |
| 1475 | fd = fds_by_id.get(fv.field_id) |
| 1476 | if fd and fd.approval_id: |
| 1477 | fvs_by_parent_approvals[fd.approval_id].append(fv) |
| 1478 | |
| 1479 | api_avs = [] |
| 1480 | for av in approval_values: |
| 1481 | # We only skip missing approval names if we are converting issue approval |
| 1482 | # values. |
| 1483 | if issue_id is not None and av.approval_id not in resource_names_dict: |
| 1484 | continue |
| 1485 | |
| 1486 | name = resource_names_dict.get(av.approval_id) |
| 1487 | approval_def = ad_names_dict.get(av.approval_id) |
| 1488 | approvers = rnc.ConvertUserNames(av.approver_ids).values() |
| 1489 | status = self._ComputeApprovalValueStatus(av.status) |
| 1490 | setter = rnc.ConvertUserName(av.setter_id) |
| 1491 | phase = phase_names_by_id.get(av.phase_id) |
| 1492 | |
| 1493 | field_values = self.ConvertFieldValues( |
| 1494 | fvs_by_parent_approvals[av.approval_id], project_id, phases) |
| 1495 | |
| 1496 | api_item = issue_objects_pb2.ApprovalValue( |
| 1497 | name=name, |
| 1498 | approval_def=approval_def, |
| 1499 | approvers=approvers, |
| 1500 | status=status, |
| 1501 | setter=setter, |
| 1502 | field_values=field_values, |
| 1503 | phase=phase) |
| 1504 | if av.set_on: |
| 1505 | api_item.set_time.FromSeconds(av.set_on) |
| 1506 | api_avs.append(api_item) |
| 1507 | |
| 1508 | return api_avs |
| 1509 | |
| 1510 | def _ComputeApprovalValueStatus(self, status): |
| 1511 | # type: (proto.tracker_pb2.ApprovalStatus) -> |
| 1512 | # api_proto.issue_objects_pb2.Issue.ApprovalStatus |
| 1513 | """Convert a protorpc ApprovalStatus to a protoc Issue.ApprovalStatus.""" |
| 1514 | try: |
| 1515 | return _APPROVAL_STATUS_CONVERT[status] |
| 1516 | except KeyError: |
| 1517 | raise ValueError('Unrecognized tracker_pb2.ApprovalStatus enum') |
| 1518 | |
| 1519 | # Projects |
| 1520 | |
| 1521 | def ConvertIssueTemplates(self, project_id, templates): |
| 1522 | # type: (int, Sequence[proto.tracker_pb2.TemplateDef]) -> |
| 1523 | # Sequence[api_proto.project_objects_pb2.IssueTemplate] |
| 1524 | """Convert a Sequence of TemplateDefs to protoc IssueTemplates. |
| 1525 | |
| 1526 | Args: |
| 1527 | project_id: ID of the Project the templates belong to. |
| 1528 | templates: Sequence of TemplateDef protorpc objects. |
| 1529 | |
| 1530 | Returns: |
| 1531 | Sequence of protoc IssueTemplate in the same order they are given in |
| 1532 | `templates`. In the rare event that any templates are not found, |
| 1533 | they will be omitted from the result. |
| 1534 | """ |
| 1535 | api_templates = [] |
| 1536 | |
| 1537 | resource_names_dict = rnc.ConvertTemplateNames( |
| 1538 | self.cnxn, project_id, [template.template_id for template in templates], |
| 1539 | self.services) |
| 1540 | |
| 1541 | for template in templates: |
| 1542 | if template.template_id not in resource_names_dict: |
| 1543 | continue |
| 1544 | name = resource_names_dict.get(template.template_id) |
| 1545 | summary_must_be_edited = template.summary_must_be_edited |
| 1546 | template_privacy = self._ComputeTemplatePrivacy(template) |
| 1547 | default_owner = self._ComputeTemplateDefaultOwner(template) |
| 1548 | component_required = template.component_required |
| 1549 | admins = rnc.ConvertUserNames(template.admin_ids).values() |
| 1550 | issue = self._FillIssueFromTemplate(template, project_id) |
| 1551 | approval_values = self.ConvertApprovalValues( |
| 1552 | template.approval_values, template.field_values, template.phases, |
| 1553 | project_id=project_id) |
| 1554 | api_templates.append( |
| 1555 | project_objects_pb2.IssueTemplate( |
| 1556 | name=name, |
| 1557 | display_name=template.name, |
| 1558 | issue=issue, |
| 1559 | approval_values=approval_values, |
| 1560 | summary_must_be_edited=summary_must_be_edited, |
| 1561 | template_privacy=template_privacy, |
| 1562 | default_owner=default_owner, |
| 1563 | component_required=component_required, |
| 1564 | admins=admins)) |
| 1565 | |
| 1566 | return api_templates |
| 1567 | |
| 1568 | def _FillIssueFromTemplate(self, template, project_id): |
| 1569 | # type: (proto.tracker_pb2.TemplateDef, int) -> |
| 1570 | # api_proto.issue_objects_pb2.Issue |
| 1571 | """Convert a TemplateDef to its embedded protoc Issue. |
| 1572 | |
| 1573 | IssueTemplate does not set the following fields: |
| 1574 | name |
| 1575 | reporter |
| 1576 | cc_users |
| 1577 | blocked_on_issue_refs |
| 1578 | blocking_issue_refs |
| 1579 | create_time |
| 1580 | close_time |
| 1581 | modify_time |
| 1582 | component_modify_time |
| 1583 | status_modify_time |
| 1584 | owner_modify_time |
| 1585 | attachment_count |
| 1586 | star_count |
| 1587 | |
| 1588 | Args: |
| 1589 | template: TemplateDef protorpc objects. |
| 1590 | project_id: ID of the Project the template belongs to. |
| 1591 | |
| 1592 | Returns: |
| 1593 | protoc Issue filled with data from given `template`. |
| 1594 | """ |
| 1595 | summary = template.summary |
| 1596 | state = issue_objects_pb2.IssueContentState.Value('ACTIVE') |
| 1597 | status = issue_objects_pb2.Issue.StatusValue( |
| 1598 | status=template.status, |
| 1599 | derivation=issue_objects_pb2.Derivation.Value('EXPLICIT')) |
| 1600 | owner = None |
| 1601 | if template.owner_id is not None: |
| 1602 | owner = issue_objects_pb2.Issue.UserValue( |
| 1603 | user=rnc.ConvertUserNames([template.owner_id]).get(template.owner_id)) |
| 1604 | labels = self.ConvertLabels(template.labels, [], project_id) |
| 1605 | components_dict = rnc.ConvertComponentDefNames( |
| 1606 | self.cnxn, template.component_ids, project_id, self.services) |
| 1607 | components = [] |
| 1608 | for component_resource_name in components_dict.values(): |
| 1609 | components.append( |
| 1610 | issue_objects_pb2.Issue.ComponentValue( |
| 1611 | component=component_resource_name, |
| 1612 | derivation=issue_objects_pb2.Derivation.Value('EXPLICIT'))) |
| 1613 | non_approval_fvs = self._GetNonApprovalFieldValues( |
| 1614 | template.field_values, project_id) |
| 1615 | field_values = self.ConvertFieldValues( |
| 1616 | non_approval_fvs, project_id, template.phases) |
| 1617 | field_values.extend( |
| 1618 | self.ConvertEnumFieldValues(template.labels, [], project_id)) |
| 1619 | phases = self._ComputePhases(template.phases) |
| 1620 | |
| 1621 | filled_issue = issue_objects_pb2.Issue( |
| 1622 | summary=summary, |
| 1623 | state=state, |
| 1624 | status=status, |
| 1625 | owner=owner, |
| 1626 | labels=labels, |
| 1627 | components=components, |
| 1628 | field_values=field_values, |
| 1629 | phases=phases) |
| 1630 | return filled_issue |
| 1631 | |
| 1632 | def _ComputeTemplatePrivacy(self, template): |
| 1633 | # type: (proto.tracker_pb2.TemplateDef) -> |
| 1634 | # api_proto.project_objects_pb2.IssueTemplate.TemplatePrivacy |
| 1635 | """Convert a protorpc TemplateDef to its protoc TemplatePrivacy.""" |
| 1636 | if template.members_only: |
| 1637 | return project_objects_pb2.IssueTemplate.TemplatePrivacy.Value( |
| 1638 | 'MEMBERS_ONLY') |
| 1639 | else: |
| 1640 | return project_objects_pb2.IssueTemplate.TemplatePrivacy.Value('PUBLIC') |
| 1641 | |
| 1642 | def _ComputeTemplateDefaultOwner(self, template): |
| 1643 | # type: (proto.tracker_pb2.TemplateDef) -> |
| 1644 | # api_proto.project_objects_pb2.IssueTemplate.DefaultOwner |
| 1645 | """Convert a protorpc TemplateDef to its protoc DefaultOwner.""" |
| 1646 | if template.owner_defaults_to_member: |
| 1647 | return project_objects_pb2.IssueTemplate.DefaultOwner.Value( |
| 1648 | 'PROJECT_MEMBER_REPORTER') |
| 1649 | else: |
| 1650 | return project_objects_pb2.IssueTemplate.DefaultOwner.Value( |
| 1651 | 'DEFAULT_OWNER_UNSPECIFIED') |
| 1652 | |
| 1653 | def _ComputePhases(self, phases): |
| 1654 | # type: (proto.tracker_pb2.TemplateDef) -> Sequence[str] |
| 1655 | """Convert a protorpc TemplateDef to its sorted string phases.""" |
| 1656 | sorted_phases = sorted(phases, key=lambda phase: phase.rank) |
| 1657 | return [phase.name for phase in sorted_phases] |
| 1658 | |
| 1659 | def ConvertLabels(self, labels, derived_labels, project_id): |
| 1660 | # type: (Sequence[str], Sequence[str], int) -> |
| 1661 | # Sequence[api_proto.issue_objects_pb2.Issue.LabelValue] |
| 1662 | """Convert string labels to LabelValues for non-enum-field labels |
| 1663 | |
| 1664 | Args: |
| 1665 | labels: Sequence of string labels |
| 1666 | project_id: ID of the Project these labels belong to. |
| 1667 | |
| 1668 | Return: |
| 1669 | Sequence of protoc IssueValues for given `labels` that |
| 1670 | do not represent enum field values. |
| 1671 | """ |
| 1672 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 1673 | non_fd_labels, non_fd_der_labels = tbo.ExplicitAndDerivedNonMaskedLabels( |
| 1674 | labels, derived_labels, config) |
| 1675 | api_labels = [] |
| 1676 | for label in non_fd_labels: |
| 1677 | api_labels.append( |
| 1678 | issue_objects_pb2.Issue.LabelValue( |
| 1679 | label=label, |
| 1680 | derivation=issue_objects_pb2.Derivation.Value('EXPLICIT'))) |
| 1681 | for label in non_fd_der_labels: |
| 1682 | api_labels.append( |
| 1683 | issue_objects_pb2.Issue.LabelValue( |
| 1684 | label=label, |
| 1685 | derivation=issue_objects_pb2.Derivation.Value('RULE'))) |
| 1686 | return api_labels |
| 1687 | |
| 1688 | def ConvertEnumFieldValues(self, labels, derived_labels, project_id): |
| 1689 | # type: (Sequence[str], Sequence[str], int) -> |
| 1690 | # Sequence[api_proto.issue_objects_pb2.FieldValue] |
| 1691 | """Convert string labels to FieldValues for enum-field labels |
| 1692 | |
| 1693 | Args: |
| 1694 | labels: Sequence of string labels |
| 1695 | project_id: ID of the Project these labels belong to. |
| 1696 | |
| 1697 | Return: |
| 1698 | Sequence of protoc FieldValues only for given `labels` that |
| 1699 | represent enum field values. |
| 1700 | """ |
| 1701 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 1702 | enum_ids_by_name = { |
| 1703 | fd.field_name.lower(): fd.field_id |
| 1704 | for fd in config.field_defs |
| 1705 | if fd.field_type is tracker_pb2.FieldTypes.ENUM_TYPE |
| 1706 | and not fd.is_deleted |
| 1707 | } |
| 1708 | resource_names_dict = rnc.ConvertFieldDefNames( |
| 1709 | self.cnxn, enum_ids_by_name.values(), project_id, self.services) |
| 1710 | |
| 1711 | api_fvs = [] |
| 1712 | |
| 1713 | labels_by_prefix = tbo.LabelsByPrefix(labels, enum_ids_by_name.keys()) |
| 1714 | for lower_field_name, values in labels_by_prefix.items(): |
| 1715 | field_id = enum_ids_by_name.get(lower_field_name) |
| 1716 | resource_name = resource_names_dict.get(field_id) |
| 1717 | if not resource_name: |
| 1718 | continue |
| 1719 | api_fvs.extend( |
| 1720 | [ |
| 1721 | issue_objects_pb2.FieldValue( |
| 1722 | field=resource_name, |
| 1723 | value=value, |
| 1724 | derivation=issue_objects_pb2.Derivation.Value( |
| 1725 | 'EXPLICIT')) for value in values |
| 1726 | ]) |
| 1727 | |
| 1728 | der_labels_by_prefix = tbo.LabelsByPrefix( |
| 1729 | derived_labels, enum_ids_by_name.keys()) |
| 1730 | for lower_field_name, values in der_labels_by_prefix.items(): |
| 1731 | field_id = enum_ids_by_name.get(lower_field_name) |
| 1732 | resource_name = resource_names_dict.get(field_id) |
| 1733 | if not resource_name: |
| 1734 | continue |
| 1735 | api_fvs.extend( |
| 1736 | [ |
| 1737 | issue_objects_pb2.FieldValue( |
| 1738 | field=resource_name, |
| 1739 | value=value, |
| 1740 | derivation=issue_objects_pb2.Derivation.Value('RULE')) |
| 1741 | for value in values |
| 1742 | ]) |
| 1743 | |
| 1744 | return api_fvs |
| 1745 | |
| 1746 | def ConvertProject(self, project): |
| 1747 | # type: (proto.project_pb2.Project) -> |
| 1748 | # api_proto.project_objects_pb2.Project |
| 1749 | """Convert a protorpc Project to its protoc Project.""" |
| 1750 | |
| 1751 | return project_objects_pb2.Project( |
| 1752 | name=rnc.ConvertProjectName( |
| 1753 | self.cnxn, project.project_id, self.services), |
| 1754 | display_name=project.project_name, |
| 1755 | summary=project.summary, |
| 1756 | thumbnail_url=project_helpers.GetThumbnailUrl(project.logo_gcs_id)) |
| 1757 | |
| 1758 | def ConvertProjects(self, projects): |
| 1759 | # type: (Sequence[proto.project_pb2.Project]) -> |
| 1760 | # Sequence[api_proto.project_objects_pb2.Project] |
| 1761 | """Convert a Sequence of protorpc Projects to protoc Projects.""" |
| 1762 | return [self.ConvertProject(proj) for proj in projects] |
| 1763 | |
| 1764 | def ConvertProjectConfig(self, project_config): |
| 1765 | # type: (proto.tracker_pb2.ProjectIssueConfig) -> |
| 1766 | # api_proto.project_objects_pb2.ProjectConfig |
| 1767 | """Convert protorpc ProjectIssueConfig to protoc ProjectConfig.""" |
| 1768 | project = self.services.project.GetProject( |
| 1769 | self.cnxn, project_config.project_id) |
| 1770 | project_grid_config = project_objects_pb2.ProjectConfig.GridViewConfig( |
| 1771 | default_x_attr=project_config.default_x_attr, |
| 1772 | default_y_attr=project_config.default_y_attr) |
| 1773 | template_names = rnc.ConvertTemplateNames( |
| 1774 | self.cnxn, project_config.project_id, [ |
| 1775 | project_config.default_template_for_developers, |
| 1776 | project_config.default_template_for_users |
| 1777 | ], self.services) |
| 1778 | return project_objects_pb2.ProjectConfig( |
| 1779 | name=rnc.ConvertProjectConfigName( |
| 1780 | self.cnxn, project_config.project_id, self.services), |
| 1781 | exclusive_label_prefixes=project_config.exclusive_label_prefixes, |
| 1782 | member_default_query=project_config.member_default_query, |
| 1783 | default_sort=project_config.default_sort_spec, |
| 1784 | default_columns=self._ComputeIssuesListColumns( |
| 1785 | project_config.default_col_spec), |
| 1786 | project_grid_config=project_grid_config, |
| 1787 | member_default_template=template_names.get( |
| 1788 | project_config.default_template_for_developers), |
| 1789 | non_members_default_template=template_names.get( |
| 1790 | project_config.default_template_for_users), |
| 1791 | revision_url_format=project.revision_url_format, |
| 1792 | custom_issue_entry_url=project_config.custom_issue_entry_url) |
| 1793 | |
| 1794 | def CreateProjectMember(self, cnxn, project_id, user_id, role): |
| 1795 | # type: (MonorailContext, int, int, str) -> |
| 1796 | # api_proto.project_objects_pb2.ProjectMember |
| 1797 | """Creates a ProjectMember object from specified parameters. |
| 1798 | |
| 1799 | Args: |
| 1800 | cnxn: MonorailConnection object. |
| 1801 | project_id: ID of the Project the User is a member of. |
| 1802 | user_id: ID of the user who is a member. |
| 1803 | role: str specifying the user's role based on a ProjectRole value. |
| 1804 | |
| 1805 | Return: |
| 1806 | A protoc ProjectMember object. |
| 1807 | """ |
| 1808 | name = rnc.ConvertProjectMemberName( |
| 1809 | cnxn, project_id, user_id, self.services) |
| 1810 | return project_objects_pb2.ProjectMember( |
| 1811 | name=name, |
| 1812 | role=project_objects_pb2.ProjectMember.ProjectRole.Value(role)) |
| 1813 | |
| 1814 | def ConvertLabelDefs(self, label_defs, project_id): |
| 1815 | # type: (Sequence[proto.tracker_pb2.LabelDef], int) -> |
| 1816 | # Sequence[api_proto.project_objects_pb2.LabelDef] |
| 1817 | """Convert protorpc LabelDefs to protoc LabelDefs""" |
| 1818 | resource_names_dict = rnc.ConvertLabelDefNames( |
| 1819 | self.cnxn, [ld.label for ld in label_defs], project_id, self.services) |
| 1820 | |
| 1821 | api_lds = [] |
| 1822 | for ld in label_defs: |
| 1823 | state = project_objects_pb2.LabelDef.LabelDefState.Value('ACTIVE') |
| 1824 | if ld.deprecated: |
| 1825 | state = project_objects_pb2.LabelDef.LabelDefState.Value('DEPRECATED') |
| 1826 | api_lds.append( |
| 1827 | project_objects_pb2.LabelDef( |
| 1828 | name=resource_names_dict.get(ld.label), |
| 1829 | value=ld.label, |
| 1830 | docstring=ld.label_docstring, |
| 1831 | state=state)) |
| 1832 | return api_lds |
| 1833 | |
| 1834 | def ConvertStatusDefs(self, status_defs, project_id): |
| 1835 | # type: (Sequence[proto.tracker_pb2.StatusDef], int) -> |
| 1836 | # Sequence[api_proto.project_objects_pb2.StatusDef] |
| 1837 | """Convert protorpc StatusDefs to protoc StatusDefs |
| 1838 | |
| 1839 | Args: |
| 1840 | status_defs: Sequence of StatusDefs. |
| 1841 | project_id: ID of the Project these belong to. |
| 1842 | |
| 1843 | Returns: |
| 1844 | Sequence of protoc StatusDefs in the same order they are given in |
| 1845 | `status_defs`. |
| 1846 | """ |
| 1847 | resource_names_dict = rnc.ConvertStatusDefNames( |
| 1848 | self.cnxn, [sd.status for sd in status_defs], project_id, self.services) |
| 1849 | config = self.services.config.GetProjectConfig(self.cnxn, project_id) |
| 1850 | mergeable_statuses = set(config.statuses_offer_merge) |
| 1851 | |
| 1852 | # Rank is only surfaced as positional value in well_known_statuses |
| 1853 | rank_by_status = {} |
| 1854 | for rank, sd in enumerate(config.well_known_statuses): |
| 1855 | rank_by_status[sd.status] = rank |
| 1856 | |
| 1857 | api_sds = [] |
| 1858 | for sd in status_defs: |
| 1859 | state = project_objects_pb2.StatusDef.StatusDefState.Value('ACTIVE') |
| 1860 | if sd.deprecated: |
| 1861 | state = project_objects_pb2.StatusDef.StatusDefState.Value('DEPRECATED') |
| 1862 | |
| 1863 | if sd.means_open: |
| 1864 | status_type = project_objects_pb2.StatusDef.StatusDefType.Value('OPEN') |
| 1865 | else: |
| 1866 | if sd.status in mergeable_statuses: |
| 1867 | status_type = project_objects_pb2.StatusDef.StatusDefType.Value( |
| 1868 | 'MERGED') |
| 1869 | else: |
| 1870 | status_type = project_objects_pb2.StatusDef.StatusDefType.Value( |
| 1871 | 'CLOSED') |
| 1872 | |
| 1873 | api_sd = project_objects_pb2.StatusDef( |
| 1874 | name=resource_names_dict.get(sd.status), |
| 1875 | value=sd.status, |
| 1876 | type=status_type, |
| 1877 | rank=rank_by_status[sd.status], |
| 1878 | docstring=sd.status_docstring, |
| 1879 | state=state, |
| 1880 | ) |
| 1881 | api_sds.append(api_sd) |
| 1882 | return api_sds |
| 1883 | |
| 1884 | def ConvertComponentDef(self, component_def): |
| 1885 | # type: (proto.tracker_pb2.ComponentDef) -> |
| 1886 | # api_proto.project_objects.ComponentDef |
| 1887 | """Convert a protorpc ComponentDef to a protoc ComponentDef.""" |
| 1888 | return self.ConvertComponentDefs([component_def], |
| 1889 | component_def.project_id)[0] |
| 1890 | |
| 1891 | def ConvertComponentDefs(self, component_defs, project_id): |
| 1892 | # type: (Sequence[proto.tracker_pb2.ComponentDef], int) -> |
| 1893 | # Sequence[api_proto.project_objects.ComponentDef] |
| 1894 | """Convert sequence of protorpc ComponentDefs to protoc ComponentDefs |
| 1895 | |
| 1896 | Args: |
| 1897 | component_defs: Sequence of protoc ComponentDefs. |
| 1898 | project_id: ID of the Project these belong to. |
| 1899 | |
| 1900 | Returns: |
| 1901 | Sequence of protoc ComponentDefs in the same order they are given in |
| 1902 | `component_defs`. |
| 1903 | """ |
| 1904 | resource_names_dict = rnc.ConvertComponentDefNames( |
| 1905 | self.cnxn, [cd.component_id for cd in component_defs], project_id, |
| 1906 | self.services) |
| 1907 | involved_user_ids = tbo.UsersInvolvedInComponents(component_defs) |
| 1908 | user_resource_names_dict = rnc.ConvertUserNames(involved_user_ids) |
| 1909 | |
| 1910 | all_label_ids = set() |
| 1911 | for cd in component_defs: |
| 1912 | all_label_ids.update(cd.label_ids) |
| 1913 | |
| 1914 | # If this becomes a performance issue, we should add bulk look up. |
| 1915 | labels_by_id = { |
| 1916 | label_id: self.services.config.LookupLabel( |
| 1917 | self.cnxn, project_id, label_id) for label_id in all_label_ids |
| 1918 | } |
| 1919 | |
| 1920 | api_cds = [] |
| 1921 | for cd in component_defs: |
| 1922 | state = project_objects_pb2.ComponentDef.ComponentDefState.Value('ACTIVE') |
| 1923 | if cd.deprecated: |
| 1924 | state = project_objects_pb2.ComponentDef.ComponentDefState.Value( |
| 1925 | 'DEPRECATED') |
| 1926 | |
| 1927 | api_cd = project_objects_pb2.ComponentDef( |
| 1928 | name=resource_names_dict.get(cd.component_id), |
| 1929 | value=cd.path, |
| 1930 | docstring=cd.docstring, |
| 1931 | state=state, |
| 1932 | admins=[ |
| 1933 | user_resource_names_dict.get(admin_id) |
| 1934 | for admin_id in cd.admin_ids |
| 1935 | ], |
| 1936 | ccs=[user_resource_names_dict.get(cc_id) for cc_id in cd.cc_ids], |
| 1937 | creator=user_resource_names_dict.get(cd.creator_id), |
| 1938 | modifier=user_resource_names_dict.get(cd.modifier_id), |
| 1939 | create_time=timestamp_pb2.Timestamp(seconds=cd.created), |
| 1940 | modify_time=timestamp_pb2.Timestamp(seconds=cd.modified), |
| 1941 | labels=[labels_by_id[label_id] for label_id in cd.label_ids], |
| 1942 | ) |
| 1943 | api_cds.append(api_cd) |
| 1944 | return api_cds |
| 1945 | |
| 1946 | def ConvertProjectSavedQueries(self, saved_queries, project_id): |
| 1947 | # type: (Sequence[proto.tracker_pb2.SavedQuery], int) -> |
| 1948 | # Sequence(api_proto.project_objects.ProjectSavedQuery) |
| 1949 | """Convert sequence of protorpc SavedQueries to protoc ProjectSavedQueries |
| 1950 | |
| 1951 | Args: |
| 1952 | saved_queries: Sequence of SavedQueries. |
| 1953 | project_id: ID of the Project these belong to. |
| 1954 | |
| 1955 | Returns: |
| 1956 | Sequence of protoc ProjectSavedQueries in the same order they are given in |
| 1957 | `saved_queries`. In the event any items in `saved_queries` are not found |
| 1958 | or don't belong to the project, they will be omitted from the result. |
| 1959 | """ |
| 1960 | resource_names_dict = rnc.ConvertProjectSavedQueryNames( |
| 1961 | self.cnxn, [sq.query_id for sq in saved_queries], project_id, |
| 1962 | self.services) |
| 1963 | api_psqs = [] |
| 1964 | for sq in saved_queries: |
| 1965 | if sq.query_id not in resource_names_dict: |
| 1966 | continue |
| 1967 | |
| 1968 | # TODO(crbug/monorail/7756): Remove base_query_id, avoid confusions. |
| 1969 | # Until then we have to expand the query by including base_query_id. |
| 1970 | # base_query_id can only be in the set of DEFAULT_CANNED_QUERIES. |
| 1971 | if sq.base_query_id: |
| 1972 | query = '{} {}'.format(tbo.GetBuiltInQuery(sq.base_query_id), sq.query) |
| 1973 | else: |
| 1974 | query = sq.query |
| 1975 | |
| 1976 | api_psqs.append( |
| 1977 | project_objects_pb2.ProjectSavedQuery( |
| 1978 | name=resource_names_dict.get(sq.query_id), |
| 1979 | display_name=sq.name, |
| 1980 | query=query)) |
| 1981 | return api_psqs |