bundle.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # bundle.py -- Bundle format support
  2. # Copyright (C) 2020 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Bundle format support."""
  22. from collections.abc import Sequence
  23. from typing import Optional, Union
  24. from .pack import PackData, write_pack_data
  25. class Bundle:
  26. version: Optional[int]
  27. capabilities: dict[str, str]
  28. prerequisites: list[tuple[bytes, str]]
  29. references: dict[str, bytes]
  30. pack_data: Union[PackData, Sequence[bytes]]
  31. def __repr__(self) -> str:
  32. return (
  33. f"<{type(self).__name__}(version={self.version}, "
  34. f"capabilities={self.capabilities}, "
  35. f"prerequisites={self.prerequisites}, "
  36. f"references={self.references})>"
  37. )
  38. def __eq__(self, other):
  39. if not isinstance(other, type(self)):
  40. return False
  41. if self.version != other.version:
  42. return False
  43. if self.capabilities != other.capabilities:
  44. return False
  45. if self.prerequisites != other.prerequisites:
  46. return False
  47. if self.references != other.references:
  48. return False
  49. if self.pack_data != other.pack_data:
  50. return False
  51. return True
  52. def _read_bundle(f, version):
  53. capabilities = {}
  54. prerequisites = []
  55. references = {}
  56. line = f.readline()
  57. if version >= 3:
  58. while line.startswith(b"@"):
  59. line = line[1:].rstrip(b"\n")
  60. try:
  61. key, value = line.split(b"=", 1)
  62. except ValueError:
  63. key = line
  64. value = None
  65. else:
  66. value = value.decode("utf-8")
  67. capabilities[key.decode("utf-8")] = value
  68. line = f.readline()
  69. while line.startswith(b"-"):
  70. (obj_id, comment) = line[1:].rstrip(b"\n").split(b" ", 1)
  71. prerequisites.append((obj_id, comment.decode("utf-8")))
  72. line = f.readline()
  73. while line != b"\n":
  74. (obj_id, ref) = line.rstrip(b"\n").split(b" ", 1)
  75. references[ref] = obj_id
  76. line = f.readline()
  77. pack_data = PackData.from_file(f)
  78. ret = Bundle()
  79. ret.references = references
  80. ret.capabilities = capabilities
  81. ret.prerequisites = prerequisites
  82. ret.pack_data = pack_data
  83. ret.version = version
  84. return ret
  85. def read_bundle(f):
  86. """Read a bundle file."""
  87. firstline = f.readline()
  88. if firstline == b"# v2 git bundle\n":
  89. return _read_bundle(f, 2)
  90. if firstline == b"# v3 git bundle\n":
  91. return _read_bundle(f, 3)
  92. raise AssertionError(f"unsupported bundle format header: {firstline!r}")
  93. def write_bundle(f, bundle) -> None:
  94. version = bundle.version
  95. if version is None:
  96. if bundle.capabilities:
  97. version = 3
  98. else:
  99. version = 2
  100. if version == 2:
  101. f.write(b"# v2 git bundle\n")
  102. elif version == 3:
  103. f.write(b"# v3 git bundle\n")
  104. else:
  105. raise AssertionError("unknown version %d" % version)
  106. if version == 3:
  107. for key, value in bundle.capabilities.items():
  108. f.write(b"@" + key.encode("utf-8"))
  109. if value is not None:
  110. f.write(b"=" + value.encode("utf-8"))
  111. f.write(b"\n")
  112. for obj_id, comment in bundle.prerequisites:
  113. f.write(b"-%s %s\n" % (obj_id, comment.encode("utf-8")))
  114. for ref, obj_id in bundle.references.items():
  115. f.write(b"%s %s\n" % (obj_id, ref))
  116. f.write(b"\n")
  117. write_pack_data(
  118. f.write,
  119. num_records=len(bundle.pack_data),
  120. records=bundle.pack_data.iter_unpacked(),
  121. )