atlassian-python-api 5.0.1__py3-none-any.whl → 5.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. atlassian/VERSION +1 -1
  2. atlassian/__init__.py +18 -3
  3. atlassian/assets/__init__.py +6 -0
  4. atlassian/{assets.py → assets/assets_cloud.py} +274 -9
  5. atlassian/assets/assets_server.py +24 -0
  6. atlassian/bamboo.py +178 -2
  7. atlassian/bitbucket/__init__.py +176 -1
  8. atlassian/bitbucket/base.py +9 -2
  9. atlassian/bitbucket/cloud/repositories/commits.py +13 -3
  10. atlassian/bitbucket/cloud/repositories/repositoryVariables.py +23 -0
  11. atlassian/bitbucket/cloud/workspaces/__init__.py +6 -1
  12. atlassian/bitbucket/server/__init__.py +11 -0
  13. atlassian/cloud_admin.py +418 -0
  14. atlassian/compass/__init__.py +109 -0
  15. atlassian/confluence/__init__.py +9 -0
  16. atlassian/confluence/base.py +44 -11
  17. atlassian/confluence/cloud/__init__.py +36 -0
  18. atlassian/confluence/cloud/admin_management.py +125 -0
  19. atlassian/confluence/cloud/classification_levels.py +77 -0
  20. atlassian/confluence/cloud/cloud.py +50 -26
  21. atlassian/confluence/cloud/content_properties.py +71 -0
  22. atlassian/confluence/cloud/graphql.py +99 -0
  23. atlassian/confluence/server/__init__.py +344 -76
  24. atlassian/confluence_base.py +24 -13
  25. atlassian/crowd.py +78 -0
  26. atlassian/jira/__init__.py +21 -0
  27. atlassian/jira/core_methods.py +11698 -0
  28. atlassian/jira/jira_cloud.py +243 -0
  29. atlassian/{jira.py → jira/jira_server.py} +498 -37
  30. atlassian/jira/service_management_methods.py +1381 -0
  31. atlassian/jira/software_methods.py +2114 -0
  32. atlassian/rest_client.py +26 -1
  33. atlassian/service_desk.py +79 -12
  34. atlassian/{xray.py → xray/__init__.py} +136 -9
  35. atlassian/yogi/__init__.py +17 -0
  36. atlassian/yogi/base.py +11 -0
  37. atlassian/yogi/cloud.py +2367 -0
  38. atlassian/yogi/yogi_confluence_cloud.py +10 -0
  39. atlassian/yogi/yogi_confluence_dc.py +94 -0
  40. atlassian/yogi/yogi_jira_cloud.py +10 -0
  41. atlassian/yogi/yogi_jira_dc.py +64 -0
  42. {atlassian_python_api-5.0.1.dist-info → atlassian_python_api-5.0.3.dist-info}/METADATA +80 -10
  43. {atlassian_python_api-5.0.1.dist-info → atlassian_python_api-5.0.3.dist-info}/RECORD +46 -27
  44. {atlassian_python_api-5.0.1.dist-info → atlassian_python_api-5.0.3.dist-info}/WHEEL +0 -0
  45. {atlassian_python_api-5.0.1.dist-info → atlassian_python_api-5.0.3.dist-info}/licenses/LICENSE +0 -0
  46. {atlassian_python_api-5.0.1.dist-info → atlassian_python_api-5.0.3.dist-info}/top_level.txt +0 -0
atlassian/bamboo.py CHANGED
@@ -82,7 +82,10 @@ class Bamboo(AtlassianRestAPI):
82
82
  if clover_enabled:
83
83
  flags.append("cloverEnabled")
84
84
  if label:
85
- params["label"] = label
85
+ # Requests serializes a sequence value as repeated query
86
+ # parameters (``label=one&label=two``), which is the Bamboo REST
87
+ # API representation for filtering by multiple labels.
88
+ params["label"] = label if isinstance(label, str) else list(label)
86
89
  params.update(kwargs)
87
90
  if "elements_key" in kwargs and "element_key" in kwargs:
