Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/copy.py

raw
1 from typing import Any
2
3 from taskgraph.task import Task
4 from taskgraph.util.readonlydict import ReadOnlyDict
5
6 immutable_types = {int, float, bool, str, type(None), ReadOnlyDict}
7
8
9 def deepcopy(obj: Any) -> Any:
10 """Perform a deep copy of an object with a tree like structure.
11
12 This is a re-implementation of Python's `copy.deepcopy` function with a few key differences:
13
14 1. Unlike the stdlib, this does *not* support copying graph-like structure,
15 which allows it to be more efficient than deepcopy on tree-like structures
16 (such as Tasks).
17 2. This special cases support for `taskgraph.task.Task` objects.
18
19 Args:
20 obj: The object to deep copy.
21
22 Returns:
23 A deep copy of the object.
24 """
25 ty = type(obj)
26 if ty in immutable_types:
27 return obj
28 if ty is dict:
29 return {k: deepcopy(v) for k, v in obj.items()}
30 if ty is list:
31 return [deepcopy(elt) for elt in obj]
32 if ty is Task:
33 task = Task(
34 kind=deepcopy(obj.kind),
35 label=deepcopy(obj.label),
36 attributes=deepcopy(obj.attributes),
37 task=deepcopy(obj.task),
38 description=deepcopy(obj.description),
39 optimization=deepcopy(obj.optimization),
40 dependencies=deepcopy(obj.dependencies),
41 soft_dependencies=deepcopy(obj.soft_dependencies),
42 if_dependencies=deepcopy(obj.if_dependencies),
43 )
44 if obj.task_id:
45 task.task_id = obj.task_id
46 return task
47 raise NotImplementedError(f"copying '{ty}' from '{obj}'")