breezyshim 0.7.13

Rust shim around the Breezy Python API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! Graph traversal operations on revision graphs.
use crate::revisionid::RevisionId;
use pyo3::exceptions::PyStopIteration;
use pyo3::prelude::*;
use pyo3::types::{PyFrozenSet, PyIterator, PyTuple};
use std::collections::HashMap;
use std::hash::Hash;

/// Trait for types that can be used as nodes in a graph.
///
/// This trait allows graph operations to work with any type that can be
/// converted to a Python object and compared for equality.
pub trait GraphNode: Eq + Hash + Clone {
    /// Convert this node to a Python object representation.
    fn to_pyobject<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>>;

    /// Create a node from a Python object.
    fn from_pyobject(obj: &Bound<PyAny>) -> PyResult<Self>;
}

/// Represents a graph of revisions.
///
/// This struct provides methods for traversing and querying relationships
/// between revisions in a version control repository.
pub struct Graph(Py<PyAny>);

impl<'py> IntoPyObject<'py> for Graph {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = std::convert::Infallible;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        Ok(self.0.into_bound(py))
    }
}

impl<'a, 'py> FromPyObject<'a, 'py> for Graph {
    type Error = PyErr;

    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
        Ok(Graph(ob.to_owned().unbind()))
    }
}

impl From<Py<PyAny>> for Graph {
    fn from(ob: Py<PyAny>) -> Self {
        Graph(ob)
    }
}

/// Implement GraphNode for RevisionId
impl GraphNode for RevisionId {
    fn to_pyobject<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        Ok(self.as_bytes().into_pyobject(py)?.into_any())
    }

    fn from_pyobject(obj: &Bound<PyAny>) -> PyResult<Self> {
        let bytes: Vec<u8> = obj.extract()?;
        Ok(RevisionId::from(bytes))
    }
}

struct NodeIter<T: GraphNode>(Py<PyAny>, std::marker::PhantomData<T>);

impl<T: GraphNode> Iterator for NodeIter<T> {
    type Item = Result<T, crate::error::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        Python::attach(|py| match self.0.call_method0(py, "__next__") {
            Ok(item) => match T::from_pyobject(item.bind(py)) {
                Ok(node) => Some(Ok(node)),
                Err(e) => Some(Err(e.into())),
            },
            Err(e) if e.is_instance_of::<PyStopIteration>(py) => None,
            Err(e) => Some(Err(e.into())),
        })
    }
}

struct TopoOrderIter<T: GraphNode>(Py<PyAny>, std::marker::PhantomData<T>);

impl<T: GraphNode> Iterator for TopoOrderIter<T> {
    type Item = Result<(usize, T, usize, bool), crate::error::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        Python::attach(|py| match self.0.call_method0(py, "__next__") {
            Ok(item) => {
                let tuple = match item.bind(py).cast::<PyTuple>() {
                    Ok(t) => t,
                    Err(e) => return Some(Err(PyErr::from(e).into())),
                };
                if tuple.len() != 4 {
                    return Some(Err(pyo3::exceptions::PyValueError::new_err(
                        "Expected 4-tuple from iter_topo_order",
                    )
                    .into()));
                }
                match (
                    tuple.get_item(0).and_then(|i| i.extract::<usize>()),
                    tuple.get_item(1).and_then(|i| T::from_pyobject(&i)),
                    tuple.get_item(2).and_then(|i| i.extract::<usize>()),
                    tuple.get_item(3).and_then(|i| i.extract::<bool>()),
                ) {
                    (Ok(seq), Ok(node), Ok(depth), Ok(eom)) => Some(Ok((seq, node, depth, eom))),
                    _ => Some(Err(pyo3::exceptions::PyValueError::new_err(
                        "Failed to extract values from topo_order tuple",
                    )
                    .into())),
                }
            }
            Err(e) if e.is_instance_of::<PyStopIteration>(py) => None,
            Err(e) => Some(Err(e.into())),
        })
    }
}