88
91
  return self._get_generator(
@@ -227,6 +230,59 @@ class Bamboo(AtlassianRestAPI):
227
230
  resource = f"rest/api/latest/plan/{plan_key}"
228
231
  return self.get(resource, params=params)
229
232
 
233
+ def get_plan_specs(self, plan_key, package=None, format="YAML"):
234
+ """Export a plan as Bamboo Specs source code.
235
+
236
+ Bamboo does not provide a repositories-only REST endpoint. The
237
+ response's ``spec.code`` field contains the plan definition, including
238
+ its ``repositories`` section. ``YAML`` is the most convenient format
239
+ for repository audits; Bamboo also supports ``JAVA`` on compatible
240
+ releases.
241
+
242
+ :param plan_key: Full plan key, for example ``PROJECT-PLAN``.
243
+ :param package: Optional Java package name when exporting Java Specs.
244
+ :param format: Export format, normally ``YAML`` or ``JAVA``.
245
+ :return: The ``RestPlanSpec`` response containing ``spec.code``.
246
+ """
247
+ params = {"format": format}
248
+ if package is not None:
249
+ params["package"] = package
250
+ return self.get(self.resource_url(f"plan/{plan_key}/specs"), params=params)
251
+
252
+ def search_linked_repositories(self, search_term=None):
253
+ """Search globally configured Bamboo linked repositories.
254
+
255
+ The public Bamboo REST API can search existing linked repositories but
256
+ does not create or update their connection configuration. Create those
257
+ connections in Bamboo administration, then use the returned repository
258
+ ID with :meth:`link_repository_to_project`.
259
+
260
+ :param search_term: Optional repository-name fragment.
261
+ :return: Bamboo's paged linked-repository response.
262
+ """
263
+ params = {}
264
+ if search_term is not None:
265
+ params["searchTerm"] = search_term
266
+ return self.get(self.resource_url("repository"), params=params)
267
+
268
+ def get_project_linked_repositories(self, project_key):
269
+ """Return linked repositories authorized for Bamboo Specs in a project."""
270
+ return self.get(self.resource_url(f"project/{project_key}/repository"))
271
+
272
+ def link_repository_to_project(self, project_key, repository_id):
273
+ """Authorize an existing linked repository for Bamboo Specs in a project.
274
+
275
+ This grants a repository-stored Bamboo Specs repository permission to
276
+ create or edit plans in ``project_key``. It does not change the
277
+ repositories checked out by an existing plan; update and apply that
278
+ plan's Bamboo Specs for plan-level repository changes.
279
+ """
280
+ return self.post(self.resource_url(f"project/{project_key}/repository"), data={"id": repository_id})
281
+
282
+ def unlink_repository_from_project(self, project_key, repository_id):
283
+ """Remove a project-level Bamboo Specs repository authorization."""
284
+ return self.delete(self.resource_url(f"project/{project_key}/repository/{repository_id}"))
285
+
230
286
  def search_plans(self, search_term, fuzzy=True, start_index=0, max_results=25):
231
287
  """
232
288
  Search plans by name
@@ -397,6 +453,7 @@ class Bamboo(AtlassianRestAPI):
397
453
  start_index=0,
398
454
  max_results=25,
399
455
  include_all_states=False,
456
+ build_state=None,
400
457
  ):
401
458
  """
402
459
  Get results as generic method
@@ -408,10 +465,12 @@ class Bamboo(AtlassianRestAPI):
408
465
  :param favourite:
409
466
  :param clover_enabled:
410
467
  :param issue_key:
411
- :param label:
468
+ :param label: A label string or an iterable of labels.
412
469
  :param start_index:
413
470
  :param max_results:
414
471
  :param include_all_states:
472
+ :param build_state: Optional Bamboo result state, such as
473
+ ``Successful`` or ``Failed``.
415
474
  :return:
416
475
  """
417
476
  resource = "result"
@@ -429,6 +488,8 @@ class Bamboo(AtlassianRestAPI):
429
488
  params["issueKey"] = issue_key
430
489
  if include_all_states:
431
490
  params["includeAllStates"] = include_all_states
491
+ if build_state is not None:
492
+ params["buildstate"] = build_state
432
493
  return self.base_list_call(
433
494
  resource,
434
495
  expand=expand,
@@ -525,6 +586,7 @@ class Bamboo(AtlassianRestAPI):
525
586
  start_index=0,
526
587
  max_results=25,
527
588
  include_all_states=False,
589
+ build_state=None,
528
590
  ):
529
591
  """
530
592
  Get Plan results
@@ -538,6 +600,8 @@ class Bamboo(AtlassianRestAPI):
538
600
  :param start_index:
539
601
  :param max_results:
540
602
  :param include_all_states:
603
+ :param build_state: Optional Bamboo result state, such as
604
+ ``Successful`` or ``Failed``.
541
605
  :return:
542
606
  """
543
607
  return self.results(
@@ -551,8 +615,71 @@ class Bamboo(AtlassianRestAPI):
551
615
  start_index=start_index,
552
616
  max_results=max_results,
553
617
  include_all_states=include_all_states,
618
+ build_state=build_state,
554
619
  )
555
620
 
621
+ def ordered_plan_results(
622
+ self,
623
+ project_key,
624
+ plan_key,
625
+ order="descending",
626
+ build_state=None,
627
+ max_results=25,
628
+ **kwargs,
629
+ ):
630
+ """Return retrieved plan results ordered by completion time.
631
+
632
+ Bamboo's result API does not expose a server-side sort parameter. This
633
+ helper orders the result page client-side by ``buildCompletedTime``.
634
+ Set ``max_results`` high enough to include the history being compared;
635
+ this method returns a list rather than the lazy generator returned by
636
+ :meth:`plan_results`.
637
+
638
+ :param order: ``"ascending"`` for oldest first or ``"descending"``
639
+ for newest first.
640
+ :param build_state: Optional ``Successful`` or ``Failed`` filter.
641
+ :param max_results: Number of results Bamboo should return to sort.
642
+ :return: A list of build results ordered by completion time.
643
+ """
644
+ if order not in {"ascending", "descending"}:
645
+ raise ValueError("order must be 'ascending' or 'descending'")
646
+
647
+ results = self.plan_results(
648
+ project_key,
649
+ plan_key,
650
+ build_state=build_state,
651
+ max_results=max_results,
652
+ **kwargs,
653
+ )
654
+ return sorted(
655
+ results,
656
+ key=lambda result: result.get("buildCompletedTime") or "",
657
+ reverse=order == "descending",
658
+ )
659
+
660
+ def latest_successful_plan_result(self, project_key, plan_key, max_results=25, **kwargs):
661
+ """Return the newest successful plan result, or ``None`` when absent."""
662
+ results = self.ordered_plan_results(
663
+ project_key,
664
+ plan_key,
665
+ build_state="Successful",
666
+ max_results=max_results,
667
+ **kwargs,
668
+ )
669
+ return results[0] if results else None
670
+
671
+ def oldest_failed_plan_result(self, project_key, plan_key, max_results=25, **kwargs):
672
+ """Return the oldest failed plan result, or ``None`` when absent."""
673
+ results = self.ordered_plan_results(
674
+ project_key,
675
+ plan_key,
676
+ order="ascending",
677
+ build_state="Failed",
678
+ max_results=max_results,
679
+ **kwargs,
680
+ )
681
+ return results[0] if results else None
682
+
556
683
  def build_result(
557
684
  self,
558
685
  build_key,
@@ -654,6 +781,23 @@ class Bamboo(AtlassianRestAPI):
654
781
 
655
782
  return self.post(self.resource_url(resource), params=params)
656
783
 
784
+ def queue_build(self, plan_key, params=None):
785
+ """Add a plan to the Bamboo build queue.
786
+
787
+ ``params`` maps directly to Bamboo's queue request parameters. For
788
+ example, pass ``{"bamboo.variable.release": "1.2.3"}`` to set a
789
+ custom plan variable. Builds execute all stages by default; provide an
790
+ explicit ``executeAllStages`` or ``stage`` value to override that
791
+ behavior. The supplied mapping is never modified.
792
+
793
+ :param plan_key: Full plan key, for example ``PROJECT-PLAN``.
794
+ :param params: Optional queue parameters and custom variables.
795
+ :return: The queued build response.
796
+ """
797
+ queue_params = dict(params or {})
798
+ queue_params.setdefault("executeAllStages", "true")
799
+ return self.post(self.resource_url(f"queue/{plan_key}"), params=queue_params)
800
+
657
801
  def stop_build(self, plan_key):
658
802
  """
659
803
  Stop the build which is in progress at the moment.
@@ -1203,6 +1347,38 @@ class Bamboo(AtlassianRestAPI):
1203
1347
  params={"includeShared": include_shared},
1204
1348
  )
