breezyshim-0.1.78/CODE_OF_CONDUCT.md000064400000000000000000000064271046102023000147120ustar 00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at core@breezy-vcs.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq breezyshim-0.1.78/COPYING.txt000064400000000000000000000432541046102023000137630ustar 00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. breezyshim-0.1.78/Cargo.toml0000644000000027250000000000100113160ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "breezyshim" version = "0.1.78" authors = [ "Martin Packman ", "Jelmer Vernooij ", ] description = "Rust shim around the Breezy Python API" homepage = "https://www.breezy-vcs.org/" documentation = "https://www.breezy-vcs.org/doc/" readme = "README.md" license = "GPL-2.0+" repository = "https://code.launchpad.net/breezyshim" [dependencies.chrono] version = "0.4" [dependencies.debversion] version = "0.2" features = ["python-debian"] optional = true [dependencies.lazy_static] version = "1.4.0" [dependencies.pyo3] version = ">=0.20" features = ["serde"] [dependencies.pyo3-filelike] version = ">=0.1" [dependencies.serde] version = "1" features = ["derive"] [dependencies.tempfile] version = "3.6.0" [dependencies.url] version = "2" features = ["serde"] [dev-dependencies.pyo3] version = ">=0.20" features = ["auto-initialize"] [features] auto-initialize = ["pyo3/auto-initialize"] debian = ["dep:debversion"] default = ["debian"] breezyshim-0.1.78/Cargo.toml.orig000064400000000000000000000017121046102023000147720ustar 00000000000000[package] name = "breezyshim" version = "0.1.78" edition = "2021" license = "GPL-2.0+" description = "Rust shim around the Breezy Python API" homepage = "https://www.breezy-vcs.org/" repository = "https://code.launchpad.net/breezyshim" documentation = "https://www.breezy-vcs.org/doc/" authors = [ "Martin Packman ", "Jelmer Vernooij ",] [dependencies] pyo3-filelike = ">=0.1" tempfile = "3.6.0" lazy_static = "1.4.0" chrono = "0.4" [features] default = [ "debian",] debian = [ "dep:debversion",] auto-initialize = [ "pyo3/auto-initialize",] [dependencies.debversion] version = "0.2" optional = true features = [ "python-debian",] [dependencies.url] version = "2" features = [ "serde",] [dependencies.serde] version = "1" features = [ "derive",] [dependencies.pyo3] workspace = true features = [ "serde",] [workspace.dependencies] pyo3 = ">=0.20" [dev-dependencies.pyo3] workspace = true features = [ "auto-initialize",] breezyshim-0.1.78/README.md000064400000000000000000000005421046102023000133620ustar 00000000000000# Rust wrapper for Breezy This crate contains a rust wrapper for the Breezy API, which is written in Python. Breezy itself is being ported to Rust, but until that port has completed, this crate allows access to the most important Breezy APIs via Rust. The Rust API here will follow the Breezy 4.0 Rust API as much as possible, to make porting easier. breezyshim-0.1.78/disperse.conf000064400000000000000000000001171046102023000145660ustar 00000000000000# See https://github.com/jelmer/disperse timeout_days: 5 tag_name: "v$VERSION" breezyshim-0.1.78/src/bazaar/mod.rs000064400000000000000000000022631046102023000152610ustar 00000000000000use pyo3::prelude::*; pub mod tree; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FileId(Vec); impl FileId { pub fn new() -> Self { Self(vec![]) } } impl From<&str> for FileId { fn from(s: &str) -> Self { Self(s.as_bytes().to_vec()) } } impl From for FileId { fn from(s: String) -> Self { Self(s.into_bytes()) } } impl From<&[u8]> for FileId { fn from(s: &[u8]) -> Self { Self(s.to_vec()) } } impl From> for FileId { fn from(s: Vec) -> Self { Self(s) } } impl From for Vec { fn from(s: FileId) -> Self { s.0 } } impl From for String { fn from(s: FileId) -> Self { String::from_utf8(s.0).unwrap() } } impl pyo3::ToPyObject for FileId { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl pyo3::FromPyObject<'_> for FileId { fn extract(ob: &PyAny) -> PyResult { let bytes = ob.extract::>()?; Ok(Self(bytes)) } } impl pyo3::IntoPy for FileId { fn into_py(self, py: Python) -> pyo3::PyObject { self.0.to_object(py) } } breezyshim-0.1.78/src/bazaar/tree.rs000064400000000000000000000007371046102023000154450ustar 00000000000000use crate::tree::{Error, MutableTree, Path}; use pyo3::prelude::*; pub trait MutableInventoryTree: MutableTree { fn add(&self, paths: &[&Path], file_ids: &[crate::bazaar::FileId]) -> Result<(), Error> { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "add", (paths.to_vec(), file_ids.to_vec())) }) .map_err(|e| e.into()) .map(|_| ()) } } impl MutableInventoryTree for crate::tree::WorkingTree {} breezyshim-0.1.78/src/branch.rs000064400000000000000000000225661046102023000145070ustar 00000000000000use crate::controldir::ControlDir; use crate::lock::Lock; use crate::repository::Repository; use crate::revisionid::RevisionId; use pyo3::import_exception; use pyo3::prelude::*; use pyo3::types::PyDict; import_exception!(breezy.errors, NotBranchError); import_exception!(breezy.errors, DependencyNotPresent); import_exception!(breezy.controldir, NoColocatedBranchSupport); #[derive(Debug)] pub enum BranchOpenError { NotBranchError(String), NoColocatedBranchSupport, DependencyNotPresent(String, String), Other(PyErr), } impl From for BranchOpenError { fn from(err: PyErr) -> Self { Python::with_gil(|py| { if err.is_instance_of::(py) { let l = err .value(py) .getattr("path") .unwrap() .extract::() .unwrap(); BranchOpenError::NotBranchError(l) } else if err.is_instance_of::(py) { BranchOpenError::NoColocatedBranchSupport } else if err.is_instance_of::(py) { let l = err .value(py) .getattr("library") .unwrap() .extract::() .unwrap(); let e = err .value(py) .getattr("error") .unwrap() .extract::() .unwrap(); BranchOpenError::DependencyNotPresent(l, e) } else { BranchOpenError::Other(err) } }) } } impl From for PyErr { fn from(err: BranchOpenError) -> Self { match err { BranchOpenError::NotBranchError(l) => NotBranchError::new_err((l,)), BranchOpenError::DependencyNotPresent(d, e) => DependencyNotPresent::new_err((d, e)), BranchOpenError::NoColocatedBranchSupport => { NoColocatedBranchSupport::new_err("NoColocatedBranchSupport") } BranchOpenError::Other(err) => err, } } } impl std::fmt::Display for BranchOpenError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { BranchOpenError::NotBranchError(p) => write!(f, "NotBranchError: {}", p), BranchOpenError::DependencyNotPresent(d, e) => { write!(f, "DependencyNotPresent({}, {})", d, e) } BranchOpenError::NoColocatedBranchSupport => write!(f, "NoColocatedBranchSupport"), BranchOpenError::Other(err) => write!(f, "Other({})", err), } } } impl std::error::Error for BranchOpenError {} #[derive(Clone)] pub struct BranchFormat(PyObject); impl BranchFormat { pub fn supports_stacking(&self) -> bool { Python::with_gil(|py| { self.0 .call_method0(py, "supports_stacking") .unwrap() .extract(py) .unwrap() }) } } pub trait Branch: ToPyObject + Send { fn format(&self) -> BranchFormat { Python::with_gil(|py| BranchFormat(self.to_object(py).getattr(py, "_format").unwrap())) } fn lock_read(&self) -> PyResult { Python::with_gil(|py| { Ok(Lock::from( self.to_object(py).call_method0(py, "lock_read")?, )) }) } fn tags(&self) -> PyResult { Python::with_gil(|py| { Ok(crate::tags::Tags::from( self.to_object(py).getattr(py, "tags")?, )) }) } fn repository(&self) -> Repository { Python::with_gil(|py| { Repository::new(self.to_object(py).getattr(py, "repository").unwrap()) }) } fn last_revision(&self) -> RevisionId { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "last_revision") .unwrap() .extract(py) .unwrap() }) } fn name(&self) -> Option { Python::with_gil(|py| { self.to_object(py) .getattr(py, "name") .unwrap() .extract::>(py) .unwrap() }) } fn basis_tree(&self) -> PyResult { Python::with_gil(|py| { Ok(crate::tree::RevisionTree( self.to_object(py).call_method0(py, "basis_tree")?, )) }) } fn get_user_url(&self) -> url::Url { Python::with_gil(|py| { let url = self .to_object(py) .getattr(py, "user_url") .unwrap() .extract::(py) .unwrap(); url.parse::().unwrap() }) } fn controldir(&self) -> ControlDir { Python::with_gil(|py| { ControlDir::new(self.to_object(py).getattr(py, "controldir").unwrap()) }) } fn push( &self, remote_branch: &dyn Branch, overwrite: bool, stop_revision: Option<&RevisionId>, tag_selector: Option bool>>, ) -> PyResult<()> { Python::with_gil(|py| { let kwargs = PyDict::new(py); kwargs.set_item("overwrite", overwrite)?; if let Some(stop_revision) = stop_revision { kwargs.set_item("stop_revision", stop_revision)?; } if let Some(tag_selector) = tag_selector { kwargs.set_item("tag_selector", py_tag_selector(py, tag_selector)?)?; } self.to_object(py).call_method( py, "push", (&remote_branch.to_object(py),), Some(kwargs), )?; Ok(()) }) } fn pull(&self, source_branch: &dyn Branch) -> PyResult<()> { Python::with_gil(|py| { self.to_object(py) .call_method(py, "pull", (&source_branch.to_object(py),), None)?; Ok(()) }) } fn get_public_branch(&self) -> Option { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "get_public_branch") .unwrap() .extract(py) .unwrap() }) } fn get_push_location(&self) -> Option { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "get_push_location") .unwrap() .extract(py) .unwrap() }) } fn get_submit_branch(&self) -> Option { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "get_submit_branch") .unwrap() .extract(py) .unwrap() }) } fn user_transport(&self) -> crate::transport::Transport { Python::with_gil(|py| { crate::transport::Transport::new( self.to_object(py).getattr(py, "user_transport").unwrap(), ) }) } } #[derive(Clone)] pub struct RegularBranch(PyObject); impl Branch for RegularBranch {} impl ToPyObject for RegularBranch { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl RegularBranch { pub fn new(obj: PyObject) -> Self { RegularBranch(obj) } } impl FromPyObject<'_> for RegularBranch { fn extract(ob: &PyAny) -> PyResult { Ok(RegularBranch(ob.to_object(ob.py()))) } } #[derive(Clone)] pub struct MemoryBranch(PyObject); impl ToPyObject for MemoryBranch { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Branch for MemoryBranch {} impl MemoryBranch { pub fn new(repository: &Repository, revno: Option, revid: &RevisionId) -> PyResult { Python::with_gil(|py| { let mb_cls = py.import("breezy.memorybranch")?.getattr("MemoryBranch")?; let o = mb_cls.call1((repository.to_object(py), (revno, revid.clone())))?; Ok(MemoryBranch(o.to_object(py))) }) } } pub(crate) fn py_tag_selector( py: Python, tag_selector: Box bool>, ) -> PyResult { #[pyclass(unsendable)] struct PyTagSelector(Box bool>); #[pymethods] impl PyTagSelector { fn __call__(&self, tag: String) -> bool { (self.0)(tag) } } Ok(PyTagSelector(tag_selector).into_py(py)) } pub fn open(url: &url::Url) -> Result, BranchOpenError> { Python::with_gil(|py| { let m = py.import("breezy.branch").unwrap(); let c = m.getattr("Branch").unwrap(); let r = c.call_method1("open", (url.to_string(),))?; Ok(Box::new(RegularBranch(r.to_object(py))) as Box) }) } pub fn open_containing(url: &url::Url) -> Result<(Box, String), BranchOpenError> { Python::with_gil(|py| { let m = py.import("breezy.branch").unwrap(); let c = m.getattr("Branch").unwrap(); let (b, p): (&PyAny, String) = c .call_method1("open_containing", (url.to_string(),))? .extract()?; Ok(( Box::new(RegularBranch(b.to_object(py))) as Box, p, )) }) } breezyshim-0.1.78/src/controldir.rs000064400000000000000000000363411046102023000154250ustar 00000000000000use crate::branch::{py_tag_selector, Branch, BranchOpenError, RegularBranch}; use crate::transport::Transport; use crate::tree::WorkingTree; use crate::location::AsLocation; use pyo3::prelude::*; use pyo3::types::PyDict; pub struct Prober(PyObject); impl ToPyObject for Prober { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for Prober { fn extract(obj: &PyAny) -> PyResult { Ok(Prober(obj.to_object(obj.py()))) } } impl Prober { pub fn new(obj: PyObject) -> Self { Prober(obj) } } pub struct ControlDir(PyObject); impl ToPyObject for ControlDir { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for ControlDir { fn extract(obj: &PyAny) -> PyResult { Ok(ControlDir(obj.to_object(obj.py()))) } } impl ControlDir { pub fn new(obj: PyObject) -> Self { Self(obj) } pub fn get_format(&self) -> ControlDirFormat { Python::with_gil(|py| { let result = self.to_object(py).getattr(py, "_format")?; Ok::<_, PyErr>(ControlDirFormat(result)) }) .unwrap() } #[deprecated] pub fn create_branch_convenience(base: &url::Url) -> Result, CreateError> { create_branch_convenience(base) } #[deprecated] pub fn create_standalone_workingtree( base: &std::path::Path, format: impl AsFormat, ) -> Result { create_standalone_workingtree(base, format) } pub fn cloning_metadir(&self) -> ControlDirFormat { Python::with_gil(|py| { let result = self.to_object(py).call_method0(py, "cloning_metadir")?; Ok::<_, PyErr>(ControlDirFormat(result)) }) .unwrap() } #[deprecated] pub fn open_tree_or_branch( location: &url::Url, name: Option<&str>, ) -> Result<(Option, Box), BranchOpenError> { open_tree_or_branch(location, name, None) } #[deprecated] pub fn open(url: &url::Url) -> Result { open(url, None) } #[deprecated] pub fn open_containing_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result<(ControlDir, String), OpenError> { open_containing_from_transport(transport, probers) } #[deprecated] pub fn open_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result { open_from_transport(transport, probers) } pub fn create_branch(&self, name: Option<&str>) -> Result, CreateError> { Python::with_gil(|py| { let branch = self .to_object(py) .call_method(py, "create_branch", (name,), None)? .extract(py)?; Ok(Box::new(RegularBranch::new(branch)) as Box) }) } pub fn open_branch( &self, branch_name: Option<&str>, ) -> Result, BranchOpenError> { Python::with_gil(|py| { let branch = self .to_object(py) .call_method(py, "open_branch", (branch_name,), None)? .extract(py)?; Ok(Box::new(RegularBranch::new(branch)) as Box) }) } pub fn push_branch( &self, source_branch: &dyn Branch, to_branch_name: Option<&str>, stop_revision: Option<&crate::RevisionId>, overwrite: Option, tag_selector: Option bool>>, ) -> PyResult> { Python::with_gil(|py| { let kwargs = PyDict::new(py); if let Some(to_branch_name) = to_branch_name { kwargs.set_item("name", to_branch_name)?; } if let Some(tag_selector) = tag_selector { kwargs.set_item("tag_selector", py_tag_selector(py, tag_selector)?)?; } if let Some(overwrite) = overwrite { kwargs.set_item("overwrite", overwrite)?; } if let Some(stop_revision) = stop_revision { kwargs.set_item("stop_revision", stop_revision.to_object(py))?; } let result = self.to_object(py).call_method( py, "push_branch", (&source_branch.to_object(py),), Some(kwargs), )?; Ok( Box::new(RegularBranch::new(result.getattr(py, "target_branch")?)) as Box, ) }) } pub fn sprout( &self, target: url::Url, source_branch: Option<&dyn Branch>, create_tree_if_local: Option, stacked: Option, ) -> ControlDir { Python::with_gil(|py| { let kwargs = PyDict::new(py); if let Some(create_tree_if_local) = create_tree_if_local { kwargs .set_item("create_tree_if_local", create_tree_if_local) .unwrap(); } if let Some(stacked) = stacked { kwargs.set_item("stacked", stacked).unwrap(); } if let Some(source_branch) = source_branch { kwargs .set_item("source_branch", &source_branch.to_object(py)) .unwrap(); } let cd = self .0 .call_method(py, "sprout", (target.to_string(),), Some(kwargs)) .unwrap(); ControlDir(cd) }) } pub fn open_workingtree(&self) -> PyResult { Python::with_gil(|py| { let wt = self.0.call_method0(py, "open_workingtree")?.extract(py)?; Ok(WorkingTree(wt)) }) } pub fn branch_names(&self) -> PyResult> { Python::with_gil(|py| { let names = self .0 .call_method0(py, "branch_names")? .extract::>(py)?; Ok(names) }) } } pub struct ControlDirFormat(PyObject); impl Clone for ControlDirFormat { fn clone(&self) -> Self { Python::with_gil(|py| ControlDirFormat(self.0.clone_ref(py))) } } impl From for ControlDirFormat { fn from(obj: PyObject) -> Self { ControlDirFormat(obj) } } impl Default for ControlDirFormat { fn default() -> Self { Python::with_gil(|py| { let breezy = PyModule::import(py, "breezy.controldir").unwrap(); let cd_format = breezy.getattr("ControlDirFormat").unwrap(); let obj = cd_format.call_method0("get_default_format").unwrap(); assert!(!obj.is_none()); ControlDirFormat(obj.into()) }) } } impl ControlDirFormat { pub fn get_format_string(&self) -> Vec { Python::with_gil(|py| { self.0 .call_method0(py, "get_format_string") .unwrap() .extract(py) .unwrap() }) } pub fn get_format_description(&self) -> String { Python::with_gil(|py| { self.0 .call_method0(py, "get_format_description") .unwrap() .extract(py) .unwrap() }) } pub fn is_control_filename(&self, filename: &str) -> bool { Python::with_gil(|py| { self.0 .call_method1(py, "is_control_filename", (filename,)) .unwrap() .extract(py) .unwrap() }) } } #[derive(Debug)] pub enum OpenError { Python(PyErr), NotFound(String), UnknownFormat, } impl From for OpenError { fn from(err: PyErr) -> Self { pyo3::import_exception!(breezy.errors, NotBranchError); pyo3::import_exception!(breezy.errors, UnknownFormatError); pyo3::Python::with_gil(|py| { if err.is_instance_of::(py) { OpenError::NotFound(err.value(py).getattr("value").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { OpenError::UnknownFormat } else { OpenError::Python(err) } }) } } impl std::fmt::Display for OpenError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { OpenError::Python(err) => err.fmt(f), OpenError::NotFound(name) => write!(f, "Not found: {}", name), OpenError::UnknownFormat => write!(f, "Unknown format"), } } } impl std::error::Error for OpenError {} #[derive(Debug)] pub enum CreateError { Python(PyErr), AlreadyExists, UnknownFormat, } impl From for CreateError { fn from(err: PyErr) -> Self { pyo3::import_exception!(breezy.errors, AlreadyControlDirError); pyo3::import_exception!(breezy.errors, UnknownFormatError); pyo3::Python::with_gil(|py| { if err.is_instance_of::(py) { CreateError::AlreadyExists } else if err.is_instance_of::(py) { CreateError::UnknownFormat } else { CreateError::Python(err) } }) } } impl std::fmt::Display for CreateError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { CreateError::Python(err) => err.fmt(f), CreateError::AlreadyExists => write!(f, "Already exists"), CreateError::UnknownFormat => write!(f, "Unknown format"), } } } impl std::error::Error for CreateError {} pub fn open_tree_or_branch( location: impl AsLocation, name: Option<&str>, possible_transports: Option<&mut Vec>, ) -> Result<(Option, Box), BranchOpenError> { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(possible_transports) = possible_transports { kwargs.set_item("possible_transports", possible_transports.to_object(py))?; } let ret = cd.to_object(py).call_method( py, "open_tree_or_branch", (location.as_location(), name), Some(kwargs), )?; let (tree, branch) = ret.extract::<(Option, PyObject)>(py)?; let branch = Box::new(RegularBranch::new(branch)) as Box; let tree = tree.map(WorkingTree); Ok((tree, branch)) }) } pub fn open( url: impl AsLocation, possible_transports: Option<&mut Vec>, ) -> Result { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(possible_transports) = possible_transports { kwargs.set_item("possible_transports", possible_transports.to_object(py))?; } let controldir = cd.call_method("open", (url.as_location(),), Some(kwargs))?; Ok(ControlDir(controldir.to_object(py))) }) } pub fn create( url: impl AsLocation, format: impl AsFormat, possible_transports: Option<&mut Vec>, ) -> Result { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); kwargs.set_item("format", format.to_object(py))?; if let Some(possible_transports) = possible_transports { kwargs.set_item("possible_transports", possible_transports.to_object(py))?; } let controldir = cd.call_method("create", (url.as_location(),), Some(kwargs))?; Ok(ControlDir(controldir.to_object(py))) }) } pub fn create_on_transport( transport: &Transport, format: impl AsFormat, ) -> Result { Python::with_gil(|py| { let format = format.as_format().unwrap().0; Ok(ControlDir(format.call_method( py, "initialize_on_transport", (&transport.to_object(py),), None, )?)) }) } pub fn open_containing_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result<(ControlDir, String), OpenError> { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(probers) = probers { kwargs.set_item("probers", probers.iter().map(|p| &p.0).collect::>())?; } let (controldir, subpath): (PyObject, String) = cd .call_method( "open_containing_from_transport", (&transport.to_object(py),), Some(kwargs), )? .extract()?; Ok((ControlDir(controldir.to_object(py)), subpath)) }) } pub fn open_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(probers) = probers { kwargs.set_item("probers", probers.iter().map(|p| &p.0).collect::>())?; } let controldir = cd.call_method( "open_from_transport", (&transport.to_object(py),), Some(kwargs), )?; Ok(ControlDir(controldir.to_object(py))) }) } pub trait AsFormat: ToPyObject { fn as_format(&self) -> Option; } impl AsFormat for &str { fn as_format(&self) -> Option { Python::with_gil(|py| { let m = py.import("breezy.controldir").ok()?; let cd = m.getattr("ControlDirFormat").ok()?; let format = cd.call_method1("get", (self.to_object(py),)).ok()?; Some(ControlDirFormat(format.to_object(py))) }) } } impl ToPyObject for &ControlDirFormat { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl AsFormat for &ControlDirFormat { fn as_format(&self) -> Option { Some(ControlDirFormat(self.0.clone())) } } pub fn create_branch_convenience(base: &url::Url) -> Result, CreateError> { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let branch = cd.call_method("create_branch_convenience", (base.to_string(),), None)?; Ok(Box::new(RegularBranch::new(branch.to_object(py))) as Box) }) } pub fn create_standalone_workingtree( base: &std::path::Path, format: impl AsFormat, ) -> Result { let base = base.to_str().unwrap(); Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let format = format.to_object(py); let wt = cd.call_method("create_standalone_workingtree", (base, format), None)?; Ok(WorkingTree(wt.to_object(py))) }) } breezyshim-0.1.78/src/controldir.rs.~1~000064400000000000000000000363341046102023000161620ustar 00000000000000use crate::branch::{py_tag_selector, Branch, BranchOpenError, RegularBranch}; use crate::transport::Transport; use crate::tree::WorkingTree; use crate::location::AsLocation; use pyo3::prelude::*; use pyo3::types::PyDict; pub struct Prober(PyObject); impl ToPyObject for Prober { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for Prober { fn extract(obj: &PyAny) -> PyResult { Ok(Prober(obj.to_object(obj.py()))) } } impl Prober { pub fn new(obj: PyObject) -> Self { Prober(obj) } } pub struct ControlDir(PyObject); impl ToPyObject for ControlDir { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for ControlDir { fn extract(obj: &PyAny) -> PyResult { Ok(ControlDir(obj.to_object(obj.py()))) } } impl ControlDir { pub fn new(obj: PyObject) -> Self { Self(obj) } pub fn get_format(&self) -> ControlDirFormat { Python::with_gil(|py| { let result = self.to_object(py).getattr(py, "_format")?; Ok::<_, PyErr>(ControlDirFormat(result)) }) .unwrap() } #[deprecated] pub fn create_branch_convenience(base: &url::Url) -> Result, CreateError> { create_branch_convenience(base) } #[deprecated] pub fn create_standalone_workingtree( base: &std::path::Path, format: impl AsFormat, ) -> Result { create_standalone_workingtree(base, format) } pub fn cloning_metadir(&self) -> ControlDirFormat { Python::with_gil(|py| { let result = self.to_object(py).call_method0(py, "cloning_metadir")?; Ok::<_, PyErr>(ControlDirFormat(result)) }) .unwrap() } #[deprecated] pub fn open_tree_or_branch( location: &url::Url, name: Option<&str>, ) -> Result<(Option, Box), BranchOpenError> { open_tree_or_branch(location, name, None) } #[deprecated] pub fn open(url: &url::Url) -> Result { open(url, None) } #[deprecated] pub fn open_containing_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result<(ControlDir, String), OpenError> { open_containing_from_transport(transport, probers) } #[deprecated] pub fn open_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result { open_from_transport(transport, probers) } pub fn create_branch(&self, name: Option<&str>) -> Result, CreateError> { Python::with_gil(|py| { let branch = self .to_object(py) .call_method(py, "create_branch", (name,), None)? .extract(py)?; Ok(Box::new(RegularBranch::new(branch)) as Box) }) } pub fn open_branch( &self, branch_name: Option<&str>, ) -> Result, BranchOpenError> { Python::with_gil(|py| { let branch = self .to_object(py) .call_method(py, "open_branch", (branch_name,), None)? .extract(py)?; Ok(Box::new(RegularBranch::new(branch)) as Box) }) } pub fn push_branch( &self, source_branch: &dyn Branch, to_branch_name: Option<&str>, stop_revision: Option<&crate::RevisionId>, overwrite: Option, tag_selector: Option bool>, ) -> PyResult> { Python::with_gil(|py| { let kwargs = PyDict::new(py); if let Some(to_branch_name) = to_branch_name { kwargs.set_item("name", to_branch_name)?; } if let Some(tag_selector) = tag_selector { kwargs.set_item("tag_selector", py_tag_selector(py, tag_selector)?)?; } if let Some(overwrite) = overwrite { kwargs.set_item("overwrite", overwrite)?; } if let Some(stop_revision) = stop_revision { kwargs.set_item("stop_revision", stop_revision.to_object(py))?; } let result = self.to_object(py).call_method( py, "push_branch", (&source_branch.to_object(py),), Some(kwargs), )?; Ok( Box::new(RegularBranch::new(result.getattr(py, "target_branch")?)) as Box, ) }) } pub fn sprout( &self, target: url::Url, source_branch: Option<&dyn Branch>, create_tree_if_local: Option, stacked: Option, ) -> ControlDir { Python::with_gil(|py| { let kwargs = PyDict::new(py); if let Some(create_tree_if_local) = create_tree_if_local { kwargs .set_item("create_tree_if_local", create_tree_if_local) .unwrap(); } if let Some(stacked) = stacked { kwargs.set_item("stacked", stacked).unwrap(); } if let Some(source_branch) = source_branch { kwargs .set_item("source_branch", &source_branch.to_object(py)) .unwrap(); } let cd = self .0 .call_method(py, "sprout", (target.to_string(),), Some(kwargs)) .unwrap(); ControlDir(cd) }) } pub fn open_workingtree(&self) -> PyResult { Python::with_gil(|py| { let wt = self.0.call_method0(py, "open_workingtree")?.extract(py)?; Ok(WorkingTree(wt)) }) } pub fn branch_names(&self) -> PyResult> { Python::with_gil(|py| { let names = self .0 .call_method0(py, "branch_names")? .extract::>(py)?; Ok(names) }) } } pub struct ControlDirFormat(PyObject); impl Clone for ControlDirFormat { fn clone(&self) -> Self { Python::with_gil(|py| ControlDirFormat(self.0.clone_ref(py))) } } impl From for ControlDirFormat { fn from(obj: PyObject) -> Self { ControlDirFormat(obj) } } impl Default for ControlDirFormat { fn default() -> Self { Python::with_gil(|py| { let breezy = PyModule::import(py, "breezy.controldir").unwrap(); let cd_format = breezy.getattr("ControlDirFormat").unwrap(); let obj = cd_format.call_method0("get_default_format").unwrap(); assert!(!obj.is_none()); ControlDirFormat(obj.into()) }) } } impl ControlDirFormat { pub fn get_format_string(&self) -> Vec { Python::with_gil(|py| { self.0 .call_method0(py, "get_format_string") .unwrap() .extract(py) .unwrap() }) } pub fn get_format_description(&self) -> String { Python::with_gil(|py| { self.0 .call_method0(py, "get_format_description") .unwrap() .extract(py) .unwrap() }) } pub fn is_control_filename(&self, filename: &str) -> bool { Python::with_gil(|py| { self.0 .call_method1(py, "is_control_filename", (filename,)) .unwrap() .extract(py) .unwrap() }) } } #[derive(Debug)] pub enum OpenError { Python(PyErr), NotFound(String), UnknownFormat, } impl From for OpenError { fn from(err: PyErr) -> Self { pyo3::import_exception!(breezy.errors, NotBranchError); pyo3::import_exception!(breezy.errors, UnknownFormatError); pyo3::Python::with_gil(|py| { if err.is_instance_of::(py) { OpenError::NotFound(err.value(py).getattr("value").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { OpenError::UnknownFormat } else { OpenError::Python(err) } }) } } impl std::fmt::Display for OpenError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { OpenError::Python(err) => err.fmt(f), OpenError::NotFound(name) => write!(f, "Not found: {}", name), OpenError::UnknownFormat => write!(f, "Unknown format"), } } } impl std::error::Error for OpenError {} #[derive(Debug)] pub enum CreateError { Python(PyErr), AlreadyExists, UnknownFormat, } impl From for CreateError { fn from(err: PyErr) -> Self { pyo3::import_exception!(breezy.errors, AlreadyControlDirError); pyo3::import_exception!(breezy.errors, UnknownFormatError); pyo3::Python::with_gil(|py| { if err.is_instance_of::(py) { CreateError::AlreadyExists } else if err.is_instance_of::(py) { CreateError::UnknownFormat } else { CreateError::Python(err) } }) } } impl std::fmt::Display for CreateError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { CreateError::Python(err) => err.fmt(f), CreateError::AlreadyExists => write!(f, "Already exists"), CreateError::UnknownFormat => write!(f, "Unknown format"), } } } impl std::error::Error for CreateError {} pub fn open_tree_or_branch( location: impl AsLocation, name: Option<&str>, possible_transports: Option<&mut Vec>, ) -> Result<(Option, Box), BranchOpenError> { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(possible_transports) = possible_transports { kwargs.set_item("possible_transports", possible_transports.to_object(py))?; } let ret = cd.to_object(py).call_method( py, "open_tree_or_branch", (location.as_location(), name), Some(kwargs), )?; let (tree, branch) = ret.extract::<(Option, PyObject)>(py)?; let branch = Box::new(RegularBranch::new(branch)) as Box; let tree = tree.map(WorkingTree); Ok((tree, branch)) }) } pub fn open( url: impl AsLocation, possible_transports: Option<&mut Vec>, ) -> Result { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(possible_transports) = possible_transports { kwargs.set_item("possible_transports", possible_transports.to_object(py))?; } let controldir = cd.call_method("open", (url.as_location(),), Some(kwargs))?; Ok(ControlDir(controldir.to_object(py))) }) } pub fn create( url: impl AsLocation, format: impl AsFormat, possible_transports: Option<&mut Vec>, ) -> Result { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); kwargs.set_item("format", format.to_object(py))?; if let Some(possible_transports) = possible_transports { kwargs.set_item("possible_transports", possible_transports.to_object(py))?; } let controldir = cd.call_method("create", (url.as_location(),), Some(kwargs))?; Ok(ControlDir(controldir.to_object(py))) }) } pub fn create_on_transport( transport: &Transport, format: impl AsFormat, ) -> Result { Python::with_gil(|py| { let format = format.as_format().unwrap().0; Ok(ControlDir(format.call_method( py, "initialize_on_transport", (&transport.to_object(py),), None, )?)) }) } pub fn open_containing_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result<(ControlDir, String), OpenError> { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(probers) = probers { kwargs.set_item("probers", probers.iter().map(|p| &p.0).collect::>())?; } let (controldir, subpath): (PyObject, String) = cd .call_method( "open_containing_from_transport", (&transport.to_object(py),), Some(kwargs), )? .extract()?; Ok((ControlDir(controldir.to_object(py)), subpath)) }) } pub fn open_from_transport( transport: &Transport, probers: Option<&[Prober]>, ) -> Result { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new(py); if let Some(probers) = probers { kwargs.set_item("probers", probers.iter().map(|p| &p.0).collect::>())?; } let controldir = cd.call_method( "open_from_transport", (&transport.to_object(py),), Some(kwargs), )?; Ok(ControlDir(controldir.to_object(py))) }) } pub trait AsFormat: ToPyObject { fn as_format(&self) -> Option; } impl AsFormat for &str { fn as_format(&self) -> Option { Python::with_gil(|py| { let m = py.import("breezy.controldir").ok()?; let cd = m.getattr("ControlDirFormat").ok()?; let format = cd.call_method1("get", (self.to_object(py),)).ok()?; Some(ControlDirFormat(format.to_object(py))) }) } } impl ToPyObject for &ControlDirFormat { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl AsFormat for &ControlDirFormat { fn as_format(&self) -> Option { Some(ControlDirFormat(self.0.clone())) } } pub fn create_branch_convenience(base: &url::Url) -> Result, CreateError> { Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let branch = cd.call_method("create_branch_convenience", (base.to_string(),), None)?; Ok(Box::new(RegularBranch::new(branch.to_object(py))) as Box) }) } pub fn create_standalone_workingtree( base: &std::path::Path, format: impl AsFormat, ) -> Result { let base = base.to_str().unwrap(); Python::with_gil(|py| { let m = py.import("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let format = format.to_object(py); let wt = cd.call_method("create_standalone_workingtree", (base, format), None)?; Ok(WorkingTree(wt.to_object(py))) }) } breezyshim-0.1.78/src/debian/mod.rs000064400000000000000000000000301046102023000152310ustar 00000000000000pub mod vcs_up_to_date; breezyshim-0.1.78/src/debian/vcs_up_to_date.rs000064400000000000000000000046731046102023000174710ustar 00000000000000use crate::tree::Tree; use debversion::Version; use pyo3::prelude::*; #[derive(PartialEq, Eq)] pub enum UpToDateStatus { UpToDate, MissingChangelog, PackageMissingInArchive { package: String, }, TreeVersionNotInArchive { tree_version: Version, archive_versions: Vec, }, NewArchiveVersion { archive_version: Version, tree_version: Version, }, } pub struct Apt(pub PyObject); pub fn check_up_to_date( tree: &dyn Tree, subpath: &std::path::Path, apt: &Apt, ) -> PyResult { use pyo3::import_exception; import_exception!(breezy.plugins.debian.vcs_up_to_date, MissingChangelogError); import_exception!( breezy.plugins.debian.vcs_up_to_date, PackageMissingInArchive ); import_exception!( breezy.plugins.debian.vcs_up_to_date, TreeVersionNotInArchive ); import_exception!(breezy.plugins.debian.vcs_up_to_date, NewArchiveVersion); Python::with_gil(|py| { let m = py.import("breezy.plugins.debian.vcs_up_to_date")?; let check_up_to_date = m.getattr("check_up_to_date")?; match check_up_to_date.call1((tree.to_object(py), subpath.to_path_buf(), &apt.0)) { Err(e) if e.is_instance_of::(py) => { Ok(UpToDateStatus::MissingChangelog) } Err(e) if e.is_instance_of::(py) => { Ok(UpToDateStatus::PackageMissingInArchive { package: e.value(py).getattr("package")?.extract()?, }) } Err(e) if e.is_instance_of::(py) => { Ok(UpToDateStatus::TreeVersionNotInArchive { tree_version: e.value(py).getattr("tree_version")?.extract()?, archive_versions: e .value(py) .getattr("archive_versions")? .extract::>()?, }) } Err(e) if e.is_instance_of::(py) => { Ok(UpToDateStatus::NewArchiveVersion { archive_version: e.value(py).getattr("archive_version")?.extract()?, tree_version: e.value(py).getattr("tree_version")?.extract()?, }) } Ok(_o) => Ok(UpToDateStatus::UpToDate), Err(e) => Err(e), } }) } breezyshim-0.1.78/src/delta.rs000064400000000000000000000044621046102023000143360ustar 00000000000000use crate::tree::TreeChange; use pyo3::prelude::*; /// Describes changes from one tree to another. /// /// Contains seven lists with TreeChange objects. /// /// added /// removed /// renamed /// copied /// kind_changed /// modified /// unchanged /// unversioned /// /// Each id is listed only once. /// /// Files that are both modified and renamed or copied are listed only in /// renamed or copied, with the text_modified flag true. The text_modified /// applies either to the content of the file or the target of the /// symbolic link, depending of the kind of file. /// /// Files are only considered renamed if their name has changed or /// their parent directory has changed. Renaming a directory /// does not count as renaming all its contents. /// /// The lists are normally sorted when the delta is created. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TreeDelta { pub added: Vec, pub removed: Vec, pub renamed: Vec, pub copied: Vec, pub kind_changed: Vec, pub modified: Vec, pub unchanged: Vec, pub unversioned: Vec, pub missing: Vec, } impl TreeDelta { pub fn has_changed(&self) -> bool { !self.added.is_empty() || !self.removed.is_empty() || !self.renamed.is_empty() || !self.copied.is_empty() || !self.kind_changed.is_empty() || !self.modified.is_empty() } } impl FromPyObject<'_> for TreeDelta { fn extract(ob: &PyAny) -> PyResult { let added = ob.getattr("added")?.extract()?; let removed = ob.getattr("removed")?.extract()?; let renamed = ob.getattr("renamed")?.extract()?; let copied = ob.getattr("copied")?.extract()?; let kind_changed = ob.getattr("kind_changed")?.extract()?; let modified = ob.getattr("modified")?.extract()?; let unchanged = ob.getattr("unchanged")?.extract()?; let unversioned = ob.getattr("unversioned")?.extract()?; let missing = ob.getattr("missing")?.extract()?; Ok(TreeDelta { added, removed, renamed, copied, kind_changed, modified, unchanged, unversioned, missing, }) } } breezyshim-0.1.78/src/diff.rs000064400000000000000000000016351046102023000141540ustar 00000000000000use crate::tree::Tree; use pyo3::prelude::*; use pyo3::types::PyDict; use std::io::Write; pub fn show_diff_trees( tree1: &dyn Tree, tree2: &dyn Tree, mut w: impl Write, old_label: Option<&str>, new_label: Option<&str>, ) -> PyResult<()> { Python::with_gil(|py| -> PyResult<()> { let m = py.import("breezy.diff")?; let f = m.getattr("show_diff_trees")?; let o = py.import("io")?.call_method0("BytesIO")?; let kwargs = PyDict::new(py); if let Some(old_label) = old_label { kwargs.set_item("old_label", old_label)?; } if let Some(new_label) = new_label { kwargs.set_item("new_label", new_label)?; } f.call((tree1.to_object(py), tree2.to_object(py), o), Some(kwargs))?; let s = o.call_method0("getvalue")?.extract::>()?; w.write_all(&s)?; Ok(()) })?; Ok(()) } breezyshim-0.1.78/src/dirty_tracker.rs000064400000000000000000000070741046102023000161150ustar 00000000000000use crate::tree::WorkingTree; use pyo3::import_exception; use pyo3::prelude::*; pub struct DirtyTracker { obj: PyObject, owned: bool, } impl ToPyObject for DirtyTracker { fn to_object(&self, py: Python) -> PyObject { self.obj.clone_ref(py) } } impl FromPyObject<'_> for DirtyTracker { fn extract(ob: &PyAny) -> PyResult { Ok(DirtyTracker { obj: ob.to_object(ob.py()), owned: false, }) } } impl From for DirtyTracker { fn from(obj: PyObject) -> Self { DirtyTracker { obj, owned: false } } } import_exception!(breezy.dirty_tracker, TooManyOpenFiles); #[derive(Debug)] pub enum Error { TooManyOpenFiles, Python(PyErr), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match &self { Error::TooManyOpenFiles => write!(f, "Too many open files"), Error::Python(e) => write!(f, "{}", e), } } } impl std::error::Error for Error {} impl From for Error { fn from(e: PyErr) -> Self { Python::with_gil(|py| { if e.is_instance_of::(py) { Error::TooManyOpenFiles } else { Error::Python(e) } }) } } impl DirtyTracker { fn new(obj: PyObject) -> Result { Python::with_gil(|py| { let dt = DirtyTracker { obj, owned: true }; dt.to_object(py).call_method0(py, "__enter__")?; Ok(dt) }) } pub fn is_dirty(&self) -> bool { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "is_dirty") .unwrap() .extract(py) .unwrap() }) } pub fn relpaths(&self) -> impl IntoIterator { Python::with_gil(|py| { let set = self .to_object(py) .call_method0(py, "relpaths") .unwrap() .extract::>(py) .unwrap(); set.into_iter() }) } pub fn mark_clean(&self) { Python::with_gil(|py| { self.to_object(py).call_method0(py, "mark_clean").unwrap(); }) } } impl Drop for DirtyTracker { fn drop(&mut self) { if !self.owned { return; } Python::with_gil(|py| { self.to_object(py) .call_method1(py, "__exit__", (py.None(), py.None(), py.None())) .unwrap(); }) } } /// Create a dirty tracker object pub fn get_dirty_tracker( local_tree: &WorkingTree, subpath: Option<&std::path::Path>, use_inotify: Option, ) -> Result, Error> { Python::with_gil(|py| { let dt_cls = match use_inotify { Some(true) => { let m = py.import("breezy.dirty_tracker")?; m.getattr("DirtyTracker")? } Some(false) => return Ok(None), None => match py.import("breezy.dirty_tracker") { Ok(m) => m.getattr("DirtyTracker")?, Err(e) => { if e.is_instance_of::(py) { return Ok(None); } else { return Err(e.into()); } } }, }; let o = dt_cls.call1((local_tree.to_object(py), subpath))?; Ok(Some(DirtyTracker::new(o.into())?)) }) } breezyshim-0.1.78/src/export.rs000064400000000000000000000012641046102023000145630ustar 00000000000000use crate::tree::Tree; use pyo3::prelude::*; use pyo3::types::PyDict; use std::path::Path; pub fn export( tree: &dyn Tree, target: &std::path::Path, subdir: Option<&std::path::Path>, ) -> PyResult<()> { Python::with_gil(|py| { let m = py.import("breezy.export").unwrap(); let export = m.getattr("export").unwrap(); let kwargs = PyDict::new(py); let subdir = if subdir.is_none() || subdir == Some(Path::new("")) { None } else { Some(subdir) }; kwargs.set_item("subdir", subdir).unwrap(); export.call((tree.to_object(py), target, "dir", py.None()), Some(kwargs))?; Ok(()) }) } breezyshim-0.1.78/src/forge.rs000064400000000000000000000443661046102023000143560ustar 00000000000000use crate::branch::{py_tag_selector, Branch, RegularBranch}; use crate::revisionid::RevisionId; use pyo3::conversion::ToPyObject; use pyo3::exceptions::PyValueError; use pyo3::import_exception; use pyo3::prelude::*; use pyo3::types::PyDict; import_exception!(breezy.forge, ForgeLoginRequired); import_exception!(breezy.forge, UnsupportedForge); import_exception!(breezy.errors, AlreadyControlDirError); #[derive(Clone, Debug)] pub enum Error { LoginRequired, UnsupportedForge(url::Url), ProjectExists(String), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::LoginRequired => write!(f, "Login required"), Error::UnsupportedForge(url) => write!(f, "Unsupported forge: {}", url), Error::ProjectExists(name) => write!(f, "Project already exists: {}", name), } } } impl std::error::Error for Error {} impl From for Error { fn from(err: PyErr) -> Self { Python::with_gil(|py| { if err.is_instance_of::(py) { Error::LoginRequired } else if err.is_instance_of::(py) { Error::UnsupportedForge( err.value(py) .getattr("branch") .unwrap() .extract::() .unwrap() .parse() .unwrap(), ) } else if err.is_instance_of::(py) { Error::ProjectExists( err.value(py) .getattr("path") .unwrap() .extract::() .unwrap(), ) } else { panic!("Unexpected error: {}", err); } }) } } impl From for PyErr { fn from(err: Error) -> PyErr { match err { Error::LoginRequired => ForgeLoginRequired::new_err("Login required"), Error::UnsupportedForge(url) => UnsupportedForge::new_err(url.to_string()), Error::ProjectExists(name) => AlreadyControlDirError::new_err(name), } } } #[derive(Clone)] pub struct Forge(PyObject); impl From for Forge { fn from(obj: PyObject) -> Self { Forge(obj) } } #[derive(Clone, Copy)] pub enum MergeProposalStatus { All, Open, Closed, Merged, } impl MergeProposalStatus { pub fn all() -> Vec { vec![MergeProposalStatus::All] } } impl std::str::FromStr for MergeProposalStatus { type Err = String; fn from_str(s: &str) -> Result { match s { "all" => Ok(MergeProposalStatus::All), "open" => Ok(MergeProposalStatus::Open), "merged" => Ok(MergeProposalStatus::Merged), "closed" => Ok(MergeProposalStatus::Closed), _ => Err(format!("Invalid merge proposal status: {}", s)), } } } impl ToString for MergeProposalStatus { fn to_string(&self) -> String { match self { MergeProposalStatus::All => "all".to_string(), MergeProposalStatus::Open => "open".to_string(), MergeProposalStatus::Merged => "merged".to_string(), MergeProposalStatus::Closed => "closed".to_string(), } } } impl ToPyObject for MergeProposalStatus { fn to_object(&self, py: Python) -> PyObject { self.to_string().to_object(py) } } impl FromPyObject<'_> for MergeProposalStatus { fn extract(ob: &PyAny) -> PyResult { let status = ob.extract::()?; match status.as_str() { "all" => Ok(MergeProposalStatus::All), "open" => Ok(MergeProposalStatus::Open), "merged" => Ok(MergeProposalStatus::Merged), "closed" => Ok(MergeProposalStatus::Closed), _ => Err(PyValueError::new_err((format!( "Invalid merge proposal status: {}", status ),))), } } } #[derive(Clone)] pub struct MergeProposal(PyObject); impl From for MergeProposal { fn from(obj: PyObject) -> Self { MergeProposal(obj) } } impl MergeProposal { pub fn reopen(&self) -> PyResult<()> { Python::with_gil(|py| { self.0.call_method0(py, "reopen")?; Ok(()) }) } pub fn close(&self) -> PyResult<()> { Python::with_gil(|py| { self.0.call_method0(py, "close")?; Ok(()) }) } pub fn url(&self) -> PyResult { Python::with_gil(|py| { let url = self.0.getattr(py, "url")?; Ok(url.extract::(py)?.parse().unwrap()) }) } pub fn is_merged(&self) -> PyResult { Python::with_gil(|py| { let is_merged = self.0.call_method0(py, "is_merged")?; is_merged.extract(py) }) } pub fn is_closed(&self) -> PyResult { Python::with_gil(|py| { let is_closed = self.0.call_method0(py, "is_closed")?; is_closed.extract(py) }) } pub fn get_title(&self) -> PyResult> { Python::with_gil(|py| { let title = self.0.call_method0(py, "get_title")?; title.extract(py) }) } pub fn set_title(&self, title: Option<&str>) -> PyResult<()> { Python::with_gil(|py| { self.0.call_method1(py, "set_title", (title,))?; Ok(()) }) } pub fn get_commit_message(&self) -> PyResult> { Python::with_gil(|py| { let commit_message = self.0.call_method0(py, "get_commit_message")?; commit_message.extract(py) }) } pub fn set_commit_message(&self, commit_message: Option<&str>) -> PyResult<()> { Python::with_gil(|py| { self.0 .call_method1(py, "set_commit_message", (commit_message,))?; Ok(()) }) } pub fn get_target_branch_url(&self) -> PyResult> { Python::with_gil(|py| { let target_branch_url = self.0.call_method0(py, "get_target_branch_url")?; target_branch_url .extract::(py)? .parse() .map(Some) .map_err(|e| PyValueError::new_err(format!("{}", e))) }) } pub fn get_source_branch_url(&self) -> PyResult> { Python::with_gil(|py| { let source_branch_url = self.0.call_method0(py, "get_source_branch_url")?; source_branch_url .extract::(py)? .parse() .map(Some) .map_err(|e| PyValueError::new_err(format!("{}", e))) }) } pub fn get_description(&self) -> PyResult> { Python::with_gil(|py| { let description = self.0.call_method0(py, "get_description")?; description.extract(py) }) } pub fn set_description(&self, description: Option<&str>) -> PyResult<()> { Python::with_gil(|py| { self.0.call_method1(py, "set_description", (description,))?; Ok(()) }) } pub fn can_be_merged(&self) -> PyResult { Python::with_gil(|py| { let can_be_merged = self.0.call_method0(py, "can_be_merged")?; can_be_merged.extract(py) }) } pub fn supports_auto_merge(&self) -> bool { Python::with_gil(|py| { self.0 .getattr(py, "supports_auto_merge") .unwrap() .extract(py) .unwrap() }) } pub fn merge(&self, auto: bool) -> Result<(), Error> { Python::with_gil(|py| { self.0.call_method1(py, "merge", (auto,))?; Ok(()) }) } } #[pyclass] pub struct ProposalBuilder(PyObject, PyObject); impl ProposalBuilder { pub fn description(self, description: &str) -> Self { Python::with_gil(|py| { self.1 .as_ref(py) .set_item("description", description) .unwrap(); }); self } pub fn labels(self, labels: &[&str]) -> Self { Python::with_gil(|py| { self.1.as_ref(py).set_item("labels", labels).unwrap(); }); self } pub fn reviewers(self, reviewers: &[&str]) -> Self { Python::with_gil(|py| { self.1.as_ref(py).set_item("reviewers", reviewers).unwrap(); }); self } pub fn allow_collaboration(self, allow_collaboration: bool) -> Self { Python::with_gil(|py| { self.1 .as_ref(py) .set_item("allow_collaboration", allow_collaboration) .unwrap(); }); self } pub fn title(self, title: &str) -> Self { Python::with_gil(|py| { self.1.as_ref(py).set_item("title", title).unwrap(); }); self } pub fn commit_message(self, commit_message: &str) -> Self { Python::with_gil(|py| { self.1 .as_ref(py) .set_item("commit_message", commit_message) .unwrap(); }); self } pub fn build(self) -> PyResult { Python::with_gil(|py| { let kwargs = self.1; let proposal = self.0.call_method1(py, "create_proposal", (kwargs,))?; Ok(MergeProposal::from(proposal)) }) } } impl Forge { pub fn get_proposal_by_url(&self, url: &url::Url) -> PyResult { Python::with_gil(|py| { let proposal = self.to_object(py) .call_method1(py, "get_proposal_by_url", (url.as_str(),))?; Ok(MergeProposal::from(proposal)) }) } pub fn base_url(&self) -> url::Url { Python::with_gil(|py| { let base_url = self.to_object(py).getattr(py, "base_url").unwrap(); base_url.extract::(py).unwrap().parse().unwrap() }) } pub fn forge_kind(&self) -> String { Python::with_gil(|py| { self.to_object(py) .as_ref(py) .get_type() .name() .unwrap() .to_string() }) } pub fn forge_name(&self) -> String { Python::with_gil(|py| { self.to_object(py) .as_ref(py) .get_type() .name() .unwrap() .to_string() }) } pub fn merge_proposal_description_format(&self) -> String { Python::with_gil(|py| { let merge_proposal_description_format = self .to_object(py) .getattr(py, "merge_proposal_description_format") .unwrap(); merge_proposal_description_format.extract(py).unwrap() }) } pub fn supports_merge_proposal_commit_message(&self) -> bool { Python::with_gil(|py| { let supports_merge_proposal_commit_message = self .to_object(py) .getattr(py, "supports_merge_proposal_commit_message") .unwrap(); supports_merge_proposal_commit_message.extract(py).unwrap() }) } pub fn supports_merge_proposal_title(&self) -> bool { Python::with_gil(|py| { let supports_merge_proposal_title = self .to_object(py) .getattr(py, "supports_merge_proposal_title") .unwrap(); supports_merge_proposal_title.extract(py).unwrap() }) } pub fn get_proposer( &self, from_branch: &dyn Branch, to_branch: &dyn Branch, ) -> PyResult { Python::with_gil(|py| { Ok(ProposalBuilder( self.0.call_method1( py, "get_proposer", (from_branch.to_object(py), to_branch.to_object(py)), )?, PyDict::new(py).into(), )) }) } pub fn iter_my_proposals( &self, status: Option, author: Option, ) -> Result, Error> { let ret: Vec = Python::with_gil(|py| -> Result, Error> { Ok(self .to_object(py) .call_method( py, "iter_my_proposals", (status.to_object(py), author), None, )? .as_ref(py) .iter() .unwrap() .map(|proposal| MergeProposal::from(proposal.unwrap().to_object(py))) .collect()) })?; Ok(ret.into_iter()) } pub fn get_derived_branch( &self, main_branch: &dyn Branch, name: &str, owner: Option<&str>, preferred_schemes: Option<&[&str]>, ) -> PyResult> { Python::with_gil(|py| { let kwargs = PyDict::new(py); if let Some(owner) = owner { kwargs.set_item("owner", owner)?; } if let Some(preferred_schemes) = preferred_schemes { kwargs.set_item("preferred_schemes", preferred_schemes)?; } let branch = self.to_object(py).call_method( py, "get_derived_branch", (main_branch.to_object(py), name), Some(kwargs), )?; Ok(Box::new(RegularBranch::new(branch)) as Box) }) } pub fn iter_proposals( &self, source_branch: &dyn Branch, target_branch: &dyn Branch, status: MergeProposalStatus, ) -> PyResult> { Python::with_gil(move |py| { let kwargs = PyDict::new(py); kwargs.set_item("status", status.to_string())?; let proposals: Vec = self .0 .call_method( py, "iter_proposals", (&source_branch.to_object(py), &target_branch.to_object(py)), Some(kwargs), )? .extract(py)?; Ok(proposals.into_iter().map(MergeProposal::from)) }) } pub fn publish_derived( &self, local_branch: &dyn Branch, main_branch: &dyn Branch, name: &str, overwrite_existing: Option, owner: Option<&str>, stop_revision: Option<&RevisionId>, tag_selector: Option bool>>, ) -> PyResult<(Box, url::Url)> { Python::with_gil(|py| { let kwargs = PyDict::new(py); kwargs.set_item("local_branch", &local_branch.to_object(py))?; kwargs.set_item("main_branch", &main_branch.to_object(py))?; kwargs.set_item("name", name)?; if let Some(overwrite_existing) = overwrite_existing { kwargs.set_item("overwrite_existing", overwrite_existing)?; } if let Some(owner) = owner { kwargs.set_item("owner", owner)?; } if let Some(stop_revision) = stop_revision { kwargs.set_item("stop_revision", stop_revision)?; } if let Some(tag_selector) = tag_selector { kwargs.set_item("tag_selector", py_tag_selector(py, tag_selector)?)?; } let (b, u): (PyObject, String) = self .to_object(py) .call_method(py, "publish_derived", (), Some(kwargs))? .extract(py)?; Ok(( Box::new(RegularBranch::new(b)) as Box, u.parse::().unwrap(), )) }) } pub fn get_push_url(&self, branch: &dyn Branch) -> url::Url { Python::with_gil(|py| { let url = self .to_object(py) .call_method1(py, "get_push_url", (&branch.to_object(py),)) .unwrap() .extract::(py) .unwrap(); url.parse::().unwrap() }) } } impl std::fmt::Debug for Forge { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Forge").finish() } } impl FromPyObject<'_> for Forge { fn extract(ob: &PyAny) -> PyResult { Ok(Forge(ob.to_object(ob.py()))) } } impl ToPyObject for Forge { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } pub fn get_forge(branch: &dyn Branch) -> Result { Python::with_gil(|py| { let m = py.import("breezy.forge").unwrap(); let forge = m.call_method1("get_forge", (branch.to_object(py),))?; Ok(Forge(forge.to_object(py))) }) } pub fn determine_title(description: &str) -> String { Python::with_gil(|py| { let m = py.import("breezy.forge").unwrap(); let title = m.call_method1("determine_title", (description,)).unwrap(); title.extract::() }) .unwrap() } pub fn iter_forge_instances() -> impl Iterator { let ret = Python::with_gil(|py| { let m = py.import("breezy.forge").unwrap(); let f = m.getattr("iter_forge_instances").unwrap(); let instances = f.call0().unwrap(); instances .iter() .unwrap() .map(|i| Forge(i.unwrap().to_object(py))) .collect::>() }); ret.into_iter() } pub fn create_project(name: &str, summary: Option<&str>) -> Result<(), Error> { Python::with_gil(|py| { let m = py.import("breezy.forge").unwrap(); m.call_method1("create_project", (name, summary))?; Ok(()) }) } pub fn get_proposal_by_url(url: &url::Url) -> Result { Python::with_gil(|py| { let m = py.import("breezy.forge").unwrap(); let proposal = m.call_method1("get_proposal_by_url", (url.to_string(),))?; Ok(MergeProposal::from(proposal.to_object(py))) }) } breezyshim-0.1.78/src/github.rs000064400000000000000000000004231046102023000145200ustar 00000000000000use pyo3::prelude::*; pub fn retrieve_github_token() -> String { Python::with_gil(|py| { let m = py.import("breezy.plugins.github.forge").unwrap(); let token = m.call_method0("retrieve_github_token").unwrap(); token.extract().unwrap() }) } breezyshim-0.1.78/src/gpg.rs000064400000000000000000000042741046102023000140230ustar 00000000000000use crate::repository::Repository; use crate::RevisionId; use pyo3::import_exception; use pyo3::prelude::*; use std::collections::HashMap; #[derive(Debug)] pub enum Error { GPGNotInstalled, } #[derive(Debug)] pub enum Mode { Normal, Detach, Clear, } #[derive(Debug)] pub enum Status { Valid, KeyMissing(String), NotValid(String), NotSigned, Expired(String), } import_exception!(breezy.gpg, GPGNotInstalled); impl From for Error { fn from(e: PyErr) -> Self { Python::with_gil(|py| { if e.is_instance_of::(py) { Error::GPGNotInstalled } else { panic!("unexpected exception: {:?}", e) } }) } } pub struct GPGStrategy(PyObject); impl ToPyObject for GPGStrategy { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for GPGStrategy { fn extract(ob: &PyAny) -> PyResult { Ok(GPGStrategy(ob.to_object(ob.py()))) } } pub struct VerificationResult {} impl FromPyObject<'_> for VerificationResult { fn extract(_ob: &PyAny) -> PyResult { Ok(VerificationResult {}) } } impl ToPyObject for VerificationResult { fn to_object(&self, py: Python) -> PyObject { py.None() } } pub fn bulk_verify_signatures( repository: &Repository, revids: &[&RevisionId], strategy: &GPGStrategy, ) -> Result< ( HashMap, Vec<(RevisionId, VerificationResult, String)>, bool, ), Error, > { Python::with_gil(|py| { let gpg = PyModule::import(py, "breezy.gpg").unwrap(); let bulk_verify_signatures = gpg.getattr("bulk_verify_signatures").unwrap(); let r = bulk_verify_signatures .call1(( repository.to_object(py), revids.iter().map(|r| r.to_object(py)).collect::>(), strategy.to_object(py), )) .map_err(|e| -> Error { e.into() })?; Ok(r.extract::<( HashMap, Vec<(RevisionId, VerificationResult, String)>, bool, )>() .unwrap()) }) } breezyshim-0.1.78/src/graph.rs000064400000000000000000000046321046102023000143450ustar 00000000000000use crate::revisionid::RevisionId; use pyo3::exceptions::PyStopIteration; use pyo3::import_exception; use pyo3::prelude::*; import_exception!(breezy.errors, RevisionNotPresent); pub struct Graph(PyObject); impl ToPyObject for Graph { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for Graph { fn extract(ob: &PyAny) -> PyResult { Ok(Graph(ob.to_object(ob.py()))) } } impl From for Graph { fn from(ob: PyObject) -> Self { Graph(ob) } } struct RevIter(PyObject); impl Iterator for RevIter { type Item = Result; fn next(&mut self) -> Option { Python::with_gil(|py| match self.0.call_method0(py, "__next__") { Ok(item) => Some(Ok(RevisionId::from(item.extract::>(py).unwrap()))), Err(e) if e.is_instance_of::(py) => None, Err(e) => Some(Err(e.into())), }) } } #[derive(Debug)] pub enum Error { RevisionNotPresent(RevisionId), } impl From for Error { fn from(e: PyErr) -> Self { Python::with_gil(|py| { if e.is_instance_of::(py) { Error::RevisionNotPresent(RevisionId::from( e.value(py) .getattr("revision_id") .unwrap() .extract::>() .unwrap(), )) } else { panic!("unexpected error: {:?}", e) } }) } } impl Graph { pub fn is_ancestor(&self, rev1: &RevisionId, rev2: &RevisionId) -> bool { Python::with_gil(|py| { self.0 .call_method1(py, "is_ancestor", (rev1.as_bytes(), rev2.as_bytes())) .unwrap() .extract(py) .unwrap() }) } pub fn iter_lefthand_ancestry( &self, revid: &RevisionId, stop_revisions: Option<&[RevisionId]>, ) -> impl Iterator> { Python::with_gil(|py| { let iter = self .0 .call_method1( py, "iter_lefthand_ancestry", (revid.as_bytes(), stop_revisions.map(|x| x.to_vec())), ) .unwrap(); RevIter(iter) }) } } breezyshim-0.1.78/src/hooks.rs000064400000000000000000000023571046102023000143710ustar 00000000000000use pyo3::prelude::*; pub struct HookDict(PyObject); pub struct Hook(PyObject); impl HookDict { pub fn new(module: &str, cls: &str, name: &str) -> Self { Python::with_gil(|py| -> PyResult { let module = PyModule::import(py, module)?; let cls = module.getattr(cls)?; let entrypoint = cls.getattr(name)?; Ok(Self(entrypoint.to_object(py))) }) .unwrap() } pub fn clear(&self, name: &str) -> PyResult<()> { Python::with_gil(|py| { let entrypoint = self.0.as_ref(py).get_item(name)?; entrypoint.call_method0("clear")?; Ok(()) }) } pub fn add(&self, name: &str, func: Hook) -> PyResult<()> { Python::with_gil(|py| { let entrypoint = self.0.as_ref(py).get_item(name)?; entrypoint.call_method1("add", (func.0,))?; Ok(()) }) } pub fn get(&self, name: &str) -> PyResult> { Python::with_gil(|py| { let entrypoint = self.0.as_ref(py).get_item(name)?; Ok(entrypoint .extract::>()? .into_iter() .map(Hook) .collect()) }) } } breezyshim-0.1.78/src/intertree.rs000064400000000000000000000015411046102023000152410ustar 00000000000000use crate::delta::TreeDelta; use crate::tree::Tree; use pyo3::prelude::*; pub struct InterTree(PyObject); pub fn get(source: &dyn Tree, target: &dyn Tree) -> InterTree { Python::with_gil(|py| { let source = source.to_object(py); let target = target.to_object(py); let intertree_cls = py .import("breezy.tree") .unwrap() .getattr("InterTree") .unwrap(); InterTree( intertree_cls .call_method1("get", (source, target)) .unwrap() .to_object(py), ) }) } impl InterTree { pub fn compare(&self) -> TreeDelta { Python::with_gil(|py| { self.0 .call_method0(py, "compare") .unwrap() .extract(py) .unwrap() }) } } breezyshim-0.1.78/src/lib.rs000064400000000000000000000061641046102023000140140ustar 00000000000000//! This crate contains a rust wrapper for the Breezy API, which is written in Python. //! //! Breezy itself is being ported to Rust, but until that port has completed, this crate allows //! access to the most important Breezy APIs via Rust. //! //! The Rust API here will follow the Breezy 4.0 Rust API as much as possible, to make porting //! easier. //! //! # Example //! //! ``` //! use breezyshim::branch::open as open_branch; //! breezyshim::plugin::load_plugins(); //! let b = open_branch(&"lp:brz".parse().unwrap()).unwrap(); //! println!("Last revision: {:?}", b.last_revision()); //! ``` pub mod bazaar; pub mod branch; pub mod controldir; pub mod delta; pub mod diff; pub mod dirty_tracker; pub mod export; pub mod forge; pub mod github; pub mod gpg; pub mod graph; pub mod hooks; pub mod intertree; pub mod location; pub mod lock; pub mod merge; pub mod plugin; pub mod rename_map; pub mod repository; pub mod revisionid; pub mod status; pub mod tags; pub mod transform; pub mod transport; pub mod tree; pub mod urlutils; pub mod version; pub mod workspace; #[cfg(feature = "debian")] pub mod debian; pub use branch::Branch; pub use controldir::{ControlDir, Prober}; pub use dirty_tracker::DirtyTracker; pub use forge::{get_forge, Forge, MergeProposal, MergeProposalStatus}; pub use lock::Lock; use pyo3::exceptions::PyImportError; pub use revisionid::RevisionId; use std::sync::Once; pub use transport::{get_transport, Transport}; pub use tree::{RevisionTree, Tree, WorkingTree}; pub use urlutils::{join_segment_parameters, split_segment_parameters}; pub use workspace::reset_tree; pub fn init_git() { pyo3::Python::with_gil(|py| { py.import("breezy.git").unwrap(); }) } pub fn init_bzr() { pyo3::Python::with_gil(|py| { py.import("breezy.bzr").unwrap(); }) } #[derive(Debug)] pub struct BreezyNotInstalled { pub message: String, } impl std::fmt::Display for BreezyNotInstalled { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Breezy is not installed: {}", self.message) } } static INIT_BREEZY: Once = Once::new(); pub fn init() -> Result<(), BreezyNotInstalled> { INIT_BREEZY.call_once(|| { pyo3::Python::with_gil(|py| match py.import("breezy") { Ok(_) => Ok(()), Err(e) => { if e.is_instance_of::(py) { Err(BreezyNotInstalled { message: e.to_string(), }) } else { Err::<(), pyo3::PyErr>(e).unwrap(); unreachable!() } } }) .expect("Breezy is not installed"); init_git(); init_bzr(); // Work around a breezy bug pyo3::Python::with_gil(|py| { let m = py.import("breezy.controldir").unwrap(); let f = m.getattr("ControlDirFormat").unwrap(); f.call_method0("known_formats").unwrap(); }); }); Ok(()) } pub fn load_plugins() { pyo3::Python::with_gil(|py| { let m = py.import("breezy.plugin").unwrap(); m.call_method0("load_plugins").unwrap(); }) } breezyshim-0.1.78/src/location.rs000064400000000000000000000026701046102023000150540ustar 00000000000000use pyo3::prelude::*; use url::Url; pub fn cvs_to_url(cvsroot: &str) -> Url { Python::with_gil(|py| { let breezy_location = py.import("breezy.location").unwrap(); breezy_location .call_method1("cvs_to_url", (cvsroot,)) .unwrap() .extract::() .unwrap() .parse() .unwrap() }) } pub fn rcp_location_to_url(rcp_location: &str) -> Result { Python::with_gil(|py| { let breezy_location = py.import("breezy.location").unwrap(); Ok(breezy_location .call_method1("rcp_location_to_url", (rcp_location,)) .map_err(|e| e.to_string())? .extract::() .unwrap() .parse() .unwrap()) }) } pub trait AsLocation { fn as_location(&self) -> PyObject; } impl AsLocation for &url::Url { fn as_location(&self) -> PyObject { Python::with_gil(|py| { pyo3::types::PyString::new(py, self.to_string().as_str()).to_object(py) }) } } impl AsLocation for &str { fn as_location(&self) -> PyObject { Python::with_gil(|py| { pyo3::types::PyString::new(py, self).to_object(py) }) } } impl AsLocation for &std::path::Path { fn as_location(&self) -> PyObject { Python::with_gil(|py| { pyo3::types::PyString::new(py, self.to_str().unwrap()).to_object(py) }) } } breezyshim-0.1.78/src/lock.rs000064400000000000000000000006371046102023000141750ustar 00000000000000use pyo3::prelude::*; pub struct Lock(PyObject); impl From for Lock { fn from(obj: PyObject) -> Self { Lock(obj) } } impl ToPyObject for Lock { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Drop for Lock { fn drop(&mut self) { Python::with_gil(|py| { self.0.call_method0(py, "unlock").unwrap(); }); } } breezyshim-0.1.78/src/merge.rs000064400000000000000000000111761046102023000143440ustar 00000000000000use crate::branch::Branch; use crate::graph::Graph; use crate::hooks::HookDict; use crate::transform::TreeTransform; use crate::tree::Tree; use crate::RevisionId; use pyo3::import_exception; use pyo3::prelude::*; use pyo3::types::PyDict; import_exception!(breezy.errors, UnrelatedBranches); pub enum Error { UnrelatedBranches, } impl From for Error { fn from(e: PyErr) -> Self { Python::with_gil(|py| { if e.is_instance_of::(py) { Error::UnrelatedBranches } else { panic!("unexpected error: {:?}", e) } }) } } pub struct Merger(PyObject); pub enum MergeType { Merge3, } impl From for Merger { fn from(obj: PyObject) -> Self { Merger(obj) } } impl Merger { pub fn new(branch: &dyn Branch, this_tree: &dyn Tree, revision_graph: &Graph) -> Self { Python::with_gil(|py| { let m = py.import("breezy.merge").unwrap(); let cls = m.getattr("Merger").unwrap(); let kwargs = PyDict::new(py); kwargs .set_item("this_tree", this_tree.to_object(py)) .unwrap(); kwargs .set_item("revision_graph", revision_graph.to_object(py)) .unwrap(); let merger = cls.call((branch.to_object(py),), Some(kwargs)).unwrap(); Merger(merger.into()) }) } pub fn find_base(&self) -> PyResult> { Python::with_gil(|py| match self.0.call_method0(py, "find_base") { Ok(_py_obj) => Ok(self .0 .getattr(py, "base_rev_id") .unwrap() .extract(py) .unwrap()), Err(err) => { if err.is_instance_of::(py) { Ok(None) } else { Err(err) } } }) } pub fn set_other_revision( &mut self, other_revision: &RevisionId, other_branch: &dyn Branch, ) -> PyResult<()> { Python::with_gil(|py| { self.0.call_method1( py, "set_other_revision", (other_revision.clone(), other_branch.to_object(py)), )?; Ok(()) }) } pub fn set_base_revision( &mut self, base_revision: &RevisionId, base_branch: &dyn Branch, ) -> PyResult<()> { Python::with_gil(|py| { self.0.call_method1( py, "set_base_revision", (base_revision.clone(), base_branch.to_object(py)), )?; Ok(()) }) } pub fn set_merge_type(&mut self, merge_type: MergeType) { Python::with_gil(|py| { let m = py.import("breezy.merge").unwrap(); let merge_type = match merge_type { MergeType::Merge3 => m.getattr("Merge3Merger").unwrap(), }; self.0.setattr(py, "merge_type", merge_type).unwrap(); }) } pub fn make_merger(&self) -> PyResult { Python::with_gil(|py| { let merger = self.0.call_method0(py, "make_merger")?; Ok(Submerger(merger)) }) } pub fn from_revision_ids( other_tree: &dyn Tree, other_branch: &dyn Branch, other: &RevisionId, tree_branch: &dyn Branch, ) -> Result { Python::with_gil(|py| { let m = py.import("breezy.merge").unwrap(); let cls = m.getattr("Merger").unwrap(); let kwargs = PyDict::new(py); kwargs .set_item("other_branch", other_branch.to_object(py)) .unwrap(); kwargs.set_item("other", other.to_object(py)).unwrap(); kwargs .set_item("tree_branch", tree_branch.to_object(py)) .unwrap(); let merger = cls.call_method( "from_revision_ids", (other_tree.to_object(py),), Some(kwargs), )?; Ok(Merger(merger.into())) }) } } pub struct Submerger(PyObject); impl Submerger { pub fn make_preview_transform(&self) -> PyResult { Python::with_gil(|py| { let transform = self .0 .call_method0(py, "make_preview_transform")? .to_object(py); Ok(TreeTransform::from(transform)) }) } } lazy_static::lazy_static! { pub static ref MERGE_HOOKS: HookDict = HookDict::new("breezy.merge", "Merger", "hooks"); } breezyshim-0.1.78/src/plugin.rs000064400000000000000000000005461046102023000145420ustar 00000000000000use pyo3::prelude::*; pub fn load_plugins() { Python::with_gil(|py| { let m = py.import("breezy.plugin").unwrap(); let load_plugins = m.getattr("load_plugins").unwrap(); load_plugins.call0().unwrap(); }); } #[cfg(test)] mod tests { use super::*; #[test] fn test_load_plugins() { load_plugins(); } } breezyshim-0.1.78/src/rename_map.rs000064400000000000000000000006641046102023000153510ustar 00000000000000use crate::tree::{MutableTree, Tree}; pub fn guess_renames(from_tree: &dyn Tree, mutable_tree: &dyn MutableTree) -> pyo3::PyResult<()> { pyo3::Python::with_gil(|py| { let m = py.import("breezy.rename_map")?; let rename_map = m.getattr("RenameMap")?; rename_map.call_method1( "guess_renames", (from_tree.to_object(py), mutable_tree.to_object(py)), )?; Ok(()) }) } breezyshim-0.1.78/src/repository.rs000064400000000000000000000132651046102023000154650ustar 00000000000000use crate::controldir::ControlDir; use crate::delta::TreeDelta; use crate::graph::Graph; use crate::revisionid::RevisionId; use crate::tree::RevisionTree; use pyo3::exceptions::PyStopIteration; use pyo3::prelude::*; use pyo3::types::PyDict; use chrono::DateTime; use chrono::TimeZone; #[derive(Clone)] pub struct RepositoryFormat(PyObject); impl RepositoryFormat { pub fn supports_chks(&self) -> bool { Python::with_gil(|py| { self.0 .getattr(py, "supports_chks") .unwrap() .extract(py) .unwrap() }) } } #[derive(Clone)] pub struct Repository(PyObject); #[derive(Debug)] pub struct Revision { pub revision_id: RevisionId, pub parent_ids: Vec, pub message: String, pub committer: String, pub timestamp: f64, pub timezone: i32, } impl Revision { pub fn datetime(&self) -> DateTime { let tz = chrono::FixedOffset::east(self.timezone); tz.timestamp_opt(self.timestamp as i64, 0).unwrap() } } impl ToPyObject for Revision { fn to_object(&self, py: Python) -> PyObject { let kwargs = PyDict::new(py); kwargs.set_item("message", self.message.clone()).unwrap(); kwargs .set_item("committer", self.committer.clone()) .unwrap(); kwargs.set_item("timestamp", self.timestamp).unwrap(); kwargs.set_item("timezone", self.timezone).unwrap(); kwargs.set_item("revision_id", &self.revision_id).unwrap(); kwargs .set_item("parent_ids", self.parent_ids.iter().collect::>()) .unwrap(); py.import("breezy.revision") .unwrap() .getattr("Revision") .unwrap() .call((), Some(kwargs)) .unwrap() .to_object(py) } } impl FromPyObject<'_> for Revision { fn extract(ob: &'_ PyAny) -> PyResult { Ok(Revision { revision_id: ob.getattr("revision_id")?.extract()?, parent_ids: ob.getattr("parent_ids")?.extract()?, message: ob.getattr("message")?.extract()?, committer: ob.getattr("committer")?.extract()?, timestamp: ob.getattr("timestamp")?.extract()?, timezone: ob.getattr("timezone")?.extract()?, }) } } pub struct RevisionIterator(PyObject); impl Iterator for RevisionIterator { type Item = (RevisionId, Option); fn next(&mut self) -> Option { Python::with_gil(|py| match self.0.call_method0(py, "__next__") { Err(e) if e.is_instance_of::(py) => None, Ok(o) => Some(o.extract(py).unwrap()), Err(e) => panic!("Error in revision iterator: {}", e), }) } } pub struct DeltaIterator(PyObject); impl Iterator for DeltaIterator { type Item = TreeDelta; fn next(&mut self) -> Option { Python::with_gil(|py| match self.0.call_method0(py, "__next__") { Err(e) if e.is_instance_of::(py) => None, Ok(o) => Some(o.extract(py).unwrap()), Err(e) => panic!("Error in delta iterator: {}", e), }) } } impl ToPyObject for Repository { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Repository { pub fn new(obj: PyObject) -> Self { Repository(obj) } pub fn fetch( &self, other_repository: &Repository, stop_revision: Option<&RevisionId>, ) -> PyResult<()> { Python::with_gil(|py| { self.0.call_method1( py, "fetch", ( other_repository.to_object(py), stop_revision.map(|r| r.to_object(py)), ), )?; Ok(()) }) } pub fn revision_tree(&self, revid: &RevisionId) -> PyResult { Python::with_gil(|py| { let o = self.0.call_method1(py, "revision_tree", (revid.clone(),))?; Ok(RevisionTree(o)) }) } pub fn get_graph(&self) -> Graph { Python::with_gil(|py| Graph::from(self.0.call_method0(py, "get_graph").unwrap())) } pub fn controldir(&self) -> ControlDir { Python::with_gil(|py| ControlDir::new(self.0.getattr(py, "controldir").unwrap())) } pub fn format(&self) -> RepositoryFormat { Python::with_gil(|py| RepositoryFormat(self.0.getattr(py, "_format").unwrap())) } pub fn iter_revisions( &self, revision_ids: Vec, ) -> impl Iterator)> { Python::with_gil(|py| { let o = self .0 .call_method1(py, "iter_revisions", (revision_ids,)) .unwrap(); RevisionIterator(o) }) } pub fn get_revision_deltas( &self, revs: &[Revision], specific_files: Option<&[&std::path::Path]>, ) -> impl Iterator { Python::with_gil(|py| { let revs = revs.iter().map(|r| r.to_object(py)).collect::>(); let specific_files = specific_files .map(|files| files.iter().map(|f| f.to_path_buf()).collect::>()); let o = self .0 .call_method1(py, "get_revision_deltas", (revs, specific_files)) .unwrap(); DeltaIterator(o) }) } pub fn get_revision(&self, revision_id: &RevisionId) -> PyResult { Python::with_gil(|py| { self.0 .call_method1(py, "get_revision", (revision_id.clone(),))? .extract(py) }) } } breezyshim-0.1.78/src/revisionid.rs000064400000000000000000000040041046102023000154100ustar 00000000000000use pyo3::prelude::*; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] pub struct RevisionId(Vec); impl std::fmt::Debug for RevisionId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = String::from_utf8(self.0.clone()).unwrap(); write!(f, "{}", s) } } impl RevisionId { pub fn as_bytes(&self) -> &[u8] { &self.0 } pub fn is_null(&self) -> bool { self.0 == NULL_REVISION } pub fn is_reserved(&self) -> bool { self.0.starts_with(b":") } pub fn null() -> Self { Self(NULL_REVISION.to_vec()) } } impl From> for RevisionId { fn from(value: Vec) -> Self { Self(value) } } impl Serialize for RevisionId { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(String::from_utf8(self.0.clone()).unwrap().as_str()) } } impl<'de> Deserialize<'de> for RevisionId { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { String::deserialize(deserializer).map(|s| Self(s.into_bytes())) } } impl FromPyObject<'_> for RevisionId { fn extract(ob: &'_ PyAny) -> PyResult { let bytes = ob.extract::>()?; Ok(Self(bytes)) } } impl ToPyObject for &RevisionId { fn to_object(&self, py: Python) -> PyObject { pyo3::types::PyBytes::new(py, &self.0).to_object(py) } } impl IntoPy for RevisionId { fn into_py(self, py: Python) -> PyObject { pyo3::types::PyBytes::new(py, self.0.as_slice()).to_object(py) } } impl std::fmt::Display for RevisionId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = String::from_utf8(self.0.clone()).unwrap(); write!(f, "{}", s) } } pub const CURRENT_REVISION: &[u8] = b"current:"; pub const NULL_REVISION: &[u8] = b"null:"; breezyshim-0.1.78/src/status.rs000064400000000000000000000004361046102023000145650ustar 00000000000000use crate::tree::WorkingTree; use pyo3::prelude::*; pub fn show_tree_status(wt: &WorkingTree) -> PyResult<()> { Python::with_gil(|py| { let m = py.import("breezy.status")?; let f = m.getattr("show_tree_status")?; f.call1((&wt.0,))?; Ok(()) }) } breezyshim-0.1.78/src/tags.rs000064400000000000000000000047541046102023000142070ustar 00000000000000use crate::revisionid::RevisionId; use pyo3::prelude::*; use std::collections::{HashMap, HashSet}; pub struct Tags(PyObject); impl From for Tags { fn from(obj: PyObject) -> Self { Tags(obj) } } #[derive(Debug)] pub enum Error { NoSuchTag(String), TagAlreadyExists(String), Other(PyErr), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::NoSuchTag(tag) => write!(f, "No such tag: {}", tag), Error::TagAlreadyExists(tag) => write!(f, "Tag already exists: {}", tag), Error::Other(err) => write!(f, "{}", err), } } } impl std::error::Error for Error {} pyo3::import_exception!(breezy.errors, NoSuchTag); impl From for Error { fn from(err: PyErr) -> Self { Python::with_gil(|py| { if err.is_instance_of::(py) { Error::NoSuchTag(err.value(py).getattr("tag_name").unwrap().extract().unwrap()) } else { Error::Other(err) } }) } } impl Tags { pub fn get_reverse_tag_dict(&self) -> PyResult>> { Python::with_gil(|py| { self .0 .call_method0(py, "get_reverse_tag_dict")? .extract(py) }) } pub fn get_tag_dict(&self) -> PyResult>> { Python::with_gil(|py| { self .0 .call_method0(py, "get_tag_dict")? .extract(py) }) } pub fn lookup_tag(&self, tag: &str) -> Result { Ok(Python::with_gil(|py| { self.0 .call_method1(py, "lookup_tag", (tag,))? .extract(py) })?) } pub fn has_tag(&self, tag: &str) -> bool { Python::with_gil(|py| { self.0 .call_method1(py, "has_tag", (tag,)).unwrap() .extract(py).unwrap() }) } pub fn set_tag(&self, tag: &str, revision_id: &RevisionId) -> Result<(), Error> { Python::with_gil(|py| { self.0 .call_method1(py, "set_tag", (tag, revision_id.to_object(py))) })?; Ok(()) } pub fn delete_tag(&self, tag: &str) -> Result<(), Error> { Python::with_gil(|py| { self.0 .call_method1(py, "delete_tag", (tag,)) })?; Ok(()) } } breezyshim-0.1.78/src/transform.rs000064400000000000000000000040761046102023000152610ustar 00000000000000use pyo3::prelude::*; use crate::tree::Tree; pub struct TreeTransform(PyObject); #[derive(Clone)] pub struct TreeChange {} impl From for TreeChange { fn from(_ob: PyObject) -> Self { TreeChange {} } } impl FromPyObject<'_> for TreeChange { fn extract(_ob: &PyAny) -> PyResult { Ok(TreeChange {}) } } #[derive(Clone)] pub struct Conflict(PyObject); pub struct PreviewTree(PyObject); impl ToPyObject for PreviewTree { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl From for PreviewTree { fn from(ob: PyObject) -> Self { PreviewTree(ob) } } impl Tree for PreviewTree {} impl TreeTransform { pub fn iter_changes(&self) -> PyResult>> { let mut v: Vec = vec![]; Python::with_gil(|py| { let ret = self.to_object(py).call_method0(py, "iter_changes")?; for item in ret.as_ref(py).iter()? { v.push(item?.extract()?); } Ok(Box::new(v.into_iter()) as Box>) }) } pub fn cooked_conflicts(&self) -> PyResult> { let mut v: Vec = vec![]; Python::with_gil(|py| { let ret = self.to_object(py).getattr(py, "cooked_conflicts")?; for item in ret.as_ref(py).iter()? { v.push(Conflict(item?.into())); } Ok(v) }) } pub fn get_preview_tree(&self) -> PyResult { Python::with_gil(|py| { let ret = self.to_object(py).getattr(py, "preview_tree")?; Ok(PreviewTree(ret)) }) } } impl From for TreeTransform { fn from(ob: PyObject) -> Self { TreeTransform(ob) } } impl ToPyObject for TreeTransform { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for TreeTransform { fn extract(ob: &PyAny) -> PyResult { Ok(TreeTransform(ob.into())) } } breezyshim-0.1.78/src/transport.rs000064400000000000000000000045031046102023000152750ustar 00000000000000use pyo3::prelude::*; use pyo3::types::PyDict; pub struct Transport(PyObject); impl Transport { pub fn new(obj: PyObject) -> Self { Transport(obj) } pub fn base(&self) -> url::Url { pyo3::Python::with_gil(|py| { self.to_object(py) .getattr(py, "base") .unwrap() .extract::(py) .unwrap() .parse() .unwrap() }) } pub fn is_local(&self) -> bool { pyo3::import_exception!(breezy.errors, NotLocalUrl); pyo3::Python::with_gil(|py| { self.0 .call_method1(py, "local_abspath", (".",)) .map(|_| true) .or_else(|e| { if e.is_instance_of::(py) { Ok::<_, PyErr>(false) } else { panic!("Unexpected error: {:?}", e) } }) .unwrap() }) } } impl FromPyObject<'_> for Transport { fn extract(obj: &PyAny) -> PyResult { Ok(Transport(obj.to_object(obj.py()))) } } impl ToPyObject for Transport { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } #[derive(Debug)] pub enum Error { Python(PyErr), } impl From for Error { fn from(e: PyErr) -> Self { Error::Python(e) } } impl From for PyErr { fn from(e: Error) -> Self { match e { Error::Python(e) => e, } } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::Python(e) => e.fmt(f), } } } impl std::error::Error for Error {} pub fn get_transport( url: &url::Url, possible_transports: Option<&mut Vec>, ) -> Result { pyo3::Python::with_gil(|py| { let urlutils = py.import("breezy.transport").unwrap(); let kwargs = PyDict::new(py); kwargs.set_item( "possible_transports", possible_transports.map(|t| t.iter().map(|t| t.0.clone()).collect::>()), )?; let o = urlutils.call_method("get_transport", (url.to_string(),), Some(kwargs))?; Ok(Transport(o.to_object(py))) }) } breezyshim-0.1.78/src/tree.rs000064400000000000000000000642701046102023000142070ustar 00000000000000use crate::branch::{Branch, RegularBranch}; use crate::controldir::ControlDir; use crate::lock::Lock; use crate::revisionid::RevisionId; use pyo3::import_exception; use pyo3::prelude::*; import_exception!(breezy.commit, PointlessCommit); import_exception!(breezy.errors, NotBranchError); import_exception!(breezy.errors, DependencyNotPresent); import_exception!(breezy.transport, NoSuchFile); pub type Path = std::path::Path; pub type PathBuf = std::path::PathBuf; #[derive(Debug, PartialEq)] pub enum Kind { File, Directory, Symlink, TreeReference, } impl Kind { pub fn marker(&self) -> &'static str { match self { Kind::File => "", Kind::Directory => "/", Kind::Symlink => "@", Kind::TreeReference => "+", } } pub fn to_string(&self) -> &'static str { match self { Kind::File => "file", Kind::Directory => "directory", Kind::Symlink => "symlink", Kind::TreeReference => "tree-reference", } } } impl pyo3::ToPyObject for Kind { fn to_object(&self, py: pyo3::Python) -> pyo3::PyObject { match self { Kind::File => "file".to_object(py), Kind::Directory => "directory".to_object(py), Kind::Symlink => "symlink".to_object(py), Kind::TreeReference => "tree-reference".to_object(py), } } } impl pyo3::FromPyObject<'_> for Kind { fn extract(ob: &pyo3::PyAny) -> pyo3::PyResult { let s: String = ob.extract()?; match s.as_str() { "file" => Ok(Kind::File), "directory" => Ok(Kind::Directory), "symlink" => Ok(Kind::Symlink), "tree-reference" => Ok(Kind::TreeReference), _ => Err(pyo3::exceptions::PyValueError::new_err(format!( "Invalid kind: {}", s ))), } } } pub enum TreeEntry { File { executable: bool, kind: Kind, revision: Option, size: u64, }, Directory { revision: Option, }, Symlink { revision: Option, symlink_target: String, }, TreeReference { revision: Option, reference_revision: RevisionId, }, } impl FromPyObject<'_> for TreeEntry { fn extract(ob: &PyAny) -> PyResult { match ob.getattr("kind")?.extract()? { "file" => { let executable: bool = ob.getattr("executable")?.extract()?; let kind: Kind = ob.getattr("kind")?.extract()?; let size: u64 = ob.getattr("size")?.extract()?; let revision: Option = ob.getattr("revision")?.extract()?; Ok(TreeEntry::File { executable, kind, size, revision, }) } "directory" => { let revision: Option = ob.getattr("revision")?.extract()?; Ok(TreeEntry::Directory { revision }) } "symlink" => { let revision: Option = ob.getattr("revision")?.extract()?; let symlink_target: String = ob.getattr("symlink_target")?.extract()?; Ok(TreeEntry::Symlink { revision, symlink_target, }) } "tree-reference" => { let revision: Option = ob.getattr("revision")?.extract()?; let reference_revision: RevisionId = ob.getattr("reference_revision")?.extract()?; Ok(TreeEntry::TreeReference { revision, reference_revision, }) } kind => panic!("Invalid kind: {}", kind), } } } #[derive(Debug)] pub enum Error { NoSuchFile(PathBuf), Other(PyErr), } impl std::error::Error for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::NoSuchFile(path) => write!(f, "No such file: {}", path.to_string_lossy()), Error::Other(e) => write!(f, "{}", e), } } } impl From for Error { fn from(e: PyErr) -> Self { Python::with_gil(|py| { if e.is_instance_of::(py) { return Error::NoSuchFile(e.value(py).getattr("path").unwrap().extract().unwrap()); } Error::Other(e) }) } } impl From for PyErr { fn from(e: Error) -> Self { match e { Error::NoSuchFile(path) => NoSuchFile::new_err(path.to_string_lossy().to_string()), Error::Other(e) => e, } } } pub trait Tree: ToPyObject { fn get_tag_dict(&self) -> Result, PyErr> { Python::with_gil(|py| { let branch = self.to_object(py).getattr(py, "branch")?; let tags = branch.getattr(py, "tags")?; let tag_dict = tags.call_method0(py, "get_tag_dict")?; tag_dict.extract(py) }) } fn get_file(&self, path: &Path) -> Result, Error> { Python::with_gil(|py| { let f = self.to_object(py).call_method1(py, "get_file", (path,))?; let f = pyo3_filelike::PyBinaryFile::from(f); Ok(Box::new(f) as Box) }) } fn get_file_text(&self, path: &Path) -> Result, Error> { Python::with_gil(|py| { let text = self .to_object(py) .call_method1(py, "get_file_text", (path,))?; text.extract(py).map_err(|e| e.into()) }) } fn get_file_lines(&self, path: &Path) -> Result>, Error> { Python::with_gil(|py| { let lines = self .to_object(py) .call_method1(py, "get_file_lines", (path,))?; lines.extract(py).map_err(|e| e.into()) }) } fn lock_read(&self) -> Result { Python::with_gil(|py| { let lock = self.to_object(py).call_method0(py, "lock_read")?; Ok(Lock::from(lock)) }) } fn has_filename(&self, path: &Path) -> bool { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "has_filename", (path,)) .unwrap() .extract(py) .unwrap() }) } fn get_parent_ids(&self) -> Result, Error> { Python::with_gil(|py| { Ok(self .to_object(py) .call_method0(py, "get_parent_ids") .unwrap() .extract(py)?) }) } fn is_ignored(&self, path: &Path) -> Option { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "is_ignored", (path,)) .unwrap() .extract(py) .unwrap() }) } fn is_versioned(&self, path: &Path) -> bool { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "is_versioned", (path,)) .unwrap() .extract(py) .unwrap() }) } fn iter_changes( &self, other: &dyn Tree, specific_files: Option<&[&Path]>, want_unversioned: Option, require_versioned: Option, ) -> Result>>, Error> { Python::with_gil(|py| { let kwargs = pyo3::types::PyDict::new(py); if let Some(specific_files) = specific_files { kwargs.set_item("specific_files", specific_files)?; } if let Some(want_unversioned) = want_unversioned { kwargs.set_item("want_unversioned", want_unversioned)?; } if let Some(require_versioned) = require_versioned { kwargs.set_item("require_versioned", require_versioned)?; } struct TreeChangeIter(pyo3::PyObject); impl Iterator for TreeChangeIter { type Item = Result; fn next(&mut self) -> Option { Python::with_gil(|py| { let next = match self.0.call_method0(py, "__next__") { Ok(v) => v, Err(e) => { if e.is_instance_of::(py) { return None; } return Some(Err(e.into())); } }; if next.is_none(py) { None } else { Some(next.extract(py).map_err(|e| e.into())) } }) } } Ok(Box::new(TreeChangeIter(self.to_object(py).call_method( py, "iter_changes", (other.to_object(py),), Some(kwargs), )?)) as Box>>) }) } fn has_versioned_directories(&self) -> bool { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "has_versioned_directories") .unwrap() .extract(py) .unwrap() }) } fn preview_transform(&self) -> Result { Python::with_gil(|py| { let transform = self.to_object(py).call_method0(py, "preview_transform")?; Ok(crate::transform::TreeTransform::from(transform)) }) } fn list_files( &self, include_root: Option, from_dir: Option<&Path>, recursive: Option, recurse_nested: Option, ) -> Result>>, Error> { Python::with_gil(|py| { let kwargs = pyo3::types::PyDict::new(py); if let Some(include_root) = include_root { kwargs.set_item("include_root", include_root)?; } if let Some(from_dir) = from_dir { kwargs.set_item("from_dir", from_dir)?; } if let Some(recursive) = recursive { kwargs.set_item("recursive", recursive)?; } if let Some(recurse_nested) = recurse_nested { kwargs.set_item("recurse_nested", recurse_nested)?; } struct ListFilesIter(pyo3::PyObject); impl Iterator for ListFilesIter { type Item = Result<(PathBuf, bool, Kind, TreeEntry), Error>; fn next(&mut self) -> Option { Python::with_gil(|py| { let next = match self.0.call_method0(py, "__next__") { Ok(v) => v, Err(e) => { if e.is_instance_of::(py) { return None; } return Some(Err(e.into())); } }; if next.is_none(py) { None } else { Some(next.extract(py).map_err(|e| e.into())) } }) } } Ok(Box::new(ListFilesIter(self.to_object(py).call_method( py, "list_files", (), Some(kwargs), )?)) as Box< dyn Iterator>, >) }) .map_err(|e: PyErr| -> Error { e.into() }) } fn iter_child_entries( &self, path: &std::path::Path, ) -> Result>>, Error> { Python::with_gil(|py| { struct IterChildEntriesIter(pyo3::PyObject); impl Iterator for IterChildEntriesIter { type Item = Result<(PathBuf, Kind, TreeEntry), Error>; fn next(&mut self) -> Option { Python::with_gil(|py| { let next = match self.0.call_method0(py, "__next__") { Ok(v) => v, Err(e) => { if e.is_instance_of::(py) { return None; } return Some(Err(e.into())); } }; if next.is_none(py) { None } else { Some(next.extract(py).map_err(|e| e.into())) } }) } } Ok( Box::new(IterChildEntriesIter(self.to_object(py).call_method1( py, "iter_child_entries", (path,), )?)) as Box>>, ) }) } } pub trait MutableTree: Tree { fn lock_write(&self) -> Result { Python::with_gil(|py| { let lock = self.to_object(py).call_method0(py, "lock_write").unwrap(); Ok(Lock::from(lock)) }) } fn put_file_bytes_non_atomic(&self, path: &Path, data: &[u8]) -> Result<(), Error> { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "put_file_bytes_non_atomic", (path, data))?; Ok(()) }) } fn has_changes(&self) -> std::result::Result { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "has_changes")? .extract::(py) .map_err(|e| e.into()) }) } fn mkdir(&self, path: &Path) -> Result<(), Error> { Python::with_gil(|py| -> Result<(), PyErr> { self.to_object(py).call_method1(py, "mkdir", (path,))?; Ok(()) }) .map_err(|e| e.into()) } } pub struct RevisionTree(pub PyObject); impl ToPyObject for RevisionTree { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Tree for RevisionTree {} #[derive(Debug)] pub enum CommitError { PointlessCommit, Other(PyErr), } impl std::fmt::Display for CommitError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { CommitError::PointlessCommit => write!(f, "Pointless commit"), CommitError::Other(e) => write!(f, "Other error: {}", e), } } } impl std::error::Error for CommitError {} pub struct WorkingTree(pub PyObject); impl ToPyObject for WorkingTree { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } #[derive(Debug)] pub enum WorkingTreeOpenError { NotBranchError(String), DependencyNotPresent(String, String), Other(PyErr), } impl From for WorkingTreeOpenError { fn from(err: PyErr) -> Self { Python::with_gil(|py| { if err.is_instance_of::(py) { let l = err .value(py) .getattr("path") .unwrap() .extract::() .unwrap(); WorkingTreeOpenError::NotBranchError(l) } else if err.is_instance_of::(py) { let l = err .value(py) .getattr("library") .unwrap() .extract::() .unwrap(); let e = err .value(py) .getattr("error") .unwrap() .extract::() .unwrap(); WorkingTreeOpenError::DependencyNotPresent(l, e) } else { WorkingTreeOpenError::Other(err) } }) } } impl From for PyErr { fn from(err: WorkingTreeOpenError) -> Self { match err { WorkingTreeOpenError::NotBranchError(l) => NotBranchError::new_err((l,)), WorkingTreeOpenError::DependencyNotPresent(d, e) => { DependencyNotPresent::new_err((d, e)) } WorkingTreeOpenError::Other(err) => err, } } } impl std::fmt::Display for WorkingTreeOpenError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { WorkingTreeOpenError::NotBranchError(l) => write!(f, "Not branch error: {}", l), WorkingTreeOpenError::DependencyNotPresent(d, e) => { write!(f, "Dependency not present: {} {}", d, e) } WorkingTreeOpenError::Other(e) => write!(f, "Other error: {}", e), } } } impl std::error::Error for WorkingTreeOpenError {} impl WorkingTree { /// Return the base path for this working tree. pub fn basedir(&self) -> PathBuf { Python::with_gil(|py| { self.to_object(py) .getattr(py, "basedir") .unwrap() .extract(py) .unwrap() }) } /// Return the branch for this working tree. pub fn branch(&self) -> Box { Python::with_gil(|py| { let branch = self.to_object(py).getattr(py, "branch").unwrap(); Box::new(RegularBranch::new(branch)) as Box }) } /// Return the control directory for this working tree. pub fn controldir(&self) -> ControlDir { Python::with_gil(|py| { let controldir = self.to_object(py).getattr(py, "controldir").unwrap(); ControlDir::new(controldir) }) } pub fn open(path: &Path) -> Result { Python::with_gil(|py| { let m = py.import("breezy.workingtree")?; let c = m.getattr("WorkingTree")?; let wt = c.call_method1("open", (path,))?; Ok(WorkingTree(wt.to_object(py))) }) } pub fn open_containing(path: &Path) -> Result<(WorkingTree, PathBuf), WorkingTreeOpenError> { Python::with_gil(|py| { let m = py.import("breezy.workingtree")?; let c = m.getattr("WorkingTree")?; let (wt, p): (&PyAny, String) = c.call_method1("open_containing", (path,))?.extract()?; Ok((WorkingTree(wt.to_object(py)), PathBuf::from(p))) }) } pub fn basis_tree(&self) -> Box { Python::with_gil(|py| { let tree = self.to_object(py).call_method0(py, "basis_tree").unwrap(); Box::new(RevisionTree(tree)) }) } pub fn revision_tree(&self, revision_id: &RevisionId) -> Box { Python::with_gil(|py| { let tree = self .to_object(py) .call_method1(py, "revision_tree", (revision_id.to_object(py),)) .unwrap(); Box::new(RevisionTree(tree)) }) } pub fn get_tag_dict(&self) -> Result, PyErr> { Python::with_gil(|py| { let branch = self.to_object(py).getattr(py, "branch")?; let tags = branch.getattr(py, "tags")?; let tag_dict = tags.call_method0(py, "get_tag_dict")?; tag_dict.extract(py) }) } pub fn abspath(&self, path: &Path) -> Result { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1(py, "abspath", (path,))? .extract(py)?) }) } pub fn relpath(&self, path: &Path) -> Result { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1(py, "relpath", (path,))? .extract(py)?) }) } pub fn supports_setting_file_ids(&self) -> bool { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "supports_setting_file_ids") .unwrap() .extract(py) .unwrap() }) } pub fn add(&self, paths: &[&Path]) -> Result<(), Error> { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "add", (paths.to_vec(),)) }) .map_err(|e| e.into()) .map(|_| ()) } pub fn smart_add(&self, paths: &[&Path]) -> Result<(), Error> { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "smart_add", (paths.to_vec(),)) }) .map_err(|e| e.into()) .map(|_| ()) } pub fn commit( &self, message: &str, allow_pointless: Option, committer: Option<&str>, specific_files: Option<&[&Path]>, ) -> Result { Python::with_gil(|py| { let kwargs = pyo3::types::PyDict::new(py); if let Some(committer) = committer { kwargs.set_item("committer", committer).unwrap(); } if let Some(specific_files) = specific_files { kwargs.set_item("specific_files", specific_files).unwrap(); } if let Some(allow_pointless) = allow_pointless { kwargs.set_item("allow_pointless", allow_pointless).unwrap(); } let null_commit_reporter = py .import("breezy.commit") .unwrap() .getattr("NullCommitReporter") .unwrap() .call0() .unwrap(); kwargs.set_item("reporter", null_commit_reporter).unwrap(); Ok(self .to_object(py) .call_method(py, "commit", (message,), Some(kwargs)) .map_err(|e| { if e.is_instance_of::(py) { CommitError::PointlessCommit } else { CommitError::Other(e) } })? .extract(py) .unwrap()) }) } pub fn last_revision(&self) -> Result { Python::with_gil(|py| { let last_revision = self.to_object(py).call_method0(py, "last_revision")?; Ok(RevisionId::from(last_revision.extract::>(py)?)) }) } pub fn pull(&self, source: &dyn crate::branch::Branch) -> Result<(), Error> { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "pull", (source.to_object(py),)) }) .map_err(|e| e.into()) .map(|_| ()) } } impl From for WorkingTree { fn from(obj: PyObject) -> Self { WorkingTree(obj) } } impl Tree for WorkingTree {} impl MutableTree for WorkingTree {} #[derive(Debug, PartialEq, Eq, Clone)] pub struct TreeChange { pub path: (Option, Option), pub changed_content: bool, pub versioned: (Option, Option), pub name: (Option, Option), pub kind: (Option, Option), pub executable: (Option, Option), pub copied: bool, } impl ToPyObject for TreeChange { fn to_object(&self, py: Python) -> PyObject { let dict = pyo3::types::PyDict::new(py); dict.set_item("path", &self.path).unwrap(); dict.set_item("changed_content", self.changed_content) .unwrap(); dict.set_item("versioned", self.versioned).unwrap(); dict.set_item("name", &self.name).unwrap(); dict.set_item("kind", &self.kind).unwrap(); dict.set_item("executable", self.executable).unwrap(); dict.set_item("copied", self.copied).unwrap(); dict.into() } } impl FromPyObject<'_> for TreeChange { fn extract(obj: &PyAny) -> PyResult { fn from_bool(o: &PyAny) -> PyResult { if let Ok(b) = o.extract::() { Ok(b != 0) } else { o.extract::() } } fn from_opt_bool_tuple(o: &PyAny) -> PyResult<(Option, Option)> { let tuple = o.extract::<(Option<&PyAny>, Option<&PyAny>)>()?; Ok(( tuple.0.map(from_bool).transpose()?, tuple.1.map(from_bool).transpose()?, )) } let path = obj.getattr("path")?; let changed_content = from_bool(obj.getattr("changed_content")?)?; let versioned = from_opt_bool_tuple(obj.getattr("versioned")?)?; let name = obj.getattr("name")?; let kind = obj.getattr("kind")?; let executable = from_opt_bool_tuple(obj.getattr("executable")?)?; let copied = obj.getattr("copied")?; Ok(TreeChange { path: path.extract()?, changed_content, versioned, name: name.extract()?, kind: kind.extract()?, executable, copied: copied.extract()?, }) } } pub struct MemoryTree(pub PyObject); impl ToPyObject for MemoryTree { fn to_object(&self, _py: Python) -> PyObject { self.0.clone() } } impl From<&dyn Branch> for MemoryTree { fn from(branch: &dyn Branch) -> Self { Python::with_gil(|py| { MemoryTree( branch .to_object(py) .call_method0(py, "create_memorytree") .unwrap() .extract(py) .unwrap(), ) }) } } impl Tree for MemoryTree {} impl MutableTree for MemoryTree {} breezyshim-0.1.78/src/urlutils.rs000064400000000000000000000017131046102023000151240ustar 00000000000000pub fn join_segment_parameters( url: &url::Url, parameters: std::collections::HashMap, ) -> url::Url { pyo3::Python::with_gil(|py| { let urlutils = py.import("breezy.urlutils").unwrap(); urlutils .call_method1("join_segment_parameters", (url.to_string(), parameters)) .unwrap() .extract::() .map(|s| url::Url::parse(s.as_str()).unwrap()) .unwrap() }) } pub fn split_segment_parameters( url: &url::Url, ) -> (url::Url, std::collections::HashMap) { pyo3::Python::with_gil(|py| { let urlutils = py.import("breezy.urlutils").unwrap(); urlutils .call_method1("split_segment_parameters", (url.to_string(),)) .unwrap() .extract::<(String, std::collections::HashMap)>() .map(|(s, m)| (url::Url::parse(s.as_str()).unwrap(), m)) .unwrap() }) } breezyshim-0.1.78/src/version.rs000064400000000000000000000040771046102023000147340ustar 00000000000000use pyo3::prelude::*; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum ReleaseLevel { Dev, Alpha, Beta, Candidate, Final, } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Version { major: u32, minor: u32, micro: u32, level: ReleaseLevel, serial: u32, } impl std::fmt::Display for Version { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "{}.{}.{}{}{}", self.major, self.minor, self.micro, match self.level { ReleaseLevel::Dev => "dev", ReleaseLevel::Alpha => "a", ReleaseLevel::Beta => "b", ReleaseLevel::Candidate => "rc", ReleaseLevel::Final => "", }, if self.serial > 0 { format!("{}", self.serial) } else { "".to_string() } ) } } pub fn version() -> Version { pyo3::prepare_freethreaded_python(); Python::with_gil(|py| { let m = py.import("breezy").unwrap(); let version_info = m.getattr("version_info").unwrap(); let major = version_info.get_item(0).unwrap().extract::().unwrap(); let minor = version_info.get_item(1).unwrap().extract::().unwrap(); let micro = version_info.get_item(2).unwrap().extract::().unwrap(); let level = match version_info .get_item(3) .unwrap() .extract::() .unwrap() .as_str() { "dev" => ReleaseLevel::Dev, "alpha" => ReleaseLevel::Alpha, "beta" => ReleaseLevel::Beta, "candidate" => ReleaseLevel::Candidate, "final" => ReleaseLevel::Final, _ => panic!("Invalid release level"), }; let serial = version_info.get_item(4).unwrap().extract::().unwrap(); Version { major, minor, micro, level, serial, } }) } breezyshim-0.1.78/src/workspace.rs000064400000000000000000000055651046102023000152500ustar 00000000000000use crate::dirty_tracker::DirtyTracker; use crate::tree::{Tree, WorkingTree}; use pyo3::import_exception; use pyo3::prelude::*; import_exception!(breezy.workspace, WorkspaceDirty); pub fn reset_tree( local_tree: &WorkingTree, basis_tree: Option<&dyn Tree>, subpath: Option<&std::path::Path>, dirty_tracker: Option<&DirtyTracker>, ) -> PyResult<()> { Python::with_gil(|py| { let workspace_m = py.import("breezy.workspace")?; let reset_tree = workspace_m.getattr("reset_tree")?; let local_tree: PyObject = local_tree.to_object(py); let basis_tree: Option = basis_tree.map(|o| o.to_object(py)); let dirty_tracker: Option = dirty_tracker.map(|dt| dt.to_object(py)); reset_tree.call1((local_tree, basis_tree, subpath, dirty_tracker))?; Ok(()) }) } #[derive(Debug)] pub enum CheckCleanTreeError { WorkspaceDirty(std::path::PathBuf), Python(PyErr), } impl std::fmt::Display for CheckCleanTreeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { CheckCleanTreeError::WorkspaceDirty(path) => { write!(f, "Workspace dirty at {}", path.display()) } CheckCleanTreeError::Python(e) => write!(f, "{}", e), } } } impl std::error::Error for CheckCleanTreeError {} impl From for PyErr { fn from(e: CheckCleanTreeError) -> Self { match e { CheckCleanTreeError::WorkspaceDirty(path) => { WorkspaceDirty::new_err(path.to_string_lossy().to_string()) } CheckCleanTreeError::Python(e) => e, } } } impl From for CheckCleanTreeError { fn from(e: PyErr) -> Self { Python::with_gil(|py| { if e.is_instance_of::(py) { let tree = e.value(py).getattr("tree").unwrap(); let path = e.value(py).getattr("path").unwrap(); let path = tree .call_method1("abspath", (path,)) .unwrap() .extract::() .unwrap(); CheckCleanTreeError::WorkspaceDirty(std::path::PathBuf::from(path)) } else { CheckCleanTreeError::Python(e) } }) } } pub fn check_clean_tree( local_tree: &WorkingTree, basis_tree: &dyn Tree, subpath: &std::path::Path, ) -> Result<(), CheckCleanTreeError> { Python::with_gil(|py| { let workspace_m = py.import("breezy.workspace")?; let check_clean_tree = workspace_m.getattr("check_clean_tree")?; let local_tree: PyObject = local_tree.to_object(py).clone_ref(py); let basis_tree: PyObject = basis_tree.to_object(py).clone_ref(py); check_clean_tree.call1((local_tree, basis_tree, subpath.to_path_buf()))?; Ok(()) }) }