impl Graph {
    /// Get the underlying Py<PyAny>.
    pub(crate) fn as_pyobject(&self) -> &Py<PyAny> {
        &self.0
    }

    /// Check if one node is an ancestor of another.
    ///
    /// # Arguments
    ///
    /// * `node1` - The potential ancestor node
    /// * `node2` - The potential descendant node
    ///
    /// # Returns
    ///
    /// `true` if `node1` is an ancestor of `node2`, `false` otherwise
    pub fn is_ancestor<T: GraphNode>(
        &self,
        node1: &T,
        node2: &T,
    ) -> Result<bool, crate::error::Error> {
        Python::attach(|py| {
            let result = self.0.call_method1(
                py,
                "is_ancestor",
                (node1.to_pyobject(py)?, node2.to_pyobject(py)?),
            )?;
            Ok(result.extract(py)?)
        })
    }

    /// Iterate through the left-hand ancestry of a node.
    ///
    /// # Arguments
    ///
    /// * `node` - The node to start from
    /// * `stop_nodes` - Optional list of nodes where iteration should stop
    ///
    /// # Returns
    ///
    /// An iterator that yields nodes in the ancestry chain
    pub fn iter_lefthand_ancestry<T: GraphNode>(
        &self,
        node: &T,
        stop_nodes: Option<&[T]>,
    ) -> Result<impl Iterator<Item = Result<T, crate::error::Error>>, crate::error::Error> {
        Python::attach(|py| {
            let stop_py = if let Some(nodes) = stop_nodes {
                let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
                Some(py_nodes?)
            } else {
                None
            };

            let iter = self.0.call_method1(
                py,
                "iter_lefthand_ancestry",
                (node.to_pyobject(py)?, stop_py),
            )?;
            Ok(NodeIter(iter, std::marker::PhantomData))
        })
    }