1205
1349
 
1350
+ def add_agent_capability(self, agent_id, data):
1351
+ """Add a capability to an agent using Bamboo's capability payload."""
1352
+ return self.post(self.resource_url(f"agent/{agent_id}/capability"), data=data)
1353
+
1354
+ def delete_agent_capability(self, agent_id, capability_key):
1355
+ """Delete one agent capability by its Bamboo capability key."""
1356
+ return self.delete(self.resource_url(f"agent/{agent_id}/capability/{capability_key}"))
1357
+
1358
+ def delete_all_agent_capabilities(self, agent_id):
1359
+ """Delete every capability assigned directly to an agent."""
1360
+ return self.delete(self.resource_url(f"agent/{agent_id}/capability"))
1361
+
1362
+ def get_plan_variables(self, plan_key):
1363
+ """Return variables configured for a plan."""
1364
+ return self.get(self.resource_url(f"plan/{plan_key}/variable"))
1365
+
1366
+ def get_plan_variable(self, plan_key, variable_name):
1367
+ """Return one plan variable by name."""
1368
+ return self.get(self.resource_url(f"plan/{plan_key}/variable/{variable_name}"))
1369
+
1370
+ def create_plan_variable(self, plan_key, data):
1371
+ """Create a plan variable from Bamboo's variable request body."""
1372
+ return self.post(self.resource_url(f"plan/{plan_key}/variable"), data=data)
1373
+
1374
+ def update_plan_variable(self, plan_key, variable_name, data):
1375
+ """Update a plan variable."""
1376
+ return self.put(self.resource_url(f"plan/{plan_key}/variable/{variable_name}"), data=data)
1377
+
1378
+ def delete_plan_variable(self, plan_key, variable_name):
1379
+ """Delete a plan variable."""
1380
+ return self.delete(self.resource_url(f"plan/{plan_key}/variable/{variable_name}"))
1381
+
1206
1382
  def activity(self, busy=None):
