lib.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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, strict=None))]
  46. fn parse_tree(
  47. py: Python,
  48. mut text: &[u8],
  49. strict: Option<bool>,
  50. ) -> PyResult<Vec<(Py<PyAny>, u32, Py<PyAny>)>> {
  51. let mut entries = Vec::new();
  52. let strict = strict.unwrap_or(false);
  53. while !text.is_empty() {
  54. let mode_end = memchr(b' ', text)
  55. .ok_or_else(|| ObjectFormatException::new_err(("Missing terminator for mode",)))?;
  56. let text_str = String::from_utf8_lossy(&text[..mode_end]).to_string();
  57. let mode = u32::from_str_radix(text_str.as_str(), 8)
  58. .map_err(|e| ObjectFormatException::new_err((format!("invalid mode: {}", e),)))?;
  59. if strict && text[0] == b'0' {
  60. return Err(ObjectFormatException::new_err((
  61. "Illegal leading zero on mode",
  62. )));
  63. }
  64. text = &text[mode_end + 1..];
  65. let namelen = memchr(b'\0', text)
  66. .ok_or_else(|| ObjectFormatException::new_err(("Missing trailing \\0",)))?;
  67. let name = &text[..namelen];
  68. if namelen + 20 >= text.len() {
  69. return Err(ObjectFormatException::new_err(("SHA truncated",)));
  70. }
  71. text = &text[namelen + 1..];
  72. let sha = &text[..20];
  73. entries.push((
  74. PyBytes::new(py, name).into_pyobject(py)?.unbind().into(),
  75. mode,
  76. sha_to_pyhex(py, sha)?,
  77. ));
  78. text = &text[20..];
  79. }
  80. Ok(entries)
  81. }
  82. fn cmp_with_suffix(a: (u32, &[u8]), b: (u32, &[u8])) -> std::cmp::Ordering {
  83. let len = std::cmp::min(a.1.len(), b.1.len());
  84. let cmp = a.1[..len].cmp(&b.1[..len]);
  85. if cmp != std::cmp::Ordering::Equal {
  86. return cmp;
  87. }
  88. let c1 =
  89. a.1.get(len)
  90. .map_or_else(|| if (a.0 & S_IFMT) == S_IFDIR { b'/' } else { 0 }, |&c| c);
  91. let c2 =
  92. b.1.get(len)
  93. .map_or_else(|| if (b.0 & S_IFMT) == S_IFDIR { b'/' } else { 0 }, |&c| c);
  94. c1.cmp(&c2)
  95. }
  96. /// Iterate over a tree entries dictionary.
  97. ///
  98. /// # Arguments
  99. ///
  100. /// name_order: If True, iterate entries in order of their name. If
  101. /// False, iterate entries in tree order, that is, treat subtree entries as
  102. /// having '/' appended.
  103. /// entries: Dictionary mapping names to (mode, sha) tuples
  104. ///
  105. /// # Returns: Iterator over (name, mode, hexsha)
  106. #[pyfunction]
  107. fn sorted_tree_items(
  108. py: Python,
  109. entries: &Bound<PyDict>,
  110. name_order: bool,
  111. ) -> PyResult<Vec<Py<PyAny>>> {
  112. let mut qsort_entries = entries
  113. .iter()
  114. .map(|(name, value)| -> PyResult<(Vec<u8>, u32, Vec<u8>)> {
  115. let value = value
  116. .extract::<(u32, Vec<u8>)>()
  117. .map_err(|e| PyTypeError::new_err((format!("invalid type: {}", e),)))?;
  118. Ok((name.extract::<Vec<u8>>().unwrap(), value.0, value.1))
  119. })
  120. .collect::<PyResult<Vec<(Vec<u8>, u32, Vec<u8>)>>>()?;
  121. if name_order {
  122. qsort_entries.sort_by(|a, b| a.0.cmp(&b.0));
  123. } else {
  124. qsort_entries.sort_by(|a, b| cmp_with_suffix((a.1, a.0.as_slice()), (b.1, b.0.as_slice())));
  125. }
  126. let objectsm = py.import("dulwich.objects")?;
  127. let tree_entry_cls = objectsm.getattr("TreeEntry")?;
  128. qsort_entries
  129. .into_iter()
  130. .map(|(name, mode, hexsha)| -> PyResult<Py<PyAny>> {
  131. Ok(tree_entry_cls
  132. .call1((
  133. PyBytes::new(py, name.as_slice())
  134. .into_pyobject(py)?
  135. .unbind()
  136. .into_any(),
  137. mode,
  138. PyBytes::new(py, hexsha.as_slice())
  139. .into_pyobject(py)?
  140. .unbind()
  141. .into_any(),
  142. ))?
  143. .unbind()
  144. .into())
  145. })
  146. .collect::<PyResult<Vec<Py<PyAny>>>>()
  147. }
  148. #[pymodule]
  149. fn _objects(_py: Python, m: &Bound<PyModule>) -> PyResult<()> {
  150. m.add_function(wrap_pyfunction!(sorted_tree_items, m)?)?;
  151. m.add_function(wrap_pyfunction!(parse_tree, m)?)?;
  152. Ok(())
  153. }