    /// Find the least common ancestor(s) of a set of nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - A list of nodes to find the LCA for
    ///
    /// # Returns
    ///
    /// A vector of nodes that are the least common ancestors
    pub fn find_lca<T: GraphNode>(&self, nodes: &[T]) -> Result<Vec<T>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self.0.call_method1(py, "find_lca", (py_nodes?,))?;
            let py_set = result
                .cast_bound::<pyo3::types::PySet>(py)
                .map_err(PyErr::from)?;
            let mut lca_nodes = Vec::new();
            for item in py_set {
                lca_nodes.push(T::from_pyobject(&item)?)
            }
            Ok(lca_nodes)
        })
    }

    /// Get the heads from a set of nodes.
    ///
    /// Heads are nodes that are not ancestors of any other node in the set.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to find heads from
    ///
    /// # Returns
    ///
    /// A vector of nodes that are heads
    pub fn heads<T: GraphNode>(&self, nodes: &[T]) -> Result<Vec<T>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self.0.call_method1(py, "heads", (py_nodes?,))?;
            let py_set = result
                .cast_bound::<pyo3::types::PySet>(py)
                .map_err(PyErr::from)?;
            let mut head_nodes = Vec::new();
            for item in py_set {
                head_nodes.push(T::from_pyobject(&item)?)
            }
            Ok(head_nodes)
        })
    }

    /// Find the unique ancestors of one set of nodes that are not ancestors of another set.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to check
    /// * `common_nodes` - List of common nodes to exclude
    ///
    /// # Returns
    ///
    /// A vector of nodes that are unique ancestors
    pub fn find_unique_ancestors<T: GraphNode>(
        &self,
        nodes: &[T],
        common_nodes: &[T],
    ) -> Result<Vec<T>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let py_common: Result<Vec<_>, _> =
                common_nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result =
                self.0
                    .call_method1(py, "find_unique_ancestors", (py_nodes?, py_common?))?;
            let py_list = result
                .cast_bound::<pyo3::types::PyList>(py)
                .map_err(PyErr::from)?;
            let mut unique_ancestors = Vec::new();
            for item in py_list {
                unique_ancestors.push(T::from_pyobject(&item)?)
            }
            Ok(unique_ancestors)
        })
    }

    /// Find the difference between two sets of nodes.
    ///
    /// # Arguments
    ///
    /// * `left_nodes` - The left set of nodes
    /// * `right_nodes` - The right set of nodes
    ///
    /// # Returns
    ///
    /// A tuple of (nodes only in left, nodes only in right)
    pub fn find_difference<T: GraphNode>(
        &self,
        left_nodes: &[T],
        right_nodes: &[T],
    ) -> Result<(Vec<T>, Vec<T>), crate::error::Error> {
        Python::attach(|py| {
            let py_left: Result<Vec<_>, _> = left_nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let py_right: Result<Vec<_>, _> =
                right_nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self
                .0
                .call_method1(py, "find_difference", (py_left?, py_right?))?;
            let tuple = result.cast_bound::<PyTuple>(py).map_err(PyErr::from)?;

            let left_only = tuple.get_item(0)?;
            let right_only = tuple.get_item(1)?;

            let mut left_result = Vec::new();
            for item in left_only
                .cast::<pyo3::types::PySet>()
                .map_err(PyErr::from)?
            {
                left_result.push(T::from_pyobject(&item)?);
            }

            let mut right_result = Vec::new();
            for item in right_only
                .cast::<pyo3::types::PySet>()
                .map_err(PyErr::from)?
            {
                right_result.push(T::from_pyobject(&item)?);
            }

            Ok((left_result, right_result))
        })
    }

    /// Iterate through ancestry of given nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to get ancestry for
    ///
    /// # Returns
    ///
    /// An iterator that yields nodes in the ancestry
    pub fn iter_ancestry<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<impl Iterator<Item = Result<T, crate::error::Error>>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let iter = self.0.call_method1(py, "iter_ancestry", (py_nodes?,))?;
            Ok(NodeIter(iter, std::marker::PhantomData))
        })
    }

    /// Get the parent map for a set of nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to get parents for
    ///
    /// # Returns
    ///
    /// A map from node to list of parent nodes
    pub fn get_parent_map<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<HashMap<T, Vec<T>>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self.0.call_method1(py, "get_parent_map", (py_nodes?,))?;
            let py_dict = result
                .cast_bound::<pyo3::types::PyDict>(py)
                .map_err(PyErr::from)?;

            let mut parent_map = HashMap::new();
            for (key, value) in py_dict {
                let key_node = T::from_pyobject(&key)?;

                let mut parents = Vec::new();
                for parent in value.cast::<pyo3::types::PyTuple>().map_err(PyErr::from)? {
                    parents.push(T::from_pyobject(&parent)?);
                }
                parent_map.insert(key_node, parents);
            }
            Ok(parent_map)
        })
    }

    /// Check if a node is between two other nodes.
    ///
    /// # Arguments
    ///
    /// * `candidate` - The node to check
    /// * `ancestor` - The potential ancestor
    /// * `descendant` - The potential descendant
    ///
    /// # Returns
    ///
    /// `true` if `candidate` is between `ancestor` and `descendant`
    pub fn is_between<T: GraphNode>(
        &self,
        candidate: &T,
        ancestor: &T,
        descendant: &T,
    ) -> Result<bool, crate::error::Error> {
        Python::attach(|py| {
            let result = self.0.call_method1(
                py,
                "is_between",
                (
                    candidate.to_pyobject(py)?,
                    ancestor.to_pyobject(py)?,
                    descendant.to_pyobject(py)?,
                ),
            )?;
            Ok(result.extract(py)?)
        })
    }

    /// Iterate through nodes in topological order.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to order
    ///
    /// # Returns
    ///
    /// An iterator that yields (sequence_number, node, depth, end_of_merge)
    pub fn iter_topo_order<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<
        impl Iterator<Item = Result<(usize, T, usize, bool), crate::error::Error>>,
        crate::error::Error,
    > {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let iter = self.0.call_method1(py, "iter_topo_order", (py_nodes?,))?;
            Ok(TopoOrderIter(iter, std::marker::PhantomData))
        })
    }

    /// Find all descendants of the given nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to find descendants for
    ///
    /// # Returns
    ///
    /// A vector of nodes that are descendants
    pub fn find_descendants<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<Vec<T>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self.0.call_method1(py, "find_descendants", (py_nodes?,))?;
            let py_set = result
                .cast_bound::<pyo3::types::PySet>(py)
                .map_err(PyErr::from)?;
            let mut descendants = Vec::new();
            for item in py_set {
                descendants.push(T::from_pyobject(&item)?);
            }
            Ok(descendants)
        })
    }

    /// Find the distance from nodes to null.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to find distance for
    ///
    /// # Returns
    ///
    /// A map from node to distance
    pub fn find_distance_to_null<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<HashMap<T, usize>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self
                .0
                .call_method1(py, "find_distance_to_null", (py_nodes?,))?;
            let py_dict = result
                .cast_bound::<pyo3::types::PyDict>(py)
                .map_err(PyErr::from)?;

            let mut distance_map = HashMap::new();
            for (key, value) in py_dict {
                let key_node = T::from_pyobject(&key)?;
                let distance: usize = value.extract()?;
                distance_map.insert(key_node, distance);
            }
            Ok(distance_map)
        })
    }

    /// Find the unique least common ancestor.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to find unique LCA for
    /// * `count` - The number of heads to look for (optional)
    ///
    /// # Returns
    ///
    /// The unique LCA node or None if there isn't a unique one
    pub fn find_unique_lca<T: GraphNode>(
        &self,
        nodes: &[T],
        count: Option<usize>,
    ) -> Result<Option<T>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = if let Some(c) = count {
                self.0.call_method1(py, "find_unique_lca", (py_nodes?, c))?
            } else {
                self.0.call_method1(py, "find_unique_lca", (py_nodes?,))?
            };

            if result.is_none(py) {
                Ok(None)
            } else {
                Ok(Some(T::from_pyobject(result.bind(py))?))
            }
        })
    }

    /// Find merge order for nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to find merge order for
    ///
    /// # Returns
    ///
    /// An ordered list of nodes
    pub fn find_merge_order<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<Vec<T>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self.0.call_method1(py, "find_merge_order", (py_nodes?,))?;
            let py_list = result
                .cast_bound::<pyo3::types::PyList>(py)
                .map_err(PyErr::from)?;
            let mut merge_order = Vec::new();
            for item in py_list {
                merge_order.push(T::from_pyobject(&item)?);
            }
            Ok(merge_order)
        })
    }

    /// Find the lefthand merger of a node.
    ///
    /// # Arguments
    ///
    /// * `node` - Node to find merger for
    /// * `tip` - Optional tip node
    ///
    /// # Returns
    ///
    /// The lefthand merger node
    pub fn find_lefthand_merger<T: GraphNode>(
        &self,
        node: &T,
        tip: Option<&T>,
    ) -> Result<Option<T>, crate::error::Error> {
        Python::attach(|py| {
            let args = if let Some(t) = tip {
                (node.to_pyobject(py)?, t.to_pyobject(py)?)
            } else {
                (node.to_pyobject(py)?, py.None().into_bound(py))
            };
            let result = self.0.call_method1(py, "find_lefthand_merger", args)?;

            if result.is_none(py) {
                Ok(None)
            } else {
                Ok(Some(T::from_pyobject(result.bind(py))?))
            }
        })
    }

    /// Find lefthand distances for nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to find distances for
    ///
    /// # Returns
    ///
    /// A map from node to distance
    pub fn find_lefthand_distances<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<HashMap<T, usize>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self
                .0
                .call_method1(py, "find_lefthand_distances", (py_nodes?,))?;
            let py_dict = result
                .cast_bound::<pyo3::types::PyDict>(py)
                .map_err(PyErr::from)?;

            let mut distance_map = HashMap::new();
            for (key, value) in py_dict {
                let key_node = T::from_pyobject(&key)?;
                let distance: usize = value.extract()?;
                distance_map.insert(key_node, distance);
            }
            Ok(distance_map)
        })
    }

    /// Get the child map for a set of nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - List of nodes to get children for
    ///
    /// # Returns
    ///
    /// A map from node to list of child nodes
    pub fn get_child_map<T: GraphNode>(
        &self,
        nodes: &[T],
    ) -> Result<HashMap<T, Vec<T>>, crate::error::Error> {
        Python::attach(|py| {
            let py_nodes: Result<Vec<_>, _> = nodes.iter().map(|n| n.to_pyobject(py)).collect();
            let result = self.0.call_method1(py, "get_child_map", (py_nodes?,))?;
            let py_dict = result
                .cast_bound::<pyo3::types::PyDict>(py)
                .map_err(PyErr::from)?;

            let mut child_map = HashMap::new();
            for (key, value) in py_dict {
                let key_node = T::from_pyobject(&key)?;

                let mut children = Vec::new();
                for child in value.cast::<pyo3::types::PyList>().map_err(PyErr::from)? {
                    children.push(T::from_pyobject(&child)?);
                }
                child_map.insert(key_node, children);
            }
            Ok(child_map)
        })
    }
}