1207
1383
  """Return active online agents and their current build activity.
1208
1384
 
@@ -1,7 +1,7 @@
1
1
  # coding=utf-8
2
2
  import logging
3
3
  from enum import Enum
4
- from typing import Optional
4
+ from typing import Any, Dict, List, Optional
5
5
 
6
6
  from deprecated import deprecated
7
7
  from requests import HTTPError
@@ -124,6 +124,17 @@ class Bitbucket(BitbucketBase):
124
124
  url = self.resource_url("status", api_root="rest/indexing", api_version="latest")
125
125
  return self.get(url)
126
126
 
127
+ def get_cluster_info(self):
128
+ """Get system information for the Bitbucket Data Center cluster.
129
+
130
+ This administrative endpoint is available on Bitbucket Server/Data
131
+ Center only and requires the appropriate administrator permission.
132
+ """
133
+ if self.cloud:
134
+ raise NotImplementedError("Cluster information is only available on Bitbucket Server/Data Center")
135
+ url = self.resource_url("admin/cluster", api_version="latest")
136
+ return self.get(url)
137
+
127
138
  def get_users(self, user_filter=None, limit=25, start=0):
128
139
  """
129
140
  Get list of bitbucket users.
@@ -290,6 +301,126 @@ class Bitbucket(BitbucketBase):
290
301
  files = {"plugin": open(plugin_path, "rb")}
