2
0

lib.rs 5.5 KB

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