lib.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /*
  2. * Copyright (C) 2009 Jelmer Vernooij <jelmer@jelmer.uk>
  3. *
  4. * Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. * General Public License as published by the Free Software Foundation; version 2.0
  6. * or (at your option) any later version. You can redistribute it and/or
  7. * modify it under the terms of either of these two licenses.
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. *
  15. * You should have received a copy of the licenses; if not, see
  16. * <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. * and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. * License, Version 2.0.
  19. */
  20. use memchr::memchr;
  21. use pyo3::exceptions::PyTypeError;
  22. use pyo3::import_exception;
  23. use pyo3::prelude::*;
  24. use pyo3::types::{PyBytes, PyDict};
  25. import_exception!(dulwich.errors, ObjectFormatException);
  26. const S_IFDIR: u32 = 0o40000;
  27. const S_IFMT: u32 = 0o170000; // File type mask
  28. #[inline]
  29. fn bytehex(byte: u8) -> u8 {
  30. match byte {
  31. 0..=9 => byte + b'0',
  32. 10..=15 => byte - 10 + b'a',
  33. _ => unreachable!(),
  34. }
  35. }
  36. fn sha_to_pyhex(py: Python, sha: &[u8]) -> PyResult<Py<PyAny>> {
  37. let mut hexsha = Vec::new();
  38. for c in sha {
  39. hexsha.push(bytehex((c & 0xF0) >> 4));
  40. hexsha.push(bytehex(c & 0x0F));
  41. }
  42. Ok(PyBytes::new(py, hexsha.as_slice()).into())
  43. }
  44. #[pyfunction]
  45. #[pyo3(signature = (text, sha_len, strict=None))]
  46. fn parse_tree(
  47. py: Python,
  48. mut text: &[u8],
  49. sha_len: usize,
  50. strict: Option<bool>,
  51. ) -> PyResult<Vec<(Py<PyAny>, u32, Py<PyAny>)>> {
  52. let strict = strict.unwrap_or(false);
  53. let mut entries = Vec::new();
  54. while !text.is_empty() {
  55. let mode_end = memchr(b' ', text)
  56. .ok_or_else(|| ObjectFormatException::new_err(("Missing terminator for mode",)))?;
  57. let text_str = String::from_utf8_lossy(&text[..mode_end]).to_string();
  58. let mode = u32::from_str_radix(text_str.as_str(), 8)
  59. .map_err(|e| ObjectFormatException::new_err((format!("invalid mode: {}", e),)))?;
  60. if strict && text[0] == b'0' {
  61. return Err(ObjectFormatException::new_err((
  62. "Illegal leading zero on mode",
  63. )));
  64. }
  65. text = &text[mode_end + 1..];
  66. let namelen = memchr(b'\0', text)
  67. .ok_or_else(|| ObjectFormatException::new_err(("Missing trailing \\0",)))?;
  68. let name = &text[..namelen];
  69. // Skip name and null terminator
  70. text = &text[namelen + 1..];
  71. // Check if we have enough bytes for the hash
  72. if text.len() < sha_len {
  73. return Err(ObjectFormatException::new_err(("SHA truncated",)));
  74. }
  75. let sha = &text[..sha_len];
  76. entries.push((
  77. PyBytes::new(py, name).into_pyobject(py)?.unbind().into(),
  78. mode,
  79. sha_to_pyhex(py, sha)?,
  80. ));
  81. text = &text[sha_len..];
  82. }
  83. Ok(entries)
  84. }
  85. fn cmp_with_suffix(a: (u32, &[u8]), b: (u32, &[u8])) -> std::cmp::Ordering {
  86. let len = std::cmp::min(a.1.len(), b.1.len());
  87. let cmp = a.1[..len].cmp(&b.1[..len]);
  88. if cmp != std::cmp::Ordering::Equal {
  89. return cmp;
  90. }
  91. let c1 =
  92. a.1.get(len)
  93. .map_or_else(|| if (a.0 & S_IFMT) == S_IFDIR { b'/' } else { 0 }, |&c| c);
  94. let c2 =
  95. b.1.get(len)
  96. .map_or_else(|| if (b.0 & S_IFMT) == S_IFDIR { b'/' } else { 0 }, |&c| c);
  97. c1.cmp(&c2)
  98. }
  99. /// Iterate over a tree entries dictionary.
  100. ///
  101. /// # Arguments
  102. ///
  103. /// name_order: If True, iterate entries in order of their name. If
  104. /// False, iterate entries in tree order, that is, treat subtree entries as
  105. /// having '/' appended.
  106. /// entries: Dictionary mapping names to (mode, sha) tuples
  107. ///
  108. /// # Returns: Iterator over (name, mode, hexsha)
  109. #[pyfunction]
  110. fn sorted_tree_items(
  111. py: Python,
  112. entries: &Bound<PyDict>,
  113. name_order: bool,
  114. ) -> PyResult<Vec<Py<PyAny>>> {
  115. let mut qsort_entries = entries
  116. .iter()
  117. .map(|(name, value)| -> PyResult<(Vec<u8>, u32, Vec<u8>)> {
  118. let value = value
  119. .extract::<(u32, Vec<u8>)>()
  120. .map_err(|e| PyTypeError::new_err((format!("invalid type: {}", e),)))?;
  121. Ok((name.extract::<Vec<u8>>().unwrap(), value.0, value.1))
  122. })
  123. .collect::<PyResult<Vec<(Vec<u8>, u32, Vec<u8>)>>>()?;
  124. if name_order {
  125. qsort_entries.sort_by(|a, b| a.0.cmp(&b.0));
  126. } else {
  127. qsort_entries.sort_by(|a, b| cmp_with_suffix((a.1, a.0.as_slice()), (b.1, b.0.as_slice())));
  128. }
  129. let objectsm = py.import("dulwich.objects")?;
  130. let tree_entry_cls = objectsm.getattr("TreeEntry")?;
  131. qsort_entries
  132. .into_iter()
  133. .map(|(name, mode, hexsha)| -> PyResult<Py<PyAny>> {
  134. Ok(tree_entry_cls
  135. .call1((
  136. PyBytes::new(py, name.as_slice())
  137. .into_pyobject(py)?
  138. .unbind()
  139. .into_any(),
  140. mode,
  141. PyBytes::new(py, hexsha.as_slice())
  142. .into_pyobject(py)?
  143. .unbind()
  144. .into_any(),
  145. ))?
  146. .unbind())
  147. })
  148. .collect::<PyResult<Vec<Py<PyAny>>>>()
  149. }
  150. #[pymodule]
  151. fn _objects(_py: Python, m: &Bound<PyModule>) -> PyResult<()> {
  152. m.add_function(wrap_pyfunction!(sorted_tree_items, m)?)?;
  153. m.add_function(wrap_pyfunction!(parse_tree, m)?)?;
  154. Ok(())
  155. }