291
302
  return self.post(url, files=files, headers=self.no_check_headers)
292
303
 
304
+ ################################################################################################
305
+ # Hook scripts (Bitbucket Data Center 8+)
306
+ ################################################################################################
307
+ def _url_hook_scripts(self):
308
+ return self.resource_url("hook-scripts", api_version="latest")
309
+
310
+ def create_hook_script(self, content: bytes, name: str, hook_type: str, description: Optional[str] = None):
311
+ """Register a global hook script on Bitbucket Data Center.
312
+
313
+ ``hook_type`` must be ``PRE`` or ``POST``. The caller must be a system
314
+ administrator, and Bitbucket Data Center 8.18+ requires hook scripts to
315
+ be explicitly enabled with ``feature.hook.scripts=true``.
316
+
317
+ The API expects a multipart form. ``content`` is the executable script
318
+ bytes; no temporary file is created by the client.
319
+ """
320
+ if hook_type not in ("PRE", "POST"):
321
+ raise ValueError("hook_type must be 'PRE' or 'POST'")
322
+
323
+ files: Dict[str, Any] = {
324
+ "content": ("hook-script", content, "application/octet-stream"),
325
+ "name": (None, name),
326
+ "type": (None, hook_type),
327
+ }
328
+ if description is not None:
329
+ files["description"] = (None, description)
330
+ return self.post(self._url_hook_scripts(), files=files, headers=self.no_check_headers)
331
+
332
+ def configure_project_hook_script(self, project_key: str, script_id: int, trigger_ids: Optional[List[str]] = None):
333
+ """Configure a registered hook script for every repository in a project.
334
+
335
+ Requires project administrator permission. ``trigger_ids`` controls the
336
+ hook triggers to which the script is bound.
337
+ """
338
+ url = f"{self._url_project(project_key, api_version='latest')}/hook-scripts/{script_id}"
339
+ return self.put(url, data={"triggerIds": trigger_ids or []})
340
+
341
+ def configure_repo_hook_script(
342
+ self, project_key: str, repository_slug: str, script_id: int, trigger_ids: Optional[List[str]] = None
343
+ ):
344
+ """Configure a registered hook script for a repository.
345
+
346
+ Requires repository administrator permission. ``trigger_ids`` controls
347
+ the hook triggers to which the script is bound.
348
+ """
349
+ url = f"{self._url_repo(project_key, repository_slug, api_version='latest')}/hook-scripts/{script_id}"
350
+ return self.put(url, data={"triggerIds": trigger_ids or []})
351
+
352
+ def get_project_hook_scripts(self, project_key: str, start: int = 0, limit: Optional[int] = None):
353
+ """Yield hook-script configurations for a project."""
354
+ params: Dict[str, int] = {"start": start}
355
+ if limit is not None:
356
+ params["limit"] = limit
357
+ url = f"{self._url_project(project_key, api_version='latest')}/hook-scripts"
358
+ return self._get_paged(url, params=params)
359
+
360
+ def get_repo_hook_scripts(
361
+ self, project_key: str, repository_slug: str, start: int = 0, limit: Optional[int] = None
362
+ ):
363
+ """Yield hook-script configurations for a repository."""
364
+ params: Dict[str, int] = {"start": start}
365
+ if limit is not None:
366
+ params["limit"] = limit
367
+ url = f"{self._url_repo(project_key, repository_slug, api_version='latest')}/hook-scripts"
368
+ return self._get_paged(url, params=params)
369
+
370
+ def delete_project_hook_script(self, project_key: str, script_id: int):
371
+ """Remove a hook-script configuration from a project."""
372
+ url = f"{self._url_project(project_key, api_version='latest')}/hook-scripts/{script_id}"
373
+ return self.delete(url)
374
+
375
+ def delete_repo_hook_script(self, project_key: str, repository_slug: str, script_id: int):
376
+ """Remove a hook-script configuration from a repository."""
377
+ url = f"{self._url_repo(project_key, repository_slug, api_version='latest')}/hook-scripts/{script_id}"
378
+ return self.delete(url)
379
+
380
+ def get_hook_script(self, script_id: int):
381
+ """Return the registered global hook script with ``script_id``.
382
+
383
+ The result only contains the script metadata; use
384
+ ``get_hook_script_content()`` to fetch the script body.
385
+ """
386
+ return self.get(f"{self._url_hook_scripts()}/{script_id}")
387
+
388
+ def get_hook_script_content(self, script_id: int):
389
+ """Return the raw body of the registered global hook script.
390
+
391
+ ``not_json_response`` is used because the endpoint returns the
392
+ executable script as plain text rather than a JSON payload.
393
+ """
394
+ return self.get(
395
+ f"{self._url_hook_scripts()}/{script_id}/content",
396
+ not_json_response=True,
397
+ )
398
+
399
+ def update_hook_script(
400
+ self, script_id: int, content: bytes, name: str, hook_type: str, description: Optional[str] = None
401
+ ):
402
+ """Update a registered global hook script on Bitbucket Data Center.
403
+
404
+ ``hook_type`` must be ``PRE`` or ``POST``. Like ``create_hook_script``,
405
+ the API expects a multipart form; ``content`` is the executable script
406
+ bytes.
407
+ """
408
+ if hook_type not in ("PRE", "POST"):
409
+ raise ValueError("hook_type must be 'PRE' or 'POST'")
410
+
411
+ files: Dict[str, Any] = {
412
+ "content": ("hook-script", content, "application/octet-stream"),
413
+ "name": (None, name),
414
+ "type": (None, hook_type),
415
+ }
416
+ if description is not None:
417
+ files["description"] = (None, description)
418
+ return self.put(f"{self._url_hook_scripts()}/{script_id}", files=files, headers=self.no_check_headers)
419
+
420
+ def delete_hook_script(self, script_id: int):
421
+ """Delete the registered global hook script with ``script_id``."""
422
+ return self.delete(f"{self._url_hook_scripts()}/{script_id}")
423
+
293
424
  def get_categories(self, project_key, repository_slug=None):