/// A key identifying a specific version of a file
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Key(Vec<String>);

impl From<Vec<String>> for Key {
    fn from(v: Vec<String>) -> Self {
        Key(v)
    }
}

impl From<Key> for Vec<String> {
    fn from(k: Key) -> Self {
        k.0
    }
}

impl<'py> IntoPyObject<'py> for Key {
    type Target = PyTuple;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        PyTuple::new(py, self.0)
    }
}

impl<'a, 'py> FromPyObject<'a, 'py> for Key {
    type Error = PyErr;

    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
        let tuple = ob.cast::<PyTuple>()?;
        let mut items = Vec::new();
        for item in tuple.iter() {
            items.push(item.extract::<String>()?);
        }
        Ok(Key(items))
    }
}

/// Implement GraphNode for Key
impl GraphNode for Key {
    fn to_pyobject<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        Ok(PyTuple::new(py, &self.0)?.into_any())
    }

    fn from_pyobject(obj: &Bound<PyAny>) -> PyResult<Self> {
        obj.extract::<Key>()
    }
}

/// A known graph of file versions
pub struct KnownGraph(Py<PyAny>);

impl KnownGraph {
    /// Create a new KnownGraph from a Python object
    pub fn new(py_obj: Py<PyAny>) -> Self {
        Self(py_obj)
    }

    /// Get the heads of the given nodes
    pub fn heads<T: GraphNode>(&self, nodes: Vec<T>) -> Result<Vec<T>, crate::error::Error> {
        Python::attach(|py| {
            let nodes_py: Vec<_> = nodes
                .into_iter()
                .map(|n| n.to_pyobject(py))
                .collect::<Result<Vec<_>, _>>()?;
            let nodes_frozenset = PyFrozenSet::new(py, &nodes_py)?;

            let result = self.0.call_method1(py, "heads", (nodes_frozenset,))?;

            let mut heads = Vec::new();
            for head_py in result
                .cast_bound::<PyIterator>(py)
                .map_err(|_| pyo3::exceptions::PyTypeError::new_err("Expected iterator"))?
            {
                let head = T::from_pyobject(&head_py?)?;
                heads.push(head);
            }

            Ok(heads)
        })
    }
}

impl Clone for KnownGraph {
    fn clone(&self) -> Self {
        Python::attach(|py| KnownGraph(self.0.clone_ref(py)))
    }
}

#[cfg(test)]
mod tests;