294
425
  """
295
426
  Get a list of categories assigned to a project or repository.
@@ -762,6 +893,16 @@ class Bitbucket(BitbucketBase):
762
893
  return self._get_paged(url, params=params)
763
894
 
764
895
  def _url_repos(self, project_key, api_root=None, api_version=None):
896
+ """Return the repository collection URL for a project or personal owner.
897
+
898
+ Bitbucket Server/Data Center addresses personal repositories through a
899
+ user-centric route. Pass the owner's user slug with a leading ``~``
900
+ (for example, ``~alice``) wherever a ``project_key`` is accepted by a
901
+ repository method. Project repositories continue to use the existing
902
+ ``projects/{projectKey}/repos`` route.
903
+ """
904
+ if not self.cloud and str(project_key).startswith("~"):
905
+ return self.resource_url(f"users/{project_key}/repos", api_root, api_version)
765
906
  return f"{self._url_project(project_key, api_root, api_version)}/repos"
766
907
 
767
908
  def repo_list(self, project_key, start=0, limit=25):
@@ -895,6 +1036,40 @@ class Bitbucket(BitbucketBase):
895
1036
  url = self._url_repo(project_key, repository_slug)
896
1037
  return self.put(url, data=params)
897
1038
 
1039
+ def get_repo_forkable(self, project_key, repository_slug):
1040
+ """Return whether a Bitbucket Server/Data Center repository is forkable.
1041
+
1042
+ :param project_key: Project key, or a ``~user`` personal repository owner.
1043
+ :param repository_slug: URL-compatible repository identifier.
1044
+ :return: The repository's ``forkable`` flag, or ``None`` when omitted
1045
+ by an older Bitbucket version.
1046
+ """
1047
+ return (self.get_repo(project_key, repository_slug) or {}).get("forkable")
1048
+
1049
+ def set_repo_forkable(self, project_key, repository_slug, forkable):
1050
+ """Enable or disable forking for a Server/Data Center repository.
1051
+
1052
+ The caller requires repository administration permission. This uses the
1053
+ repository ``PUT`` endpoint and preserves the behavior of
1054
+ :meth:`update_repo` for all other repository fields.
1055
+
1056
+ :param project_key: Project key, or a ``~user`` personal repository owner.
1057
+ :param repository_slug: URL-compatible repository identifier.
1058
+ :param forkable: ``True`` to allow forks or ``False`` to prohibit them.
1059
+ :return: Updated repository representation.
1060
+ """
1061
+ if not isinstance(forkable, bool):
1062
+ raise TypeError("forkable must be a boolean")
1063
+ return self.update_repo(project_key, repository_slug, forkable=forkable)
1064
+
1065
+ def enable_repo_forking(self, project_key, repository_slug):
1066
+ """Enable forking for a Server/Data Center repository."""
1067
+ return self.set_repo_forkable(project_key, repository_slug, True)
1068
+
1069
+ def disable_repo_forking(self, project_key, repository_slug):
1070
+ """Disable forking for a Server/Data Center repository."""
1071
+ return self.set_repo_forkable(project_key, repository_slug, False)
1072
+
898
1073
  def delete_repo(self, project_key, repository_slug):
899
1074
  """
900
1075
  Delete a specific repository from a project. This operates based on slug not name which may
@@ -1,6 +1,7 @@
1
1
  # coding=utf-8
2
2
 
3
3
  import copy
4
+ import re
4
5
  from datetime import datetime
5
6
  from pprint import PrettyPrinter
6
7
 
@@ -158,8 +159,14 @@ class BitbucketBase(AtlassianRestAPI):
158
159
  if isinstance(value_str, str):
159
160
  # Bitbucket Cloud returns ISO 8601 timestamps with optional
160
161
  # fractional seconds and either an offset or a trailing ``Z``.
161
- # Do not trim or otherwise alter the timestamp: doing so turns
162
- # ``+00:00`` into the invalid ``+00:00Z`` form.
162
+ # Python 3.10 and older only accept 0, 3, or 6 fractional digits,
163
+ # while Bitbucket may return another precision. Clamp the fraction
164
+ # to microsecond precision without touching the UTC offset.
165
+ value_str = re.sub(
166
+ r"\.(\d+)(?=(?:Z|[+-]\d{2}:?\d{2})?$)",
167
+ lambda match: "." + match.group(1)[:6].ljust(6, "0"),
168
+ value_str,
169
+ )
163
170
  value = datetime.fromisoformat(value_str.replace("Z", "+00:00"))
164
171
  else:
165
172
  value = value_str
@@ -15,15 +15,19 @@ class Commits(BitbucketCloudBase):
15
15
  def __get_object(self, data):
16
16
  return Commit(data, **self._new_session_args)
17
17
 
18
- def each(self, top=None, q=None, sort=None):
18
+ def each(self, top=None, q=None, sort=None, include=None, exclude=None, path=None):
19
19
  """
20
20
  Return the list of commits in this repository.
21
21
 
22
22
  :param top: string: Hash of commit to get the history for.
23
- :param q: string: Query string to narrow down the response.
24
- See https://developer.atlassian.com/bitbucket/api/2/reference/meta/filtering for details.
23
+ :param q: string: Legacy query expression. Bitbucket Cloud does not
24
+ support arbitrary ``q`` filtering for commits; it is
25
+ retained for compatibility and passed to the API.
25
26
  :param sort: string: Name of a response property to sort results.
26
27
  See https://developer.atlassian.com/bitbucket/api/2/reference/meta/filtering for details.
28
+ :param include: string: Commit or ref to include in the history.
29
+ :param exclude: string: Commit or ref to exclude from the history.
30
+ :param path: string: File path used to filter commits.
27
31
 
28
32
  :return: A generator for the Commit objects
29
33
 
@@ -35,6 +39,12 @@ class Commits(BitbucketCloudBase):
35
39
  params["sort"] = sort
36
40
  if q is not None:
37
41
  params["q"] = q
42
+ if include is not None:
43
+ params["include"] = include
44
+ if exclude is not None:
45
+ params["exclude"] = exclude
46
+ if path is not None:
47
+ params["path"] = path
38
48
  trailing = True
39
49
  if top is not None:
40
50
  trailing = False
@@ -60,6 +60,29 @@ class RepositoryVariables(BitbucketCloudBase):
60
60
 
61
61
  return
62
62
 
63
+ def get_by_key(self, key):
64
+ """Return the repository variable with ``key``, or ``None``.
65
+
66
+ Bitbucket requires the variable UUID for the item endpoint. This
67
+ helper follows the paginated collection and returns the object with
68
+ its UUID, avoiding callers having to implement that lookup themselves.
69
+ """
70
+ for variable in self.each(q=f'key="{key}"'):
71
+ if variable.key == key:
72
+ return variable
73
+ return None
74
+
75
+ def update_by_key(self, key, value, secured=None):
76
+ """Update a repository variable by its key and return the object."""
77
+ variable = self.get_by_key(key)
78
+ if variable is None:
79
+ raise ValueError(f"Repository variable with key {key!r} was not found")
80
+
81
+ data = {"value": value}
82
+ if secured is not None:
83
+ data["secured"] = secured
84
+ return variable.update(**data)
85
+
63
86
  def get(self, uuid: str): # type: ignore[override]
64
87
  """
65
88
  Returns the pipeline with the uuid in this repository.
@@ -16,7 +16,7 @@ class Workspaces(BitbucketCloudBase):
16
16
  def __get_object(self, data):
17
17
  return Workspace(data, **self._new_session_args)
18
18
 
19
- def each(self, role=None, q=None, sort=None):
19
+ def each(self, role=None, q=None, sort=None, administrator=None):
20
20
  """
21
21
  Get all workspaces matching the criteria.
22
22
 
@@ -33,6 +33,9 @@ class Workspaces(BitbucketCloudBase):
33
33
  :param sort: string (default is None):
34
34
  Name of a response property to sort results.
35
35
  See https://developer.atlassian.com/bitbucket/api/2/reference/meta/filtering for details.
36
+ :param administrator: bool (default is None):
37
+ Filter workspaces by whether the authenticated user
38
+ is a workspace administrator.
36
39
 
37
40
  :return: A generator for the Workspace objects
38
41
 
@@ -48,6 +51,8 @@ class Workspaces(BitbucketCloudBase):
48
51
  # would produce an invalid request.
49
52
  if sort is not None:
50
53
  params["sort"] = sort
54
+ if administrator is not None:
55
+ params["administrator"] = administrator
51
56
  user_workspaces_url = f"{self.url.rsplit('/', 1)[0]}/user/workspaces"
52
57
  for workspace_access in self._get_paged(user_workspaces_url, params=params, absolute=True):
53
58
  workspace_data = workspace_access.get("workspace", workspace_access)
@@ -3,6 +3,7 @@
3
3
  from .base import BitbucketServerBase
4
4
  from .globalPermissions import Groups, Users
5
5
  from .projects import Projects
6
+ from .projects.repos import Repositories
6
7
 
7
8
 
8
9
  class Server(BitbucketServerBase):
@@ -44,3 +45,13 @@ class Server(BitbucketServerBase):
44
45
  Reference: https://docs.atlassian.com/bitbucket-server/rest/7.8.0/bitbucket-rest.html#idp147
45
46
  """
46
47
  return self.__projects
48
+
49
+ def personal_repositories(self, username):
50
+ """Return repositories owned by a Bitbucket Server/Data Center user.
51
+
52
+ ``username`` may be supplied with or without the leading ``~``. The
53
+ returned collection has the same API as ``project.repos`` and uses
54
+ Bitbucket's user-centric ``/users/{userSlug}/repos`` endpoint.
55
+ """
56
+ user_slug = username if username.startswith("~") else f"~{username}"
57
+ return Repositories(self._sub_url(f"users/{user_slug}/repos"), **self._new_session_args)