breezyshim-0.1.227/COPYING.txt000064400000000000000000000432541046102023000140370ustar 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.227/Cargo.toml0000644000000047750000000000100114010ustar # 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.227" authors = [ "Martin Packman ", "Jelmer Vernooij ", ] build = false include = [ "src/*.rs", "Cargo.toml", "COPYING.txt", "src/*/*.rs", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Rust shim around the Breezy Python API" homepage = "https://www.breezy-vcs.org/" documentation = "https://docs.rs/breezyshim" readme = "README.md" license = "GPL-2.0+" repository = "https://code.launchpad.net/breezyshim" [lib] name = "breezyshim" path = "src/lib.rs" [dependencies.chrono] version = "0.4" [dependencies.ctor] version = ">=0.1" optional = true [dependencies.debian-changelog] version = "0.2.0" optional = true [dependencies.debian-control] version = ">= 0.1.14" features = ["python-debian"] optional = true [dependencies.debversion] version = ">=0.2" features = ["python-debian"] optional = true [dependencies.difflib] version = "0.4.0" optional = true [dependencies.dirty-tracker] version = "0.3" optional = true [dependencies.lazy-regex] version = ">=2" [dependencies.lazy_static] version = "1.4.0" [dependencies.log] version = "0.4" [dependencies.patchkit] version = "0.2" [dependencies.percent-encoding] version = "2.3.1" [dependencies.pyo3] version = "0.22" features = [ "chrono", "serde", ] [dependencies.pyo3-filelike] version = ">=0.1" [dependencies.serde] version = "1" features = ["derive"] [dependencies.sqlx] version = ">=0.8" optional = true [dependencies.tempfile] version = "3.6.0" [dependencies.url] version = "2" features = ["serde"] [dev-dependencies.maplit] version = "1" [dev-dependencies.pyo3] version = "0.22" features = ["chrono"] [dev-dependencies.serial_test] version = ">=2" default-features = false [features] auto-initialize = ["dep:ctor"] debian = [ "dep:debversion", "dep:debian-control", "dep:debian-changelog", "dep:difflib", ] default = ["auto-initialize"] dirty-tracker = ["dep:dirty-tracker"] sqlx = ["sqlx/postgres"] breezyshim-0.1.227/Cargo.toml.orig000064400000000000000000000031751046102023000150530ustar 00000000000000[package] name = "breezyshim" version = "0.1.227" 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://docs.rs/breezyshim" authors = [ "Martin Packman ", "Jelmer Vernooij ",] include = ["src/*.rs", "Cargo.toml", "COPYING.txt", "src/*/*.rs"] [dependencies] pyo3-filelike = ">=0.1" tempfile = "3.6.0" lazy_static = "1.4.0" chrono = "0.4" ctor = { version = ">=0.1", optional = true } lazy-regex = ">=2" patchkit = "0.2" log = "0.4" debian-control = { version = ">= 0.1.14", optional = true, features = ["python-debian"] } dirty-tracker = { version = "0.3", optional = true } debian-changelog = { version = "0.2.0", optional = true } difflib = { version = "0.4.0", optional = true } percent-encoding = "2.3.1" sqlx = { version = ">=0.8", optional = true } [features] default = ["auto-initialize"] debian = ["dep:debversion", "dep:debian-control", "dep:debian-changelog", "dep:difflib"] dirty-tracker = ["dep:dirty-tracker"] auto-initialize = ["dep:ctor"] sqlx = ["sqlx/postgres"] [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 = { version = "0.22", features = ["chrono"] } [dev-dependencies] maplit = "1" serial_test = { version = ">=2", default-features = false } [dev-dependencies.pyo3] workspace = true breezyshim-0.1.227/README.md000064400000000000000000000005421046102023000134360ustar 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.227/src/bazaar/mod.rs000064400000000000000000000063121046102023000153340ustar 00000000000000//! Bazaar-specific functionality. use crate::controldir::Prober; use pyo3::exceptions::PyModuleNotFoundError; use pyo3::prelude::*; pub mod tree; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FileId(Vec); impl Default for FileId { fn default() -> Self { Self::new() } } 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_bound(ob: &Bound) -> 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) } } pub fn gen_revision_id(username: &str, timestamp: Option) -> Vec { Python::with_gil(|py| { let m = py.import_bound("breezy.bzr.generate_ids").unwrap(); let gen_revision_id = m.getattr("gen_revision_id").unwrap(); gen_revision_id .call1((username, timestamp)) .unwrap() .extract() .unwrap() }) } #[test] fn test_gen_revision_id() { gen_revision_id("user", None); } pub fn gen_file_id(name: &str) -> Vec { Python::with_gil(|py| { let m = py.import_bound("breezy.bzr.generate_ids").unwrap(); let gen_file_id = m.getattr("gen_file_id").unwrap(); gen_file_id.call1((name,)).unwrap().extract().unwrap() }) } #[test] fn test_file_id() { gen_file_id("somename"); } pub struct RemoteBzrProber(PyObject); impl RemoteBzrProber { pub fn new() -> Option { Python::with_gil(|py| { let m = match py.import_bound("breezy.bzr") { Ok(m) => m, Err(e) => { if e.is_instance_of::(py) { return None; } else { e.print_and_set_sys_last_vars(py); panic!("Failed to import breezy.bzr"); } } }; let prober = m .getattr("RemoteBzrProber") .expect("Failed to get RemoteBzrProber"); Some(Self(prober.to_object(py))) }) } } impl FromPyObject<'_> for RemoteBzrProber { fn extract_bound(obj: &Bound) -> PyResult { Ok(Self(obj.to_object(obj.py()))) } } impl ToPyObject for RemoteBzrProber { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Prober for RemoteBzrProber {} breezyshim-0.1.227/src/bazaar/tree.rs000064400000000000000000000010051046102023000155060ustar 00000000000000//! Inventory trees use crate::error::Error; use crate::tree::{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.227/src/branch.rs000064400000000000000000000306541046102023000145600ustar 00000000000000//! Branches are the primary way to interact with the history of a project in Breezy. //! //! A branch is a named sequence of revisions. Each revision is a snapshot of the project at a //! particular point in time. Revisions are linked together in a chain, forming a history of the //! project. The branch itself is a pointer to the most recent revision in the chain. //! Branches can be pushed to and pulled from other branches, allowing changes to be shared between //! different branches. //! //! Breezy supports several different types of branches, each with different capabilities and //! constraints. use crate::controldir::ControlDir; use crate::error::Error; use crate::foreign::VcsType; use crate::lock::Lock; use crate::repository::Repository; use crate::revisionid::RevisionId; use pyo3::prelude::*; use pyo3::types::PyDict; pub struct BranchFormat(PyObject); impl Clone for BranchFormat { fn clone(&self) -> Self { Python::with_gil(|py| BranchFormat(self.0.clone_ref(py))) } } 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 vcs_type(&self) -> VcsType { self.repository().vcs_type() } fn revno(&self) -> u32 { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "revno") .unwrap() .extract(py) .unwrap() }) } fn lock_read(&self) -> Result { Python::with_gil(|py| { Ok(Lock::from( self.to_object(py).call_method0(py, "lock_read")?, )) }) } fn lock_write(&self) -> Result { Python::with_gil(|py| { Ok(Lock::from( self.to_object(py).call_method0(py, "lock_write")?, )) }) } fn tags(&self) -> Result { 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) -> Result { 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>>, ) -> Result<(), crate::error::Error> { Python::with_gil(|py| { let kwargs = PyDict::new_bound(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_bound( py, "push", (&remote_branch.to_object(py),), Some(&kwargs), )?; Ok(()) }) } fn pull(&self, source_branch: &dyn Branch, overwrite: Option) -> Result<(), Error> { Python::with_gil(|py| { let kwargs = PyDict::new_bound(py); if let Some(overwrite) = overwrite { kwargs.set_item("overwrite", overwrite)?; } self.to_object(py).call_method_bound( py, "pull", (&source_branch.to_object(py),), Some(&kwargs), )?; Ok(()) }) } fn get_parent(&self) -> Option { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "get_parent") .unwrap() .extract(py) .unwrap() }) } fn set_parent(&mut self, parent: &str) { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "set_parent", (parent,)) .unwrap(); }) } 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(), ) }) } fn get_config(&self) -> crate::config::BranchConfig { Python::with_gil(|py| { crate::config::BranchConfig::new( self.to_object(py).call_method0(py, "get_config").unwrap(), ) }) } fn get_config_stack(&self) -> crate::config::ConfigStack { Python::with_gil(|py| { crate::config::ConfigStack::new( self.to_object(py) .call_method0(py, "get_config_stack") .unwrap(), ) }) } fn sprout(&self, to_controldir: &ControlDir, to_branch_name: &str) -> Result<(), Error> { Python::with_gil(|py| { let kwargs = PyDict::new_bound(py); kwargs.set_item("name", to_branch_name)?; self.to_object(py).call_method_bound( py, "sprout", (to_controldir.to_object(py),), Some(&kwargs), )?; Ok(()) }) } fn create_checkout( &self, to_location: &std::path::Path, ) -> Result { Python::with_gil(|py| { self.to_object(py) .call_method1( py, "create_checkout", (to_location.to_string_lossy().to_string(),), ) .map(crate::tree::WorkingTree) .map_err(|e| e.into()) }) } fn generate_revision_history(&self, last_revision: &RevisionId) -> Result<(), Error> { Python::with_gil(|py| { self.to_object(py).call_method1( py, "generate_revision_history", (last_revision.to_object(py),), )?; Ok(()) }) } } pub struct GenericBranch(PyObject); impl Clone for GenericBranch { fn clone(&self) -> Self { Python::with_gil(|py| GenericBranch(self.0.clone_ref(py))) } } impl Branch for GenericBranch {} impl ToPyObject for GenericBranch { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl GenericBranch { pub fn new(obj: PyObject) -> Self { GenericBranch(obj) } } impl FromPyObject<'_> for GenericBranch { fn extract_bound(ob: &Bound) -> PyResult { Ok(GenericBranch(ob.to_object(ob.py()))) } } pub struct MemoryBranch(PyObject); impl Clone for MemoryBranch { fn clone(&self) -> Self { Python::with_gil(|py| MemoryBranch(self.0.clone_ref(py))) } } 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) -> Self { Python::with_gil(|py| { let mb_cls = py .import_bound("breezy.memorybranch") .unwrap() .getattr("MemoryBranch") .unwrap(); let o = mb_cls .call1((repository.to_object(py), (revno, revid.clone()))) .unwrap(); 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, Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.branch").unwrap(); let c = m.getattr("Branch").unwrap(); let r = c.call_method1("open", (url.to_string(),))?; Ok(Box::new(GenericBranch(r.to_object(py))) as Box) }) } pub fn open_containing(url: &url::Url) -> Result<(Box, String), Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.branch").unwrap(); let c = m.getattr("Branch").unwrap(); let (b, p): (Bound, String) = c .call_method1("open_containing", (url.to_string(),))? .extract()?; Ok(( Box::new(GenericBranch(b.to_object(py))) as Box, p, )) }) } pub fn open_from_transport( transport: &crate::transport::Transport, ) -> Result, Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.branch").unwrap(); let c = m.getattr("Branch").unwrap(); let r = c.call_method1("open_from_transport", (transport.to_object(py),))?; Ok(Box::new(GenericBranch(r.to_object(py))) as Box) }) } #[cfg(test)] mod tests { use super::*; #[test] fn test_create_and_clone() { let td = tempfile::tempdir().unwrap(); let url = url::Url::from_directory_path(td.path()).unwrap(); let branch = crate::controldir::create_branch_convenience( &url, None, &crate::controldir::ControlDirFormat::default(), ) .unwrap(); assert_eq!(branch.revno(), 0); assert_eq!(branch.last_revision(), RevisionId::null()); } #[test] fn test_create_and_clone_memory() { let td = tempfile::tempdir().unwrap(); let url = url::Url::from_directory_path(td.path()).unwrap(); let branch = crate::controldir::create_branch_convenience( &url, None, &crate::controldir::ControlDirFormat::default(), ) .unwrap(); let branch = MemoryBranch::new(&branch.repository(), None, &RevisionId::null()); assert_eq!(branch.last_revision(), RevisionId::null()); } } breezyshim-0.1.227/src/clean_tree.rs000064400000000000000000000014271046102023000154200ustar 00000000000000use crate::error::Error; use pyo3::prelude::*; use pyo3::types::PyDict; use std::path::Path; pub fn clean_tree( directory: &Path, unknown: bool, ignored: bool, detritus: bool, dry_run: bool, no_prompt: bool, ) -> Result<(), Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.clean_tree")?; let f = m.getattr("clean_tree")?; let kwargs = PyDict::new_bound(py); kwargs.set_item("directory", directory.to_str().unwrap())?; kwargs.set_item("unknown", unknown)?; kwargs.set_item("ignored", ignored)?; kwargs.set_item("detritus", detritus)?; kwargs.set_item("dry_run", dry_run)?; kwargs.set_item("no_prompt", no_prompt)?; f.call((), Some(&kwargs))?; Ok(()) }) } breezyshim-0.1.227/src/commit.rs000064400000000000000000000030161046102023000146030ustar 00000000000000use pyo3::prelude::*; pub struct NullCommitReporter(PyObject); impl NullCommitReporter { pub fn new() -> Self { Python::with_gil(|py| { let m = py.import_bound("breezy.commit").unwrap(); let ncr = m.getattr("NullCommitReporter").unwrap(); NullCommitReporter(ncr.call0().unwrap().into()) }) } } impl From for NullCommitReporter { fn from(obj: PyObject) -> Self { NullCommitReporter(obj) } } impl ToPyObject for NullCommitReporter { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } pub trait CommitReporter: ToPyObject {} impl CommitReporter for NullCommitReporter {} pub struct ReportCommitToLog(PyObject); impl ReportCommitToLog { pub fn new() -> Self { Python::with_gil(|py| { let m = py.import_bound("breezy.commit").unwrap(); let rctl = m.getattr("ReportCommitToLog").unwrap(); ReportCommitToLog(rctl.call0().unwrap().into()) }) } } impl From for ReportCommitToLog { fn from(obj: PyObject) -> Self { ReportCommitToLog(obj) } } impl ToPyObject for ReportCommitToLog { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl CommitReporter for ReportCommitToLog {} #[cfg(test)] mod tests { use super::*; #[test] fn test_null_commit_reporter() { NullCommitReporter::new(); } #[test] fn test_report_commit_to_log() { ReportCommitToLog::new(); } } breezyshim-0.1.227/src/config.rs000064400000000000000000000222601046102023000145620ustar 00000000000000//! Configuration handling. //! //! This module provides access to the Breezy configuration system. //! It allows reading and writing configuration values, and provides //! access to credential stores. use crate::Result; use pyo3::prelude::*; pub fn parse_username(e: &str) -> (String, String) { if let Some((_, username, email)) = lazy_regex::regex_captures!(r"(.*?)\s*?", e) { (username.to_string(), email.to_string()) } else { (e.to_string(), "".to_string()) } } pub fn extract_email_address(e: &str) -> Option { let (_name, email) = parse_username(e); if email.is_empty() { None } else { Some(email) } } pub trait ConfigValue: ToPyObject {} impl ConfigValue for String {} impl ConfigValue for &str {} impl ConfigValue for i64 {} impl ConfigValue for bool {} pub struct BranchConfig(PyObject); impl Clone for BranchConfig { fn clone(&self) -> Self { Python::with_gil(|py| -> Self { Self(self.0.clone_ref(py)) }) } } impl ToPyObject for BranchConfig { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl BranchConfig { pub fn new(o: PyObject) -> Self { Self(o) } pub fn set_user_option(&self, key: &str, value: T) -> Result<()> { Python::with_gil(|py| -> Result<()> { self.0 .call_method1(py, "set_user_option", (key, value.to_object(py)))?; Ok(()) })?; Ok(()) } } pub struct ConfigStack(PyObject); impl ConfigStack { pub fn new(o: PyObject) -> Self { Self(o) } pub fn get(&self, key: &str) -> Result> { Python::with_gil(|py| -> Result> { let value = self.0.call_method1(py, "get", (key,))?; if value.is_none(py) { Ok(None) } else { Ok(Some(value)) } }) } pub fn set(&self, key: &str, value: T) -> Result<()> { Python::with_gil(|py| -> Result<()> { self.0.call_method1(py, "set", (key, value.to_object(py)))?; Ok(()) })?; Ok(()) } } pub fn global_stack() -> Result { Python::with_gil(|py| -> Result { let m = py.import_bound("breezy.config")?; let stack = m.call_method0("GlobalStack")?; Ok(ConfigStack::new(stack.to_object(py))) }) } pub struct Credentials { pub scheme: Option, pub username: Option, pub password: Option, pub host: Option, pub port: Option, pub path: Option, pub realm: Option, pub verify_certificates: Option, } impl FromPyObject<'_> for Credentials { fn extract_bound(ob: &Bound) -> PyResult { let scheme = ob.get_item("scheme")?.extract()?; let username = ob.get_item("username")?.extract()?; let password = ob.get_item("password")?.extract()?; let host = ob.get_item("host")?.extract()?; let port = ob.get_item("port")?.extract()?; let path = ob.get_item("path")?.extract()?; let realm = ob.get_item("realm")?.extract()?; let verify_certificates = ob.get_item("verify_certificates")?.extract()?; Ok(Credentials { scheme, username, password, host, port, path, realm, verify_certificates, }) } } impl ToPyObject for Credentials { fn to_object(&self, py: Python) -> PyObject { let dict = pyo3::types::PyDict::new_bound(py); dict.set_item("scheme", &self.scheme).unwrap(); dict.set_item("username", &self.username).unwrap(); dict.set_item("password", &self.password).unwrap(); dict.set_item("host", &self.host).unwrap(); dict.set_item("port", self.port).unwrap(); dict.set_item("path", &self.path).unwrap(); dict.set_item("realm", &self.realm).unwrap(); dict.set_item("verify_certificates", self.verify_certificates) .unwrap(); dict.into() } } impl IntoPy for Credentials { fn into_py(self, py: Python) -> PyObject { self.to_object(py) } } pub trait CredentialStore: Send { fn get_credentials( &self, scheme: &str, host: &str, port: Option, user: Option<&str>, path: Option<&str>, realm: Option<&str>, ) -> Result; } struct PyCredentialStore(PyObject); impl CredentialStore for PyCredentialStore { fn get_credentials( &self, scheme: &str, host: &str, port: Option, user: Option<&str>, path: Option<&str>, realm: Option<&str>, ) -> Result { Python::with_gil(|py| -> Result { let creds = self.0.call_method1( py, "get_credentials", (scheme, host, port, user, path, realm), )?; Ok(creds.extract(py)?) }) } } #[pyclass] pub struct CredentialStoreWrapper(Box); #[pymethods] impl CredentialStoreWrapper { #[pyo3(signature = (scheme, host, port=None, user=None, path=None, realm=None))] fn get_credentials( &self, scheme: &str, host: &str, port: Option, user: Option<&str>, path: Option<&str>, realm: Option<&str>, ) -> PyResult { self.0 .get_credentials(scheme, host, port, user, path, realm) .map_err(|e| PyErr::new::(e.to_string())) } } pub struct CredentialStoreRegistry(PyObject); impl CredentialStoreRegistry { pub fn new() -> Self { Python::with_gil(|py| -> Self { let m = py.import_bound("breezy.config").unwrap(); let registry = m.call_method0("CredentialStoreRegistry").unwrap(); Self(registry.to_object(py)) }) } pub fn get_credential_store( &self, encoding: Option<&str>, ) -> Result>> { Python::with_gil(|py| -> Result>> { let store = match self.0.call_method1(py, "get_credential_store", (encoding,)) { Ok(store) => store, Err(e) if e.is_instance_of::(py) => { return Ok(None); } Err(e) => { return Err(e.into()); } }; Ok(Some(Box::new(PyCredentialStore(store)))) }) } pub fn get_fallback_credentials( &self, scheme: &str, port: Option, user: Option<&str>, path: Option<&str>, realm: Option<&str>, ) -> Result { Python::with_gil(|py| -> Result { let creds = self.0.call_method1( py, "get_fallback_credentials", (scheme, port, user, path, realm), )?; Ok(creds.extract(py)?) }) } pub fn register(&self, key: &str, store: Box) -> Result<()> { Python::with_gil(|py| -> Result<()> { self.0 .call_method1(py, "register", (key, CredentialStoreWrapper(store)))?; Ok(()) })?; Ok(()) } pub fn register_fallback(&self, store: Box) -> Result<()> { Python::with_gil(|py| -> Result<()> { let kwargs = pyo3::types::PyDict::new_bound(py); kwargs.set_item("fallback", true)?; self.0.call_method_bound( py, "register_fallback", (CredentialStoreWrapper(store),), Some(&kwargs), )?; Ok(()) })?; Ok(()) } } lazy_static::lazy_static! { pub static ref CREDENTIAL_STORE_REGISTRY: CredentialStoreRegistry = CredentialStoreRegistry::new() ; } #[cfg(test)] mod tests { #[test] fn test_credential_store() { fn takes_config_value(_t: T) {} takes_config_value("foo"); takes_config_value(1); takes_config_value(true); takes_config_value("foo".to_string()); } use super::*; use serial_test::serial; #[test] #[serial] fn test_config_stack() { let env = crate::testing::TestEnv::new(); let stack = global_stack().unwrap(); stack.get("email").unwrap(); std::mem::drop(env); } #[test] fn test_parse_username() { assert_eq!( parse_username("John Doe "), ("John Doe".to_string(), "joe@example.com".to_string()) ); assert_eq!( parse_username("John Doe"), ("John Doe".to_string(), "".to_string()) ); } #[test] fn test_extract_email_address() { assert_eq!( extract_email_address("John Doe "), Some("joe@example.com".to_string()) ); assert_eq!(extract_email_address("John Doe"), None); } } breezyshim-0.1.227/src/controldir.rs000064400000000000000000000606611046102023000155030ustar 00000000000000//! The `ControlDir` class provides a high-level interface to control directories, //! e.g. ".bzr" or ".git" directories. use crate::branch::{py_tag_selector, Branch, GenericBranch}; use crate::error::Error; use crate::repository::Repository; use crate::transport::Transport; use crate::tree::WorkingTree; use crate::location::AsLocation; use pyo3::prelude::*; use pyo3::types::PyDict; pub trait Prober: ToPyObject {} 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_bound(obj: &Bound) -> PyResult { Ok(ControlDir(obj.to_object(obj.py()))) } } impl ControlDir { pub fn new(obj: PyObject) -> Self { Self(obj) } pub fn get_user_url(&self) -> url::Url { Python::with_gil(|py| { let result = self.to_object(py).getattr(py, "user_url").unwrap(); url::Url::parse(&result.extract::(py).unwrap()).unwrap() }) } pub fn get_format(&self) -> ControlDirFormat { Python::with_gil(|py| { let result = self.to_object(py).getattr(py, "_format")?; Ok::<_, PyErr>(ControlDirFormat(result)) }) .unwrap() } pub fn user_transport(&self) -> Transport { Python::with_gil(|py| { let result = self.to_object(py).getattr(py, "user_transport").unwrap(); crate::transport::Transport::new(result) }) } pub fn control_transport(&self) -> Transport { Python::with_gil(|py| { let result = self.to_object(py).getattr(py, "control_transport").unwrap(); crate::transport::Transport::new(result) }) } pub fn open_repository(&self) -> Result { Python::with_gil(|py| { let result = self.to_object(py).call_method0(py, "open_repository")?; Ok(Repository::new(result)) }) } pub fn find_repository(&self) -> Result { Python::with_gil(|py| { let result = self.to_object(py).call_method0(py, "find_repository")?; Ok(Repository::new(result)) }) } 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() } pub fn create_branch(&self, name: Option<&str>) -> Result, Error> { Python::with_gil(|py| { let branch = self .to_object(py) .call_method_bound(py, "create_branch", (name,), None)? .extract(py)?; Ok(Box::new(GenericBranch::new(branch)) as Box) }) } pub fn create_repository(&self, shared: Option) -> Result { Python::with_gil(|py| { let kwargs = PyDict::new_bound(py); if let Some(shared) = shared { kwargs.set_item("shared", shared)?; } let repository = self .to_object(py) .call_method_bound(py, "create_repository", (), Some(&kwargs))? .extract(py)?; Ok(Repository::new(repository)) }) } pub fn open_branch(&self, branch_name: Option<&str>) -> Result, Error> { Python::with_gil(|py| { let branch = self .to_object(py) .call_method_bound(py, "open_branch", (branch_name,), None)? .extract(py)?; Ok(Box::new(GenericBranch::new(branch)) as Box) }) } pub fn create_workingtree(&self) -> crate::Result { Python::with_gil(|py| { let wt = self .to_object(py) .call_method0(py, "create_workingtree")? .extract(py)?; Ok(WorkingTree(wt)) }) } pub fn set_branch_reference( &self, branch: &dyn Branch, name: Option<&str>, ) -> crate::Result<()> { Python::with_gil(|py| { self.to_object(py).call_method1( py, "set_branch_reference", (&branch.to_object(py), name), )?; Ok(()) }) } 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>>, ) -> crate::Result> { Python::with_gil(|py| { let kwargs = PyDict::new_bound(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_bound( py, "push_branch", (&source_branch.to_object(py),), Some(&kwargs), )?; Ok( Box::new(GenericBranch::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, revision_id: Option<&crate::RevisionId>, ) -> Result { Python::with_gil(|py| { let kwargs = PyDict::new_bound(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(); } if let Some(revision_id) = revision_id { kwargs .set_item("revision_id", revision_id.to_object(py)) .unwrap(); } let cd = self.0 .call_method_bound(py, "sprout", (target.to_string(),), Some(&kwargs))?; Ok(ControlDir(cd)) }) } pub fn has_workingtree(&self) -> bool { Python::with_gil(|py| { let result = self .to_object(py) .call_method0(py, "has_workingtree") .unwrap(); result.extract(py).unwrap() }) } pub fn open_workingtree(&self) -> crate::Result { Python::with_gil(|py| { let wt = self.0.call_method0(py, "open_workingtree")?.extract(py)?; Ok(WorkingTree(wt)) }) } pub fn branch_names(&self) -> crate::Result> { Python::with_gil(|py| { let names = self .0 .call_method0(py, "branch_names")? .extract::>(py)?; Ok(names) }) } } impl std::fmt::Debug for ControlDir { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_fmt(format_args!("ControlDir({:?})", self.0)) } } pub struct ControlDirFormat(PyObject); impl ToPyObject for ControlDirFormat { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } 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_bound(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() }) } pub fn initialize_on_transport(&self, transport: &Transport) -> Result { Python::with_gil(|py| { let cd = self.0 .call_method1(py, "initialize_on_transport", (&transport.to_object(py),))?; Ok(ControlDir(cd)) }) } pub fn initialize(&self, location: impl AsLocation) -> Result { Python::with_gil(|py| { let cd = self .0 .call_method1(py, "initialize", (location.as_location(),))?; Ok(ControlDir(cd)) }) } } pub fn open_tree_or_branch( location: impl AsLocation, name: Option<&str>, possible_transports: Option<&mut Vec>, ) -> Result<(Option, Box), Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new_bound(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_bound( py, "open_tree_or_branch", (location.as_location(), name), Some(&kwargs), )?; let (tree, branch) = ret.extract::<(Option, PyObject)>(py)?; let branch = Box::new(GenericBranch::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_bound("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new_bound(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_bound("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new_bound(py); if let Some(format) = format.as_format() { 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_bound( py, "initialize_on_transport", (&transport.to_object(py),), None, )?)) }) } pub fn open_containing_from_transport( transport: &Transport, probers: Option<&[&dyn Prober]>, ) -> Result<(ControlDir, String), Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new_bound(py); if let Some(probers) = probers { kwargs.set_item( "probers", probers.iter().map(|p| p.to_object(py)).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<&[&dyn Prober]>, ) -> Result { Python::with_gil(|py| { let m = py.import_bound("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let kwargs = PyDict::new_bound(py); if let Some(probers) = probers { kwargs.set_item( "probers", probers.iter().map(|p| p.to_object(py)).collect::>(), )?; } let controldir = cd.call_method( "open_from_transport", (&transport.to_object(py),), Some(&kwargs), )?; Ok(ControlDir(controldir.to_object(py))) }) } pub trait AsFormat { fn as_format(&self) -> Option; } impl AsFormat for &str { fn as_format(&self) -> Option { Python::with_gil(|py| { let m = py.import_bound("breezy.controldir").ok()?; let cd = m.getattr("format_registry").ok()?; let format = cd .call_method1("make_controldir", (self.to_string(),)) .ok()?; Some(ControlDirFormat(format.to_object(py))) }) } } impl AsFormat for &ControlDirFormat { fn as_format(&self) -> Option { Some(Python::with_gil(|py| { ControlDirFormat(self.0.clone_ref(py)) })) } } pub fn create_branch_convenience( base: &url::Url, force_new_tree: Option, format: impl AsFormat, ) -> Result, Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let format = format.as_format(); let kwargs = PyDict::new_bound(py); if let Some(force_new_tree) = force_new_tree { kwargs.set_item("force_new_tree", force_new_tree)?; } if let Some(format) = format { kwargs.set_item("format", format.to_object(py))?; } let branch = cd.call_method( "create_branch_convenience", (base.to_string(),), Some(&kwargs), )?; Ok(Box::new(GenericBranch::new(branch.to_object(py))) as Box) }) } /// Create a standalone working tree. /// /// # Arguments /// * `base` - The base directory for the working tree. /// * `format` - The format of the working tree. 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_bound("breezy.controldir")?; let cd = m.getattr("ControlDir")?; let format = format.as_format(); let wt = cd.call_method( "create_standalone_workingtree", (base, format.unwrap_or_default().to_object(py)), None, )?; Ok(WorkingTree(wt.to_object(py))) }) } pub fn all_probers() -> Vec> { struct PyProber(PyObject); impl ToPyObject for PyProber { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl Prober for PyProber {} Python::with_gil(|py| -> PyResult>> { let m = py.import_bound("breezy.controldir")?; let cdf = m.getattr("ControlDirFormat")?; let probers = cdf .call_method0("all_probers")? .extract::>()?; Ok(probers .into_iter() .map(|p| Box::new(PyProber(p)) as Box) .collect::>()) }) .unwrap() } pub struct ControlDirFormatRegistry(PyObject); impl ControlDirFormatRegistry { pub fn new() -> Self { Python::with_gil(|py| { let m = py.import_bound("breezy.controldir").unwrap(); let obj = m.getattr("format_registry").unwrap(); ControlDirFormatRegistry(obj.into()) }) } pub fn make_controldir(&self, format: &str) -> Option { Python::with_gil( |py| match self.0.call_method1(py, "make_controldir", (format,)) { Ok(format) => Some(ControlDirFormat(format.to_object(py))), Err(e) if e.is_instance_of::(py) => None, Err(e) => panic!("{}", e), }, ) } } impl Default for ControlDirFormatRegistry { fn default() -> Self { ControlDirFormatRegistry::new() } } lazy_static::lazy_static! { pub static ref FORMAT_REGISTRY: ControlDirFormatRegistry = ControlDirFormatRegistry::new(); } #[cfg(test)] mod tests { use super::*; #[test] fn test_control_dir_format_registry() { let registry = ControlDirFormatRegistry::new(); let format = registry.make_controldir("2a").unwrap(); let _ = format.get_format_string(); } #[test] fn test_format_registry() { let format = FORMAT_REGISTRY.make_controldir("2a").unwrap(); let _ = format.get_format_string(); } #[test] fn test_all_probers() { let probers = all_probers(); assert!(!probers.is_empty()); } #[test] fn test_open_tree_or_branch() { let tmp_dir = tempfile::tempdir().unwrap(); create_branch_convenience( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, &ControlDirFormat::default(), ) .unwrap(); let (wt, branch) = open_tree_or_branch( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, None, ) .unwrap(); assert_eq!( wt.unwrap().basedir().canonicalize().unwrap(), tmp_dir.path().canonicalize().unwrap() ); assert_eq!( branch.get_user_url(), url::Url::from_directory_path(tmp_dir.path()).unwrap() ); } #[test] fn test_control_dir_format_default() { let d = ControlDirFormat::default(); d.get_format_string(); } #[test] fn test_open() { let tmp_dir = tempfile::tempdir().unwrap(); let e = open( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, ) .unwrap_err(); assert!(matches!(e, Error::NotBranchError(..)),); let cd = create( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), "2a", None, ) .unwrap(); let od = open( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, ) .unwrap(); assert_eq!( cd.get_format().get_format_string(), od.get_format().get_format_string() ); } #[test] fn test_create() { let tmp_dir = tempfile::tempdir().unwrap(); let cd = create( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), "2a", None, ) .unwrap(); let od = open( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, ) .unwrap(); assert_eq!( cd.get_format().get_format_string(), od.get_format().get_format_string() ); } #[test] fn test_create_on_transport() { let tmp_dir = tempfile::tempdir().unwrap(); let transport = crate::transport::get_transport( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, ) .unwrap(); let _cd = create_on_transport(&transport, "2a").unwrap(); } #[test] fn test_open_containing_from_transport() { let tmp_dir = tempfile::tempdir().unwrap(); let transport = crate::transport::get_transport( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, ) .unwrap(); let e = open_containing_from_transport(&transport, None).unwrap_err(); assert!(matches!(e, Error::NotBranchError(..)),); } #[test] fn test_open_from_transport() { let tmp_dir = tempfile::tempdir().unwrap(); let transport = crate::transport::get_transport( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, ) .unwrap(); let e = open_from_transport(&transport, None).unwrap_err(); assert!(matches!(e, Error::NotBranchError(..)),); } #[test] fn test_create_standalone_workingtree() { let tmp_dir = tempfile::tempdir().unwrap(); let wt = create_standalone_workingtree(tmp_dir.path(), "2a").unwrap(); assert_eq!( wt.basedir().canonicalize().unwrap(), tmp_dir.path().canonicalize().unwrap() ); } #[test] fn test_create_branch_convenience() { let tmp_dir = tempfile::tempdir().unwrap(); let branch = create_branch_convenience( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), None, &ControlDirFormat::default(), ) .unwrap(); assert_eq!( branch.get_user_url(), url::Url::from_directory_path(tmp_dir.path()).unwrap() ); } #[test] fn test_create_repository() { let tmp_dir = tempfile::tempdir().unwrap(); let controldir = create( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), &ControlDirFormat::default(), None, ) .unwrap(); let _repo = controldir.create_repository(None).unwrap(); } #[test] fn test_create_branch() { let tmp_dir = tempfile::tempdir().unwrap(); let controldir = create( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), &ControlDirFormat::default(), None, ) .unwrap(); assert!(matches!( controldir.create_branch(None), Err(Error::NoRepositoryPresent) )); let _repo = controldir.create_repository(None).unwrap(); let _branch = controldir.create_branch(Some("foo")).unwrap(); } #[test] fn test_create_workingtree() { let tmp_dir = tempfile::tempdir().unwrap(); let controldir = create( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), &ControlDirFormat::default(), None, ) .unwrap(); controldir.create_repository(None).unwrap(); controldir.create_branch(None).unwrap(); let _wt = controldir.create_workingtree().unwrap(); } #[test] fn test_branch_names() { let tmp_dir = tempfile::tempdir().unwrap(); let controldir = create( &url::Url::from_directory_path(tmp_dir.path()).unwrap(), &ControlDirFormat::default(), None, ) .unwrap(); controldir.create_repository(None).unwrap(); controldir.create_branch(None).unwrap(); assert_eq!(controldir.branch_names().unwrap(), vec!["".to_string()]); } } breezyshim-0.1.227/src/cvs.rs000064400000000000000000000026201046102023000141060ustar 00000000000000//! Support for detecting CVS repositories. //! //! This module provides a prober for detecting CVS repositories, but //! does not provide any support for interacting with them. use crate::controldir::Prober; use pyo3::exceptions::PyModuleNotFoundError; use pyo3::prelude::*; pub struct CVSProber(PyObject); impl CVSProber { pub fn new() -> Option { Python::with_gil(|py| { let m = match py.import_bound("breezy.plugins.cvs") { Ok(m) => m, Err(e) => { if e.is_instance_of::(py) { return None; } else { e.print_and_set_sys_last_vars(py); panic!("Failed to import breezy.plugins.cvs"); } } }; let cvsprober = m.getattr("CVSProber").expect("Failed to get CVSProber"); Some(Self(cvsprober.to_object(py))) }) } } impl FromPyObject<'_> for CVSProber { fn extract_bound(obj: &Bound) -> PyResult { Ok(Self(obj.to_object(obj.py()))) } } impl ToPyObject for CVSProber { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Prober for CVSProber {} #[cfg(test)] mod tests { use super::*; #[test] fn test_remote_cvs_prober() { let _ = CVSProber::new(); } } breezyshim-0.1.227/src/darcs.rs000064400000000000000000000026061046102023000144130ustar 00000000000000//! Darcs prober. //! //! This module provides a prober for Darcs repositories. It can detect //! darcs repositories but does not provide any additional functionality. use crate::controldir::Prober; use pyo3::exceptions::PyModuleNotFoundError; use pyo3::prelude::*; pub struct DarcsProber(PyObject); impl DarcsProber { pub fn new() -> Option { Python::with_gil(|py| { let m = match py.import_bound("breezy.plugins.darcs") { Ok(m) => m, Err(e) => { if e.is_instance_of::(py) { return None; } else { e.print_and_set_sys_last_vars(py); panic!("Failed to import breezy.plugins.darcs"); } } }; let prober = m.getattr("DarcsProber").expect("Failed to get DarcsProber"); Some(Self(prober.to_object(py))) }) } } impl FromPyObject<'_> for DarcsProber { fn extract_bound(obj: &Bound) -> PyResult { Ok(Self(obj.to_object(obj.py()))) } } impl ToPyObject for DarcsProber { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Prober for DarcsProber {} #[cfg(test)] mod tests { use super::*; #[test] fn test_new() { let _ = DarcsProber::new(); } } breezyshim-0.1.227/src/debian/apt.rs000064400000000000000000000216551046102023000153320ustar 00000000000000//! APT repository access. use crate::error::Error; use debian_control::apt::{Package, Source}; use debversion::Version; use pyo3::exceptions::PyStopIteration; use pyo3::prelude::*; pyo3::import_exception!(breezy.plugins.debian.apt_repo, NoAptSources); lazy_static::lazy_static! { static ref apt_mutex: std::sync::Mutex<()> = std::sync::Mutex::new(()); } struct SourceIterator(PyObject); impl Iterator for SourceIterator { type Item = Source; fn next(&mut self) -> Option { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let next = self.0.call_method0(py, "__next__"); match next { Ok(next) => Some(next.extract(py).unwrap()), Err(e) if e.is_instance_of::(py) => None, Err(e) if e.is_instance_of::(py) => None, Err(e) => panic!("error iterating: {:?}", e), } }) } } struct PackageIterator(PyObject); impl Iterator for PackageIterator { type Item = Package; fn next(&mut self) -> Option { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let next = self.0.call_method0(py, "__next__"); match next { Ok(next) => Some(next.extract(py).unwrap()), Err(e) if e.is_instance_of::(py) => None, Err(e) => panic!("error iterating: {:?}", e), } }) } } pub trait Apt: ToPyObject { // Retrieve the orig tarball from the repository. // // # Arguments // * `source_name` - The name of the source package to retrieve. // * `target_directory` - The directory to store the orig tarball in. // * `orig_version` - The version of the orig tarball to retrieve. // // # Returns // * `Ok(())` - If the orig tarball was successfully retrieved. fn retrieve_orig( &self, source_name: &str, target_directory: &std::path::Path, orig_version: Option<&Version>, ) -> Result<(), Error> { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let apt = self.to_object(py); apt.call_method1( py, "retrieve_orig", (source_name, target_directory, orig_version.to_object(py)), )?; Ok(()) }) } /// Retrieve the source package from the repository. /// /// # Arguments /// * `source_name` - The name of the source package to retrieve. /// * `target_directory` - The directory to store the source package in. /// * `source_version` - The version of the source package to retrieve. /// /// # Returns /// * `Ok(())` - If the source package was successfully retrieved. fn retrieve_source( &self, source_name: &str, target_directory: &std::path::Path, source_version: Option<&Version>, ) -> Result<(), Error> { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let apt = self.to_object(py); apt.call_method1( py, "retrieve_source", (source_name, target_directory, source_version.to_object(py)), )?; Ok(()) }) } /// Retrieve the binary package from the repository. fn iter_sources(&self) -> Box> { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let apt = self.to_object(py); let iter = apt.call_method0(py, "iter_sources").unwrap(); Box::new(SourceIterator(iter)) }) } /// Retrieve the binary package from the repository. fn iter_binaries(&self) -> Box> { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let apt = self.to_object(py); let iter = apt.call_method0(py, "iter_binaries").unwrap(); Box::new(PackageIterator(iter)) }) } /// Retrieve source package by name. fn iter_source_by_name(&self, name: &str) -> Box> { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let apt = self.to_object(py); let iter = apt .call_method1(py, "iter_source_by_name", (name,)) .unwrap(); Box::new(SourceIterator(iter)) }) } /// Retrieve binary package by name. fn iter_binary_by_name(&self, name: &str) -> Box> { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let apt = self.to_object(py); let iter = apt .call_method1(py, "iter_binary_by_name", (name,)) .unwrap(); Box::new(PackageIterator(iter)) }) } } pub struct LocalApt(PyObject); impl Apt for LocalApt {} impl ToPyObject for LocalApt { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl LocalApt { pub fn new(rootdir: Option<&std::path::Path>) -> Result { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let m = PyModule::import_bound(py, "breezy.plugins.debian.apt_repo")?; let apt = m.getattr("LocalApt")?; let apt = apt.call1((rootdir,))?; apt.call_method0("__enter__")?; Ok(Self(apt.to_object(py))) }) } } impl Default for LocalApt { fn default() -> Self { LocalApt::new(None).unwrap() } } impl Drop for LocalApt { fn drop(&mut self) { Python::with_gil(|py| { self.0 .call_method1(py, "__exit__", (py.None(), py.None(), py.None())) .unwrap(); }); } } pub struct RemoteApt(PyObject); impl ToPyObject for RemoteApt { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl RemoteApt { pub fn new( mirror_uri: &url::Url, distribution: Option<&str>, components: Option>, key_path: Option<&std::path::Path>, ) -> Result { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let m = PyModule::import_bound(py, "breezy.plugins.debian.apt_repo")?; let apt = m.getattr("RemoteApt")?; let apt = apt.call1((mirror_uri.as_str(), distribution, components, key_path))?; apt.call_method0("__enter__")?; Ok(Self(apt.to_object(py))) }) } pub fn from_string(text: &str, key_path: Option<&std::path::Path>) -> Result { let _mutex = apt_mutex.lock().unwrap(); Python::with_gil(|py| { let m = PyModule::import_bound(py, "breezy.plugins.debian.apt_repo")?; let apt = m.getattr("RemoteApt")?; let apt = apt.call_method1("from_string", (text, key_path))?; apt.call_method0("__enter__")?; Ok(Self(apt.to_object(py))) }) } } impl Apt for RemoteApt {} impl Drop for RemoteApt { fn drop(&mut self) { Python::with_gil(|py| { self.0 .call_method1(py, "__exit__", (py.None(), py.None(), py.None())) .unwrap(); }); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_local_apt_retrieve_orig() { let apt = LocalApt::new(None).unwrap(); let td = tempfile::tempdir().unwrap(); match apt.retrieve_orig("apt", td.path(), None) { Ok(_) => { // Verify the orig file is there let entries = td.path().read_dir().unwrap().collect::>(); assert_eq!(entries.len(), 1); let entry = entries[0].as_ref().unwrap(); assert!(entry.file_name().to_str().unwrap().starts_with("apt_"),); assert!(entry .file_name() .to_str() .unwrap() .ends_with(".orig.tar.gz"),); } Err(Error::NotImplemented) => { // This is expected, LocalApt does not implement this method } Err(e) => panic!("Unexpected error: {:?}", e), } } #[test] #[ignore] // Sometimes hangs fn test_local_apt() { let apt = LocalApt::new(None).unwrap(); let package = apt.iter_binaries().next().unwrap(); assert!(package.name().is_some()); assert!(package.version().is_some()); let mut sources = apt.iter_sources(); if let Some(source) = sources.next() { assert!(source.package().is_some()); let source = apt.iter_source_by_name("dpkg").next().unwrap(); assert_eq!(source.package().unwrap(), "dpkg"); let package = apt.iter_binary_by_name("dpkg").next().unwrap(); assert_eq!(package.name().unwrap(), "dpkg"); } } } breezyshim-0.1.227/src/debian/debcommit.rs000064400000000000000000000211011046102023000164730ustar 00000000000000use crate::commit::CommitReporter; use crate::debian::error::Error; use crate::debian::{suite_to_distribution, Vendor}; use crate::error::Error as BrzError; use crate::tree::{Kind, Path, Tree, WorkingTree}; use crate::RevisionId; use debian_changelog::ChangeLog; pub fn debcommit_release( tree: &WorkingTree, committer: Option<&str>, subpath: Option<&std::path::Path>, message: Option<&str>, vendor: Option, ) -> Result { let subpath = subpath.unwrap_or_else(|| std::path::Path::new("")); let cl_path = subpath.join("debian/changelog"); let (message, vendor) = if let (Some(message), Some(vendor)) = (message, vendor) { (message.to_string(), vendor) } else { let f = tree.get_file(&cl_path)?; let cl = ChangeLog::read(f)?; let entry = cl.iter().next().unwrap(); let message = if let Some(message) = message { message.to_string() } else { format!( "releasing package {} version {}", entry.package().unwrap(), entry.version().unwrap() ) }; let vendor = vendor.unwrap_or_else(|| { suite_to_distribution( entry .distributions() .as_ref() .and_then(|d| d.first()) .unwrap(), ) .unwrap() }); (message, vendor) }; let tag_name = if let Ok(tag_name) = crate::debian::tree_debian_tag_name( tree, tree.branch().as_ref(), Some(subpath), Some(vendor), ) { tag_name } else { return Err(Error::UnreleasedChanges); }; let mut builder = tree.build_commit().message(&message); if let Some(committer) = committer { builder = builder.committer(committer); } let revid = builder.commit()?; tree.branch().tags().unwrap().set_tag(&tag_name, &revid)?; Ok(tag_name) } pub fn changelog_changes( tree: &dyn Tree, basis_tree: &dyn Tree, cl_path: &Path, ) -> Result>, BrzError> { let mut changes = vec![]; for change in tree.iter_changes(basis_tree, Some(&[cl_path]), None, None)? { let change = change?; let paths = change.path; let changed_content = change.changed_content; let versioned = change.versioned; let kind = change.kind; // Content not changed if !changed_content { return Ok(None); } // Not versioned in new tree if !versioned.1.unwrap_or(false) { return Ok(None); } // Not a file in one tree if kind.0 != Some(Kind::File) || kind.1 != Some(Kind::File) { return Ok(None); } let old_text = basis_tree.get_file_lines(&paths.0.unwrap())?; let new_text = tree.get_file_lines(&paths.1.unwrap())?; changes.extend(new_changelog_entries(&old_text, &new_text)); } Ok(Some(changes)) } /// Strip a changelog message like debcommit does. /// /// Takes a list of changes from a changelog entry and applies a transformation /// so the message is well formatted for a commit message. /// /// # Arguments /// * `changes` - a list of lines from the changelog entry /// /// # Returns /// another list of lines with blank lines stripped from the start /// and the spaces the start of the lines split if there is only one /// logical entry. pub fn strip_changelog_message(changes: &[&str]) -> Vec { if changes.is_empty() { return vec![]; } let mut changes = changes.to_vec(); while changes.last() == Some(&"") { changes.pop(); } while changes.first() == Some(&"") { changes.remove(0); } let changes = changes .into_iter() .map(|l| lazy_regex::regex_replace!(r" |\t", l, |_| "")) .collect::>(); let leader_re = lazy_regex::regex!(r"^[ \t]*[*+-] "); let leader_changes = changes .iter() .filter(|line| leader_re.is_match(line)) .collect::>(); if leader_changes.len() == 1 { changes .iter() .map(|line| leader_re.replace(line, "").trim_start().to_string()) .collect() } else { changes.into_iter().map(|l| l.to_string()).collect() } } pub fn changelog_commit_message( tree: &dyn Tree, basis_tree: &dyn Tree, path: &Path, ) -> Result { let changes = changelog_changes(tree, basis_tree, path)?; let changes = changes.unwrap_or_default(); Ok(strip_changelog_message( changes .iter() .map(|s| s.as_str()) .collect::>() .as_slice(), ) .concat()) } /// Create a git commit with message based on the new entries in changelog. /// /// # Arguments /// * `tree` - Tree to commit in /// * `committer` - Optional committer identity /// * `subpath` - subpath to commit in /// * `paths` - specifics paths to commit, if any /// * `reporter` - CommitReporter to use /// /// # Returns /// Created revision id pub fn debcommit( tree: &WorkingTree, committer: Option<&str>, subpath: &Path, paths: Option<&[&Path]>, reporter: Option<&dyn CommitReporter>, message: Option<&str>, ) -> Result { let message = message.map_or_else( || { changelog_commit_message( tree, &tree.basis_tree().unwrap(), &subpath.join("debian/changelog"), ) .unwrap() }, |m| m.to_string(), ); let specific_files = if let Some(paths) = paths { Some(paths.iter().map(|p| subpath.join(p)).collect()) } else if !subpath.to_str().unwrap().is_empty() { Some(vec![subpath.to_path_buf()]) } else { None }; let mut builder = tree.build_commit().message(&message); if let Some(reporter) = reporter { builder = builder.reporter(reporter); } if let Some(committer) = committer { builder = builder.committer(committer); } if let Some(specific_files) = specific_files { builder = builder.specific_files( specific_files .iter() .map(|p| p.as_path()) .collect::>() .as_slice(), ); } builder.commit() } pub fn new_changelog_entries(old_text: &[Vec], new_text: &[Vec]) -> Vec { let mut sm = difflib::sequencematcher::SequenceMatcher::new(old_text, new_text); let mut changes = vec![]; for group in sm.get_grouped_opcodes(0) { let (j1, j2) = (group[0].second_start, group.last().unwrap().second_end); for line in new_text[j1..j2].iter() { if line.starts_with(b" ") { // Debian Policy Manual states that debian/changelog must be UTF-8 changes.push(String::from_utf8_lossy(line).to_string()); } } } changes } #[cfg(test)] mod tests { use super::*; mod strip_changelog_message { use super::*; #[test] fn test_empty() { assert_eq!(strip_changelog_message(&[]), Vec::::new()); } #[test] fn test_empty_changes() { assert_eq!(strip_changelog_message(&[""]), Vec::::new()); } #[test] fn test_removes_leading_whitespace() { assert_eq!( strip_changelog_message(&["foo", " bar", "\tbaz", " bang"]), vec!["foo", "bar", "baz", " bang"], ); } #[test] fn test_removes_star_if_one() { assert_eq!(strip_changelog_message(&[" * foo"]), ["foo"]); assert_eq!(strip_changelog_message(&["\t* foo"]), ["foo"]); assert_eq!(strip_changelog_message(&[" + foo"]), ["foo"]); assert_eq!(strip_changelog_message(&[" - foo"]), ["foo"]); assert_eq!(strip_changelog_message(&[" * foo"]), ["foo"]); assert_eq!( strip_changelog_message(&[" * foo", " bar"]), ["foo", "bar"] ); } #[test] fn test_leaves_start_if_multiple() { assert_eq!( strip_changelog_message(&[" * foo", " * bar"]), ["* foo", "* bar"] ); assert_eq!( strip_changelog_message(&[" * foo", " + bar"]), ["* foo", "+ bar"] ); assert_eq!( strip_changelog_message(&[" * foo", " bar", " * baz"]), ["* foo", "bar", "* baz"], ); } } } breezyshim-0.1.227/src/debian/directory.rs000064400000000000000000000005611046102023000165430ustar 00000000000000use pyo3::prelude::*; pub fn vcs_git_url_to_bzr_url(url: &str) -> url::Url { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.debian.directory").unwrap(); m.call_method1("vcs_git_url_to_bzr_url", (url,)) .unwrap() .extract::() .unwrap() .parse() .unwrap() }) } breezyshim-0.1.227/src/debian/error.rs000064400000000000000000000140511046102023000156670ustar 00000000000000use crate::error::Error as BrzError; use debversion::Version; use pyo3::import_exception; use pyo3::prelude::*; pyo3::import_exception!(breezy.plugins.debian.builder, BuildFailedError); import_exception!(breezy.plugins.debian.import_dsc, UpstreamAlreadyImported); import_exception!(breezy.plugins.debian.upstream.branch, DistCommandfailed); import_exception!(breezy.plugins.debian.upstream, PackageVersionNotPresent); import_exception!(breezy.plugins.debian.upstream, MissingUpstreamTarball); import_exception!(breezy.plugins.debian.changelog, UnreleasedChanges); import_exception!(breezy.plugins.debian.import_dsc, VersionAlreadyImported); #[derive(Debug)] pub enum Error { BrzError(BrzError), BuildFailed, UpstreamAlreadyImported(String), VersionAlreadyImported { package: String, version: Version, tag_name: String, }, DistCommandFailed(String), PackageVersionNotPresent { package: String, version: String, }, MissingUpstreamTarball { package: String, version: String, }, UnreleasedChanges, ChangeLogError(debian_changelog::Error), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::BrzError(err) => write!(f, "{}", err), Error::BuildFailed => write!(f, "Build failed"), Error::UpstreamAlreadyImported(version) => { write!(f, "Upstream version {} already imported", version) } Error::DistCommandFailed(err) => write!(f, "Dist command failed: {}", err), Error::PackageVersionNotPresent { package, version } => { write!(f, "Package {} version {} not present", package, version) } Error::MissingUpstreamTarball { package, version } => { write!( f, "Missing upstream tarball for {} version {}", package, version ) } Error::UnreleasedChanges => write!(f, "Unreleased changes"), Error::ChangeLogError(err) => write!(f, "{}", err), Error::VersionAlreadyImported { package, version, tag_name, } => { write!( f, "Version {} of package {} already imported with tag {}", version, package, tag_name ) } } } } impl std::error::Error for Error {} impl From for Error { fn from(err: BrzError) -> Error { Error::BrzError(err) } } impl From for Error { fn from(err: debian_changelog::Error) -> Error { Error::ChangeLogError(err) } } impl From for Error { fn from(err: PyErr) -> Error { Python::with_gil(|py| { let brz_error: BrzError = err.into(); if let BrzError::Other(ref err) = brz_error { if err.is_instance_of::(py) { let v = err.value_bound(py); Error::UpstreamAlreadyImported(v.getattr("version").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { let v = err.value_bound(py); Error::VersionAlreadyImported { package: v.getattr("package").unwrap().extract().unwrap(), version: v.getattr("version").unwrap().extract().unwrap(), tag_name: v.getattr("tag_name").unwrap().extract().unwrap(), } } else if err.is_instance_of::(py) { let v = err.value_bound(py); Error::DistCommandFailed(v.getattr("error").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { let v = err.value_bound(py); Error::PackageVersionNotPresent { package: v.getattr("package").unwrap().extract().unwrap(), version: v.getattr("version").unwrap().extract().unwrap(), } } else if err.is_instance_of::(py) { let v = err.value_bound(py); Error::MissingUpstreamTarball { package: v.getattr("package").unwrap().extract().unwrap(), version: v.getattr("version").unwrap().extract().unwrap(), } } else if err.is_instance_of::(py) { Error::BuildFailed } else if err.is_instance_of::(py) { Error::UnreleasedChanges } else { Error::BrzError(brz_error) } } else { Error::BrzError(brz_error) } }) } } impl From for PyErr { fn from(err: Error) -> PyErr { match err { Error::BrzError(err) => err.into(), Error::BuildFailed => BuildFailedError::new_err(("Build failed",)).into(), Error::UpstreamAlreadyImported(version) => { UpstreamAlreadyImported::new_err((version,)).into() } Error::DistCommandFailed(err) => DistCommandfailed::new_err((err,)).into(), Error::PackageVersionNotPresent { package, version } => { PackageVersionNotPresent::new_err((package, version)).into() } Error::MissingUpstreamTarball { package, version } => { MissingUpstreamTarball::new_err((package, version)).into() } Error::UnreleasedChanges => UnreleasedChanges::new_err(()).into(), Error::ChangeLogError(_err) => todo!(), Error::VersionAlreadyImported { package, version, tag_name, } => VersionAlreadyImported::new_err((package, version, tag_name)).into(), } } } breezyshim-0.1.227/src/debian/import_dsc.rs000064400000000000000000000110221046102023000166740ustar 00000000000000use crate::branch::GenericBranch; use crate::debian::TarballKind; use crate::tree::WorkingTree; use crate::{branch::Branch, tree::Tree, RevisionId}; use pyo3::prelude::*; use std::{collections::HashMap, path::Path, path::PathBuf}; pub struct DistributionBranchSet(PyObject); impl ToPyObject for DistributionBranchSet { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl DistributionBranchSet { /// Create a new DistributionBranchSet instance. pub fn new() -> Self { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.debian.import_dsc").unwrap(); let ctr = m.getattr("DistributionBranchSet").unwrap(); DistributionBranchSet(ctr.call0().unwrap().into()) }) } pub fn add_branch(&self, branch: &DistributionBranch) { Python::with_gil(|py| { self.0 .call_method1(py, "add_branch", (branch.to_object(py),)) .unwrap(); }) } } pub struct DistributionBranch(PyObject); impl ToPyObject for DistributionBranch { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl DistributionBranch { pub fn new( branch: &dyn Branch, pristine_upstream_branch: &dyn Branch, tree: Option<&dyn Tree>, pristine_upstream_tree: Option<&dyn Tree>, ) -> Self { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.debian.import_dsc").unwrap(); let ctr = m.getattr("DistributionBranch").unwrap(); DistributionBranch( ctr.call1(( branch.to_object(py), pristine_upstream_branch.to_object(py), tree.map(|t| t.to_object(py)), pristine_upstream_tree.map(|t| t.to_object(py)), )) .unwrap() .into(), ) }) } pub fn revid_of_version( &self, version: &debversion::Version, ) -> Result { Ok(Python::with_gil(|py| -> PyResult { self.0 .call_method1(py, "revid_of_version", (version.to_object(py),))? .extract::(py) })?) } pub fn import_package( &self, dsc_path: &Path, apply_patches: bool, ) -> Result { Ok(Python::with_gil(|py| -> PyResult { self.0 .call_method1( py, "import_package", (dsc_path.to_object(py), apply_patches), )? .extract::(py) })?) } pub fn tree(&self) -> Option { Python::with_gil(|py| -> PyResult> { let tree = self .0 .getattr(py, "tree")? .extract::>(py)?; if tree.is_none() { return Ok(None); } Ok(Some(WorkingTree::from(tree.unwrap()))) }) .unwrap() } pub fn branch(&self) -> Box { Python::with_gil(|py| -> PyResult> { Ok(Box::new(GenericBranch::new(self.0.getattr(py, "branch")?))) }) .unwrap() } pub fn pristine_upstream_source(&self) -> crate::debian::upstream::PristineTarSource { Python::with_gil( |py| -> PyResult { Ok(crate::debian::upstream::PristineTarSource::from( self.0.getattr(py, "pristine_upstream_source")?, )) }, ) .unwrap() } pub fn create_empty_upstream_tree( &self, basedir: &Path, ) -> Result<(), crate::debian::error::Error> { Python::with_gil(|py| -> PyResult<()> { self.0 .call_method1(py, "create_empty_upstream_tree", (basedir.to_object(py),))?; Ok(()) })?; Ok(()) } pub fn extract_upstream_tree( &self, upstream_tips: &HashMap, basedir: &Path, ) -> Result<(), crate::debian::error::Error> { Ok(Python::with_gil(|py| -> PyResult<()> { self.0.call_method1( py, "extract_upstream_tree", (upstream_tips.to_object(py), basedir.to_object(py)), )?; Ok(()) })?) } } breezyshim-0.1.227/src/debian/merge_upstream.rs000064400000000000000000000073451046102023000175650ustar 00000000000000use crate::branch::Branch; use crate::debian::error::Error; use crate::debian::upstream::UpstreamSource; use crate::debian::TarballKind; use crate::tree::Tree; use crate::workingtree::WorkingTree; use crate::RevisionId; use pyo3::prelude::*; use pyo3::types::PyDict; use std::collections::HashMap; use std::path::{Path, PathBuf}; /// Import new tarballs. /// /// # Arguments /// * `tree` - Working tree to operate in /// * `subpath` - Subpath to operate in /// * `tarball_filenames` - List of tarball filenames as tuples with (path, component) /// * `package` - Package name /// * `version` - New upstream version to merge /// * `current_version` - Current upstream version in tree /// * `upstream_branch` - Optional upstream branch to merge from /// * `upstream_revisions` - Dictionary mapping versions to upstream revisions /// * `merge_type` - Merge type /// * `committer` - Committer string to use /// * `files_excluded` - Files to exclude /// /// # Returns /// List with (component, tag, revid, pristine_tar_imported, subpath) tuples pub fn do_import( tree: &WorkingTree, subpath: &Path, tarball_filenames: &[&Path], package: &str, version: &str, current_version: Option<&str>, upstream_branch: &dyn Branch, upstream_revisions: HashMap, merge_type: Option<&str>, force: bool, force_pristine_tar: bool, committer: Option<&str>, files_excluded: Option<&[&Path]>, ) -> Result, PathBuf)>, Error> { Python::with_gil(|py| { let m = PyModule::import_bound(py, "breezy.plugins.debian.merge_upstream").unwrap(); let do_import = m.getattr("do_import").unwrap(); let kwargs = PyDict::new_bound(py); kwargs.set_item("tree", tree.to_object(py))?; kwargs.set_item("subpath", subpath)?; kwargs.set_item("tarball_filenames", tarball_filenames.to_vec())?; kwargs.set_item("package", package)?; kwargs.set_item("version", version)?; kwargs.set_item("current_version", current_version)?; kwargs.set_item("upstream_branch", upstream_branch.to_object(py))?; kwargs.set_item("upstream_revisions", upstream_revisions.to_object(py))?; kwargs.set_item("merge_type", merge_type)?; kwargs.set_item("force", force)?; kwargs.set_item("force_pristine_tar", force_pristine_tar)?; kwargs.set_item("committer", committer)?; kwargs.set_item("files_excluded", files_excluded)?; Ok(do_import.call((), Some(&kwargs))?.extract()?) }) } pub fn get_tarballs( orig_dir: &Path, tree: &dyn Tree, package: &str, version: &str, locations: &[&Path], ) -> Result, Error> { Python::with_gil(|py| { let m = PyModule::import_bound(py, "breezy.plugins.debian.merge_upstream").unwrap(); let get_tarballs = m.getattr("get_tarballs").unwrap(); Ok(get_tarballs .call1(( orig_dir, tree.to_object(py), package, version, locations.to_vec(), ))? .extract()?) }) } pub fn get_existing_imported_upstream_revids( upstream_source: &dyn UpstreamSource, package: &str, new_upstream_version: &str, ) -> Result, PathBuf)>, Error> { Python::with_gil(|py| { let m = PyModule::import_bound(py, "breezy.plugins.debian.merge_upstream").unwrap(); let get_existing_imported_upstream_revids = m.getattr("get_existing_imported_upstream_revids").unwrap(); Ok(get_existing_imported_upstream_revids .call1((upstream_source.to_object(py), package, new_upstream_version))? .extract()?) }) } breezyshim-0.1.227/src/debian/mod.rs000064400000000000000000000173401046102023000153210ustar 00000000000000//! Debian specific functionality. //! //! This module provides functionality for working with Debian packages. //! //! It mostly wraps the `breezy.plugins.debian` module from the Breezy VCS. pub mod apt; pub mod debcommit; pub mod directory; pub mod error; pub mod import_dsc; pub mod merge_upstream; pub mod release; pub mod upstream; pub mod vcs_up_to_date; pub const DEFAULT_BUILD_DIR: &str = "../build-area"; pub const DEFAULT_ORIG_DIR: &str = ".."; pub const DEFAULT_RESULT_DIR: &str = ".."; use crate::debian::error::Error as DebianError; use crate::error::Error; use crate::tree::{Tree, WorkingTree}; use crate::Branch; use std::collections::HashMap; use std::path::PathBuf; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyDict; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Vendor { Debian, Ubuntu, Kali, } impl std::fmt::Display for Vendor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Vendor::Debian => write!(f, "debian"), Vendor::Ubuntu => write!(f, "ubuntu"), Vendor::Kali => write!(f, "kali"), } } } impl std::str::FromStr for Vendor { type Err = String; fn from_str(s: &str) -> Result { match s { "debian" => Ok(Vendor::Debian), "ubuntu" => Ok(Vendor::Ubuntu), "kali" => Ok(Vendor::Kali), _ => Err(format!("Invalid vendor: {}", s)), } } } impl FromPyObject<'_> for Vendor { fn extract_bound(ob: &Bound) -> PyResult { let vendor = ob.extract::()?; match vendor.as_str() { "debian" => Ok(Vendor::Debian), "ubuntu" => Ok(Vendor::Ubuntu), "kali" => Ok(Vendor::Kali), _ => Err(PyValueError::new_err((format!( "Invalid vendor: {}", vendor ),))), } } } #[derive(Debug, Clone, PartialEq, Eq, std::hash::Hash, Default)] pub enum VersionKind { #[default] Auto, Snapshot, Release, } impl std::str::FromStr for VersionKind { type Err = String; fn from_str(s: &str) -> Result { match s { "auto" => Ok(VersionKind::Auto), "snapshot" => Ok(VersionKind::Snapshot), "release" => Ok(VersionKind::Release), _ => Err(format!("Invalid version kind: {}", s)), } } } impl ToPyObject for VersionKind { fn to_object(&self, py: Python) -> PyObject { match self { VersionKind::Auto => "auto".to_object(py), VersionKind::Snapshot => "snapshot".to_object(py), VersionKind::Release => "release".to_object(py), } } } impl std::fmt::Display for VersionKind { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { VersionKind::Auto => write!(f, "auto"), VersionKind::Snapshot => write!(f, "snapshot"), VersionKind::Release => write!(f, "release"), } } } impl FromPyObject<'_> for VersionKind { fn extract_bound(ob: &Bound) -> PyResult { let kind = ob.extract::()?; match kind.as_str() { "auto" => Ok(VersionKind::Auto), "snapshot" => Ok(VersionKind::Snapshot), "release" => Ok(VersionKind::Release), _ => Err(PyValueError::new_err((format!( "Invalid version kind: {}", kind ),))), } } } #[derive(Debug, Clone, PartialEq, Eq, std::hash::Hash)] pub enum TarballKind { Orig, Additional(String), } impl serde::ser::Serialize for TarballKind { fn serialize(&self, serializer: S) -> Result { match self { TarballKind::Orig => serializer.serialize_none(), TarballKind::Additional(kind) => serializer.serialize_some(kind), } } } impl<'a> serde::de::Deserialize<'a> for TarballKind { fn deserialize>(deserializer: D) -> Result { let kind = Option::::deserialize(deserializer)?; Ok(kind.into()) } } impl From> for TarballKind { fn from(kind: Option) -> Self { match kind { Some(kind) => TarballKind::Additional(kind), None => TarballKind::Orig, } } } impl From for Option { fn from(kind: TarballKind) -> Self { match kind { TarballKind::Orig => None, TarballKind::Additional(kind) => Some(kind), } } } impl FromPyObject<'_> for TarballKind { fn extract_bound(ob: &Bound) -> PyResult { let kind = ob.extract::>()?; Ok(kind.into()) } } impl ToPyObject for TarballKind { fn to_object(&self, py: Python) -> PyObject { let o: Option = self.clone().into(); o.to_object(py) } } impl IntoPy for TarballKind { fn into_py(self, py: Python) -> PyObject { self.to_object(py) } } pub fn build_helper( local_tree: &WorkingTree, subpath: &std::path::Path, branch: &dyn Branch, target_dir: &std::path::Path, builder: &str, guess_upstream_branch_url: bool, apt_repo: Option<&dyn apt::Apt>, ) -> Result, DebianError> { pyo3::prepare_freethreaded_python(); Python::with_gil(|py| -> PyResult> { let locals = PyDict::new_bound(py); locals.set_item("local_tree", local_tree)?; locals.set_item("subpath", subpath)?; locals.set_item("branch", branch)?; locals.set_item("target_dir", target_dir)?; locals.set_item("builder", builder)?; locals.set_item("guess_upstream_branch_url", guess_upstream_branch_url)?; if let Some(apt_repo) = apt_repo { locals.set_item("apt", apt_repo.to_object(py))?; } py.import_bound("breezy.plugins.debian.cmds")? .call_method1("_build_helper", (locals,))? .extract() }) .map_err(DebianError::from) } /// Return the name of the debian tag for the given tree and branch. /// /// # Arguments /// * `tree` - The tree to get the debian tag name for. /// * `branch` - The branch to get the debian tag name for. /// * `subpath` - The subpath to get the debian tag name for. /// * `vendor` - The vendor to get the debian tag name for. /// /// # Returns /// The name of the debian tag. pub fn tree_debian_tag_name( tree: &dyn Tree, branch: &dyn Branch, subpath: Option<&std::path::Path>, vendor: Option, ) -> Result { Python::with_gil(|py| { let result = py.import_bound("breezy.plugins.debian")?.call_method1( "tree_debian_tag_name", ( tree.to_object(py), branch.to_object(py), subpath, vendor.map(|v| v.to_string()), ), )?; Ok(result.extract()?) }) } // TODO(jelmer): deduplicate this with the suite_to_distribution function // in debian-analyzer /// Infer the distribution from a suite. /// /// When passed the name of a suite (anything in the distributions field of /// a changelog) it will infer the distribution from that (i.e. Debian or /// Ubuntu). /// /// # Arguments /// * `suite`: the string containing the suite /// /// # Returns /// Vendor or None if the distribution cannot be inferred. pub fn suite_to_distribution(suite: &str) -> Option { Python::with_gil(|py| -> PyResult> { let result = py .import_bound("breezy.plugins.debian.util")? .call_method1("suite_to_distribution", (suite,))?; Ok(result.extract()?) }) .unwrap() } breezyshim-0.1.227/src/debian/release.rs000064400000000000000000000024101046102023000161520ustar 00000000000000//! Debian package releasing use crate::error::Error; use crate::tree::MutableTree; use pyo3::prelude::*; #[derive(Debug)] pub enum ReleaseError { GeneratedFile, BrzError(Error), } impl From for ReleaseError { fn from(err: Error) -> Self { ReleaseError::BrzError(err) } } impl std::fmt::Display for ReleaseError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { ReleaseError::GeneratedFile => write!(f, "Generated file"), ReleaseError::BrzError(err) => write!(f, "{}", err), } } } impl std::error::Error for ReleaseError {} pub fn release( local_tree: &dyn MutableTree, subpath: &std::path::Path, ) -> Result { pyo3::import_exception!(debmutate.reformatting, GeneratedFile); Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.debian.release").unwrap(); let release = m.getattr("release").unwrap(); match release.call1((local_tree.to_object(py), subpath)) { Ok(result) => Ok(result.extract().unwrap()), Err(err) if err.is_instance_of::(py) => Err(ReleaseError::GeneratedFile), Err(err) => Err(ReleaseError::BrzError(err.into())), } }) } breezyshim-0.1.227/src/debian/upstream.rs000064400000000000000000000275371046102023000164130ustar 00000000000000use crate::branch::Branch; use crate::controldir::ControlDir; use crate::debian::error::Error; use crate::debian::TarballKind; use crate::debian::VersionKind; use crate::tree::Tree; use crate::RevisionId; use debversion::Version; use pyo3::prelude::*; use pyo3::types::{PyCFunction, PyDict, PyTuple}; use std::collections::HashMap; use std::ffi::OsString; use std::path::{Path, PathBuf}; pub struct PristineTarSource(PyObject); impl From for PristineTarSource { fn from(obj: PyObject) -> Self { PristineTarSource(obj) } } impl ToPyObject for PristineTarSource { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl IntoPy for PristineTarSource { fn into_py(self, py: Python) -> PyObject { self.to_object(py) } } /// A source for upstream versions (uscan, debian/rules, etc). pub struct UpstreamBranchSource(PyObject); impl From for UpstreamBranchSource { fn from(obj: PyObject) -> Self { UpstreamBranchSource(obj) } } impl ToPyObject for UpstreamBranchSource { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } pub struct Tarball { pub filename: String, pub component: TarballKind, pub md5: String, } pub type Tarballs = Vec; impl FromPyObject<'_> for Tarball { fn extract_bound(ob: &Bound) -> PyResult { Ok(Tarball { filename: ob.get_item(0)?.extract()?, component: ob.get_item(1)?.extract()?, md5: ob.get_item(2)?.extract()?, }) } } impl ToPyObject for Tarball { fn to_object(&self, py: Python) -> PyObject { ( self.filename.clone(), self.component.clone(), self.md5.clone(), ) .to_object(py) } } impl IntoPy for Tarball { fn into_py(self, py: Python) -> PyObject { self.to_object(py) } } pub trait UpstreamSource: ToPyObject { /// Check what the latest upstream version is. /// /// # Arguments /// * `package` - Name of the package /// * `version` - The current upstream version of the package. /// /// # Returns /// A tuple of the latest upstream version and the mangled version. fn get_latest_version( &self, package: Option<&str>, current_version: Option<&str>, ) -> Result, Error> { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1(py, "get_latest_version", (package, current_version))? .extract(py)?) }) } /// Retrieve recent version strings. /// /// # Arguments /// * `package`: Name of the package /// * `version`: Last upstream version since which to retrieve versions fn get_recent_versions( &self, package: Option<&str>, since_version: Option<&str>, ) -> Box> { let mut ret = vec![]; Python::with_gil(|py| -> PyResult<()> { let recent_versions = self.to_object(py).call_method1( py, "get_recent_versions", (package, since_version), )?; while let Ok(Some((version, mangled_version))) = recent_versions.call_method0(py, "__next__")?.extract(py) { ret.push((version, mangled_version)); } Ok(()) }) .unwrap(); Box::new(ret.into_iter()) } /// Lookup the revision ids for a particular version. /// /// # Arguments /// * `package` - Package name /// * `version` - Version string /// /// # Returns /// A dictionary mapping component names to revision ids fn version_as_revisions( &self, package: Option<&str>, version: &str, tarballs: Option, ) -> Result, Error> { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1(py, "version_as_revisions", (package, version, tarballs))? .extract(py)?) }) } /// Check whether this upstream source contains a particular package. /// /// # Arguments /// * `package` - Package name /// * `version` - Version string /// * `tarballs` - Tarballs list fn has_version( &self, package: Option<&str>, version: &str, tarballs: Option, ) -> Result { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1(py, "has_version", (package, version, tarballs))? .extract(py)?) }) } /// Fetch the source tarball for a particular version. /// /// # Arguments /// * `package` - Name of the package /// * `version` - Version string of the version to fetch /// * `target_dir` - Directory in which to store the tarball /// * `components` - List of component names to fetch; may be None, /// /// # Returns /// Paths of the fetched tarballs fn fetch_tarballs( &self, package: Option<&str>, version: &str, target_dir: &Path, components: Option<&[TarballKind]>, ) -> Result, Error> { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1( py, "fetch_tarballs", (package, version, target_dir, components.map(|x| x.to_vec())), )? .extract(py)?) }) } } impl UpstreamSource for UpstreamBranchSource {} impl std::fmt::Debug for UpstreamBranchSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("UpstreamBranchSource").finish() } } impl UpstreamBranchSource { pub fn upstream_branch(&self) -> Box { let o = Python::with_gil(|py| self.to_object(py).getattr(py, "upstream_branch").unwrap()); Box::new(crate::branch::GenericBranch::new(o)) } pub fn revision_tree( &self, source_name: Option<&str>, mangled_upstream_version: &str, ) -> Result { Python::with_gil(|py| { Ok(crate::tree::RevisionTree(self.to_object(py).call_method1( py, "revision_tree", (source_name, mangled_upstream_version), )?)) }) } pub fn version_as_revision( &self, package: Option<&str>, version: &str, tarballs: Option, ) -> Result<(RevisionId, PathBuf), Error> { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1(py, "version_as_revision", (package, version, tarballs))? .extract(py)?) }) } pub fn from_branch( upstream_branch: &dyn crate::branch::Branch, version_kind: Option, local_dir: &ControlDir, create_dist: Option< impl Fn(&dyn Tree, &str, &str, &Path, &Path) -> Result + Send + Sync + 'static, >, ) -> Result { Python::with_gil(|py| { let m = py .import_bound("breezy.plugins.debian.upstream.branch") .unwrap(); let cls = m.getattr("UpstreamBranchSource").unwrap(); let upstream_branch = upstream_branch.to_object(py); let kwargs = PyDict::new_bound(py); kwargs.set_item("version_kind", version_kind.unwrap_or_default())?; kwargs.set_item("local_dir", local_dir.to_object(py))?; if let Some(create_dist) = create_dist { let create_dist = move |args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>| -> PyResult<_> { let args = args.extract::<(PyObject, String, String, PathBuf, PathBuf)>()?; create_dist( &crate::tree::RevisionTree(args.0), &args.1, &args.2, &args.3, &args.4, ) .map(|x| x.to_string_lossy().into_owned()) .map_err(|e| e.into()) }; let create_dist = PyCFunction::new_closure_bound(py, None, None, create_dist)?; kwargs.set_item("create_dist", create_dist)?; } Ok(UpstreamBranchSource( cls.call_method("from_branch", (upstream_branch,), Some(&kwargs))? .into(), )) }) } } impl UpstreamSource for PristineTarSource {} impl PristineTarSource { /// Check whether this upstream source contains a particular package. /// /// # Arguments /// * `package` - Package name /// * `version` - Version string /// * `tarballs` - Tarballs list pub fn has_version( &self, package: Option<&str>, version: &str, tarballs: Option, try_hard: bool, ) -> Result { Python::with_gil(|py| { Ok(self .to_object(py) .call_method1(py, "has_version", (package, version, tarballs, try_hard))? .extract(py)?) }) } } /// Update the revision in a upstream version string. /// /// # Arguments /// * `branch` - Branch in which the revision can be found /// * `version_string` - Original version string /// * `revid` - Revision id of the revision /// * `sep` - Separator to use when adding snapshot pub fn upstream_version_add_revision( upstream_branch: &dyn crate::branch::Branch, version_string: &str, revid: &RevisionId, sep: Option<&str>, ) -> Result { let sep = sep.unwrap_or("+"); Python::with_gil(|py| { let m = py .import_bound("breezy.plugins.debian.upstream.branch") .unwrap(); let upstream_version_add_revision = m.getattr("upstream_version_add_revision").unwrap(); Ok(upstream_version_add_revision .call_method1( "upstream_version_add_revision", ( upstream_branch.to_object(py), version_string, revid.to_object(py), sep, ), )? .extract()?) }) } pub fn get_pristine_tar_source( packaging_tree: &dyn Tree, packaging_branch: &dyn Branch, ) -> Result { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.debian.upstream").unwrap(); let cls = m.getattr("get_pristine_tar_source").unwrap(); Ok(PristineTarSource( cls.call1((packaging_tree.to_object(py), packaging_branch.to_object(py)))? .into(), )) }) } pub fn run_dist_command( revtree: &dyn Tree, package: Option<&str>, version: &Version, target_dir: &Path, dist_command: &str, include_controldir: bool, subpath: &Path, ) -> Result { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.debian.upstream").unwrap(); let run_dist_command = m.getattr("run_dist_command").unwrap(); let kwargs = PyDict::new_bound(py); kwargs.set_item("revtree", revtree.to_object(py))?; kwargs.set_item("package", package)?; kwargs.set_item("version", version)?; kwargs.set_item(target_dir, target_dir)?; kwargs.set_item("dist_command", dist_command)?; kwargs.set_item("include_controldir", include_controldir)?; kwargs.set_item("subpath", subpath)?; Ok(run_dist_command.call((), Some(&kwargs))?.extract()?) }) } breezyshim-0.1.227/src/debian/vcs_up_to_date.rs000064400000000000000000000051151046102023000175350ustar 00000000000000use crate::debian::apt::Apt; use 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 fn check_up_to_date( tree: &dyn Tree, subpath: &std::path::Path, apt: &impl 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_bound("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.to_object(py), )) { Err(e) if e.is_instance_of::(py) => { Ok(UpToDateStatus::MissingChangelog) } Err(e) if e.is_instance_of::(py) => { Ok(UpToDateStatus::PackageMissingInArchive { package: e.into_value(py).getattr(py, "package")?.extract(py)?, }) } Err(e) if e.is_instance_of::(py) => { let value = e.into_value(py); Ok(UpToDateStatus::TreeVersionNotInArchive { tree_version: value.getattr(py, "tree_version")?.extract(py)?, archive_versions: value .getattr(py, "archive_versions")? .extract::>(py)?, }) } Err(e) if e.is_instance_of::(py) => { let value = e.into_value(py); Ok(UpToDateStatus::NewArchiveVersion { archive_version: value.getattr(py, "archive_version")?.extract(py)?, tree_version: value.getattr(py, "tree_version")?.extract(py)?, }) } Ok(_o) => Ok(UpToDateStatus::UpToDate), Err(e) => Err(e), } }) } breezyshim-0.1.227/src/delta.rs000064400000000000000000000062261046102023000144120ustar 00000000000000//! Detection of changes between trees. use crate::osutils::is_inside_any; use 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_bound(ob: &Bound) -> 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, }) } } pub fn filter_excluded<'a>( iter_changes: impl Iterator + 'a, exclude: &'a [&'a std::path::Path], ) -> impl Iterator + 'a { iter_changes.filter(|change| { let new_excluded = if let Some(p) = change.path.1.as_ref() { is_inside_any(exclude, p.as_path()) } else { false }; let old_excluded = if let Some(p) = change.path.0.as_ref() { is_inside_any(exclude, p.as_path()) } else { false }; if old_excluded && new_excluded { false } else if old_excluded || new_excluded { // TODO(jelmer): Perhaps raise an error here instead? false } else { true } }) } breezyshim-0.1.227/src/diff.rs000064400000000000000000000020261046102023000142230ustar 00000000000000//! Generation of unified diffs between trees. use 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>, ) -> Result<(), crate::error::Error> { Python::with_gil(|py| -> PyResult<()> { let m = py.import_bound("breezy.diff")?; let f = m.getattr("show_diff_trees")?; let o = py.import_bound("io")?.call_method0("BytesIO")?; let kwargs = PyDict::new_bound(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.227/src/dirty_tracker.rs000064400000000000000000000140351046102023000161640ustar 00000000000000//! Fast and efficient detection of files that have been modified in a directory tree. use crate::tree::WorkingTree; use dirty_tracker::DirtyTracker; pub use dirty_tracker::State; pub struct DirtyTreeTracker { tracker: DirtyTracker, tree: WorkingTree, base: std::path::PathBuf, } impl DirtyTreeTracker { /// Create a new DirtyTreeTracker for the given WorkingTree. pub fn new(tree: WorkingTree) -> Self { let base = tree.basedir(); let tracker = DirtyTracker::new(&base).unwrap(); Self { tracker, tree, base, } } pub fn new_in_subpath(tree: WorkingTree, subpath: &std::path::Path) -> Self { let base = tree.basedir(); let tracker = DirtyTracker::new(&base.join(subpath)).unwrap(); Self { tracker, tree, base, } } /// Get the current state. pub fn state(&mut self) -> State { let relpaths = self.relpaths(); if relpaths.is_none() { return State::Unknown; } if relpaths.unwrap().into_iter().next().is_some() { State::Dirty } else { State::Clean } } /// Get the relative paths of the dirty files. pub fn relpaths(&mut self) -> Option> { self.tracker.paths().map(|ps| { ps.iter() .map(|p| p.strip_prefix(&self.base).unwrap()) .filter(|p| !self.tree.is_control_filename(p)) .map(|p| p.to_path_buf()) .collect() }) } /// Get the absolute paths of the dirty files. pub fn paths(&mut self) -> Option> { self.relpaths() .map(|ps| ps.iter().map(|p| self.tree.abspath(p).unwrap()).collect()) } /// Mark the tree as clean. pub fn mark_clean(&mut self) { self.tracker.mark_clean() } } #[cfg(test)] mod tests { use super::*; use crate::controldir::create_standalone_workingtree; use crate::controldir::ControlDirFormat; #[test] fn test_unchanged_tree() { let td = tempfile::tempdir().unwrap(); let tree = create_standalone_workingtree(td.path(), &ControlDirFormat::default()).unwrap(); let mut tracker = DirtyTreeTracker::new(tree); assert_eq!(tracker.state(), State::Clean); assert_eq!(tracker.relpaths(), Some(std::collections::HashSet::new())); assert_eq!(tracker.paths(), Some(std::collections::HashSet::new())); } #[test] fn test_unversioned_file() { let td = tempfile::tempdir().unwrap(); let tree = create_standalone_workingtree(td.path(), &ControlDirFormat::default()).unwrap(); let mut tracker = DirtyTreeTracker::new(tree); std::fs::write(td.path().join("foo"), "bar").unwrap(); assert_eq!( tracker.relpaths(), Some(maplit::hashset! { std::path::PathBuf::from("foo") }) ); assert_eq!( tracker.paths(), Some(maplit::hashset! { td.path().join("foo") }) ); assert_eq!(tracker.state(), State::Dirty); } #[test] fn test_control_file_change() { let td = tempfile::tempdir().unwrap(); let tree = create_standalone_workingtree(td.path(), &ControlDirFormat::default()).unwrap(); let mut tracker = DirtyTreeTracker::new(tree.clone()); tree.build_commit() .message("Dummy") .committer("Joe Example ") .allow_pointless(true) .commit() .unwrap(); assert_eq!(tracker.relpaths(), Some(std::collections::HashSet::new())); assert_eq!(tracker.state(), State::Clean); assert_eq!(tracker.paths(), Some(std::collections::HashSet::new())); } } breezyshim-0.1.227/src/error.rs000064400000000000000000001475651046102023000144660ustar 00000000000000//! Error handling for the Breezy Python bindings use crate::transform::RawConflict; use pyo3::import_exception; use pyo3::prelude::*; use pyo3::PyErr; use url::Url; import_exception!(breezy.errors, UnknownFormatError); import_exception!(breezy.errors, NotBranchError); import_exception!(breezy.errors, ReadOnlyError); import_exception!(breezy.controldir, NoColocatedBranchSupport); import_exception!(breezy.errors, DependencyNotPresent); import_exception!(breezy.errors, PermissionDenied); import_exception!(breezy.transport, UnsupportedProtocol); import_exception!(breezy.transport, UnusableRedirect); import_exception!(breezy.urlutils, InvalidURL); import_exception!(breezy.errors, TransportError); import_exception!(breezy.errors, UnsupportedFormatError); import_exception!(breezy.errors, UnsupportedVcs); import_exception!(breezy.git.remote, RemoteGitError); import_exception!(breezy.git.remote, ProtectedBranchHookDeclined); import_exception!(http.client, IncompleteRead); import_exception!(breezy.bzr, LineEndingError); import_exception!(breezy.errors, InvalidHttpResponse); import_exception!(breezy.errors, AlreadyControlDirError); import_exception!(breezy.errors, AlreadyBranchError); import_exception!(breezy.errors, DivergedBranches); import_exception!(breezy.workspace, WorkspaceDirty); import_exception!(breezy.transport, NoSuchFile); import_exception!(breezy.commit, PointlessCommit); import_exception!(breezy.errors, NoWhoami); import_exception!(breezy.errors, NoSuchTag); import_exception!(breezy.errors, TagAlreadyExists); import_exception!(breezy.forge, ForgeLoginRequired); import_exception!(breezy.forge, UnsupportedForge); import_exception!(breezy.forge, MergeProposalExists); import_exception!(breezy.errors, UnsupportedOperation); import_exception!(breezy.errors, NoRepositoryPresent); import_exception!(breezy.errors, LockFailed); import_exception!(breezy.errors, LockContention); import_exception!(breezy.transport, FileExists); import_exception!(breezy.errors, NoSuchRevisionInTree); import_exception!(breezy.tree, MissingNestedTree); import_exception!(breezy.transform, ImmortalLimbo); import_exception!(breezy.transform, MalformedTransform); import_exception!(breezy.transform, TransformRenameFailed); import_exception!(breezy.errors, UnexpectedHttpStatus); import_exception!(breezy.errors, BadHttpRequest); import_exception!(breezy.errors, TransportNotPossible); import_exception!(breezy.errors, IncompatibleFormat); import_exception!(breezy.errors, NoSuchRevision); import_exception!(breezy.forge, NoSuchProject); import_exception!(breezy.plugins.gitlab.forge, ForkingDisabled); import_exception!(breezy.plugins.gitlab.forge, GitLabConflict); import_exception!(breezy.plugins.gitlab.forge, ProjectCreationTimeout); import_exception!(breezy.forge, SourceNotDerivedFromTarget); import_exception!(breezy.controldir, BranchReferenceLoop); import_exception!(breezy.errors, RedirectRequested); import_exception!(breezy.errors, ConflictsInTree); import_exception!(breezy.errors, NoRoundtrippingSupport); import_exception!(breezy.inter, NoCompatibleInter); lazy_static::lazy_static! { // Only present in breezy << 4.0 pub static ref BreezyConnectionError: Option = { Python::with_gil(|py| { let m = py.import_bound("breezy.errors").unwrap(); m.getattr("ConnectionError").ok().map(|x| x.to_object(py)) }) }; } #[derive(Debug)] pub enum Error { Other(PyErr), UnknownFormat(String), NotBranchError(String, Option), NoColocatedBranchSupport, DependencyNotPresent(String, String), PermissionDenied(std::path::PathBuf, Option), UnsupportedProtocol(String, Option), UnusableRedirect(String, String, String), ConnectionError(String), InvalidURL(String, Option), TransportError(String), UnsupportedFormat(String), UnsupportedVcs(String), RemoteGitError(String), IncompleteRead(Vec, Option), LineEndingError(String), InvalidHttpResponse( String, String, Option, std::collections::HashMap, ), AlreadyControlDir(std::path::PathBuf), AlreadyBranch(std::path::PathBuf), DivergedBranches, WorkspaceDirty(std::path::PathBuf), NoSuchFile(std::path::PathBuf), PointlessCommit, NoWhoami, NoSuchTag(String), TagAlreadyExists(String), Socket(std::io::Error), ForgeLoginRequired, UnsupportedForge(url::Url), ForgeProjectExists(String), MergeProposalExists(url::Url, Option), UnsupportedOperation(String, String), ProtectedBranchHookDeclined(String), NoRepositoryPresent, LockFailed(String), FileExists(std::path::PathBuf, Option), LockContention(String, String), NotImplemented, NoSuchRevisionInTree(crate::RevisionId), MissingNestedTree(std::path::PathBuf), /// Failed to delete transform temporary directory ImmortalLimbo(std::path::PathBuf), MalformedTransform(Vec), TransformRenameFailed( std::path::PathBuf, std::path::PathBuf, String, std::io::Error, ), UnexpectedHttpStatus { url: url::Url, code: u16, extra: Option, headers: std::collections::HashMap, }, Timeout, BadHttpRequest(Url, String), TransportNotPossible(String), IncompatibleFormat(String, String), NoSuchRevision(crate::RevisionId), NoSuchProject(String), ForkingDisabled(String), ProjectCreationTimeout(String, chrono::Duration), GitLabConflict(String), SourceNotDerivedFromTarget, BranchReferenceLoop, RedirectRequested { source: url::Url, target: url::Url, is_permanent: bool, }, ConflictsInTree, NoRoundtrippingSupport, NoCompatibleInter, ReadOnly, } impl From for Error { fn from(e: url::ParseError) -> Self { Error::InvalidURL(e.to_string(), None) } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Self::Other(e) => write!(f, "Error::Other({})", e), Self::UnknownFormat(s) => write!(f, "Unknown format: {}", s), Self::NotBranchError(path, detail) => { if let Some(detail) = detail { write!(f, "Not a branch: {}: {}", path, detail) } else { write!(f, "Not a branch: {}", path) } } Self::NoColocatedBranchSupport => write!(f, "No colocated branch support"), Self::DependencyNotPresent(d, r) => write!(f, "Dependency {} not present: {}", d, r), Self::PermissionDenied(p, r) => { if let Some(r) = r { write!(f, "Permission denied: {}: {}", p.display(), r) } else { write!(f, "Permission denied: {}", p.display()) } } Self::UnsupportedProtocol(p, r) => { if let Some(r) = r { write!(f, "Unsupported protocol: {}: {}", p, r) } else { write!(f, "Unsupported protocol: {}", p) } } Self::UnusableRedirect(p, r, u) => { write!(f, "Unusable redirect: {}: {} -> {}", p, r, u) } Self::ConnectionError(e) => write!(f, "Connection error: {}", e), Self::InvalidURL(p, r) => { if let Some(r) = r { write!(f, "Invalid URL: {}: {}", p, r) } else { write!(f, "Invalid URL: {}", p) } } Self::TransportError(e) => write!(f, "Transport error: {}", e), Self::UnsupportedFormat(s) => write!(f, "Unsupported format: {}", s), Self::UnsupportedVcs(s) => write!(f, "Unsupported VCS: {}", s), Self::RemoteGitError(e) => write!(f, "Remote Git error: {}", e), Self::IncompleteRead(partial, expected) => { write!(f, "Incomplete read: {:?} {:?}", partial, expected) } Self::LineEndingError(e) => write!(f, "Line ending error: {}", e), Self::InvalidHttpResponse(s, c, b, _hs) => { if let Some(b) = b { write!(f, "Invalid HTTP response: {} {}: {}", s, c, b) } else { write!(f, "Invalid HTTP response: {} {}", s, c) } } Self::AlreadyControlDir(p) => write!(f, "Already exists: {}", p.display()), Self::AlreadyBranch(p) => write!(f, "Already a branch: {}", p.display()), Self::DivergedBranches => write!(f, "Diverged branches"), Self::WorkspaceDirty(p) => write!(f, "Workspace dirty at {}", p.display()), Self::NoSuchFile(p) => write!(f, "No such file: {}", p.to_string_lossy()), Self::PointlessCommit => write!(f, "Pointless commit"), Self::NoWhoami => write!(f, "No whoami"), Self::NoSuchTag(tag) => write!(f, "No such tag: {}", tag), Self::TagAlreadyExists(tag) => write!(f, "Tag already exists: {}", tag), Self::Socket(e) => write!(f, "socket error: {}", e), Self::ForgeLoginRequired => write!(f, "Forge login required"), Self::UnsupportedForge(url) => write!(f, "Unsupported forge: {}", url), Self::ForgeProjectExists(p) => write!(f, "Forge project exists: {}", p), Self::MergeProposalExists(p, r) => { if let Some(r) = r { write!(f, "Merge proposal exists: {} -> {}", p, r) } else { write!(f, "Merge proposal exists: {}", p) } } Self::UnsupportedOperation(a, b) => write!(f, "Unsupported operation: {} on {}", a, b), Self::ProtectedBranchHookDeclined(e) => { write!(f, "Protected branch hook declined: {}", e) } Self::NoRepositoryPresent => write!(f, "No repository present"), Self::LockFailed(w) => write!(f, "Lock failed: {}", w), Self::FileExists(p, r) => { if let Some(r) = r { write!(f, "File exists: {}: {}", p.display(), r) } else { write!(f, "File exists: {}", p.display()) } } Self::LockContention(a, b) => write!(f, "Lock contention: {} {}", a, b), Self::NotImplemented => write!(f, "Not implemented"), Self::NoSuchRevisionInTree(rev) => write!(f, "No such revision in tree: {}", rev), Self::MissingNestedTree(p) => write!(f, "Missing nested tree: {}", p.display()), Self::ImmortalLimbo(p) => write!( f, "Failed to delete transform temporary directory: {}", p.display() ), Self::MalformedTransform(e) => write!(f, "Malformed transform: {:?}", e), Self::TransformRenameFailed(a, b, c, d) => write!( f, "Transform rename failed: {} -> {}: {}: {}", a.display(), b.display(), c, d ), Self::UnexpectedHttpStatus { url, code, extra, headers: _, } => { if let Some(extra) = extra { write!(f, "Unexpected HTTP status: {} {}: {}", url, code, extra) } else { write!(f, "Unexpected HTTP status: {} {}", url, code) } } Self::Timeout => write!(f, "Timeout"), Self::BadHttpRequest(url, msg) => write!(f, "Bad HTTP request: {} {}", url, msg), Self::TransportNotPossible(e) => write!(f, "Transport not possible: {}", e), Self::IncompatibleFormat(a, b) => { write!(f, "Incompatible format: {} is not compatible with {}", a, b) } Self::NoSuchRevision(rev) => write!(f, "No such revision: {}", rev), Self::NoSuchProject(p) => write!(f, "No such project: {}", p), Self::ForkingDisabled(p) => write!(f, "Forking disabled: {}", p), Self::ProjectCreationTimeout(p, t) => { write!(f, "Project creation timeout: {} after {} seconds", p, t) } Self::GitLabConflict(p) => write!(f, "GitLab conflict: {}", p), Self::ConflictsInTree => write!(f, "Conflicts in tree"), Self::SourceNotDerivedFromTarget => write!(f, "Source not derived from target"), Self::BranchReferenceLoop => write!(f, "Branch reference loop"), Self::NoRoundtrippingSupport => write!(f, "No roundtripping support"), Self::NoCompatibleInter => write!(f, "No compatible inter"), Self::ReadOnly => write!(f, "Read-only"), Self::RedirectRequested { source, target, is_permanent, } => { write!( f, "Redirect requested: {} -> {} (permanent: {})", source, target, is_permanent ) } } } } impl std::error::Error for Error {} impl From for Error { fn from(err: PyErr) -> Self { pyo3::import_exception!(socket, error); pyo3::Python::with_gil(|py| { let value = err.value_bound(py); if err.is_instance_of::(py) { Error::UnknownFormat(value.getattr("format").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::NotBranchError( value.getattr("path").unwrap().extract().unwrap(), value.getattr("detail").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::NoColocatedBranchSupport } else if err.is_instance_of::(py) { Error::DependencyNotPresent( value.getattr("library").unwrap().extract().unwrap(), value.getattr("error").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::PermissionDenied( value.getattr("path").unwrap().extract().unwrap(), value.getattr("extra").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::UnsupportedProtocol( value.getattr("url").unwrap().extract().unwrap(), value.getattr("extra").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::UnusableRedirect( value.getattr("source").unwrap().extract().unwrap(), value.getattr("target").unwrap().extract().unwrap(), value.getattr("reason").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::InvalidURL( value.getattr("path").unwrap().extract().unwrap(), value.getattr("extra").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::ConnectionError(err.to_string()) } else if err.is_instance_of::(py) { Error::UnsupportedFormat(value.getattr("format").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::UnsupportedVcs(value.getattr("vcs").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { if let Ok(e) = value.getattr("msg").unwrap().extract() { Error::RemoteGitError(e) } else { // Just get it from the args tuple Error::RemoteGitError(value.getattr("args").unwrap().extract().unwrap()) } } else if err.is_instance_of::(py) { Error::IncompleteRead( value.getattr("partial").unwrap().extract().unwrap(), value.getattr("expected").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::LineEndingError(value.getattr("file").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::AlreadyControlDir(value.getattr("path").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::AlreadyBranch(value.getattr("path").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::DivergedBranches } else if err.is_instance_of::(py) { let value = err.into_value(py); let tree = value.getattr(py, "tree").unwrap(); let path = value.getattr(py, "path").unwrap(); let path = tree .call_method1(py, "abspath", (path,)) .unwrap() .extract::(py) .unwrap(); Error::WorkspaceDirty(std::path::PathBuf::from(path)) } else if err.is_instance_of::(py) { Error::NoSuchFile(std::path::PathBuf::from( value.getattr("path").unwrap().extract::().unwrap(), )) } else if err.is_instance_of::(py) { Error::PointlessCommit } else if err.is_instance_of::(py) { Error::NoWhoami } else if err.is_instance_of::(py) { Error::NoSuchTag(value.getattr("tag_name").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::TagAlreadyExists(value.getattr("tag_name").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::Socket(std::io::Error::from_raw_os_error( value.getattr("errno").unwrap().extract().unwrap(), )) } else if err.is_instance_of::(py) { Error::ForgeLoginRequired } else if err.is_instance_of::(py) { let branch = value.getattr("branch").unwrap(); if let Ok(url) = branch.getattr("user_url") { Error::UnsupportedForge(url.extract::().unwrap().parse().unwrap()) } else { Error::UnsupportedForge(branch.extract::().unwrap().parse().unwrap()) } } else if err.is_instance_of::(py) { let source_url: String = value.getattr("url").unwrap().extract().unwrap(); let existing_proposal = value.getattr("existing_proposal").unwrap(); let target_url: Option = if existing_proposal.is_none() { None } else { Some(existing_proposal.getattr("url").unwrap().extract().unwrap()) }; Error::MergeProposalExists( source_url.parse().unwrap(), target_url.map(|u| u.parse().unwrap()), ) } else if err.is_instance_of::(py) { Error::UnsupportedOperation( value.getattr("mname").unwrap().extract().unwrap(), value.getattr("tname").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::ProtectedBranchHookDeclined(value.getattr("msg").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::NoRepositoryPresent } else if err.is_instance_of::(py) { let why = value.getattr("why").unwrap(); if why.is_none() { Error::LockFailed("".to_string()) } else { let why = why.call_method0("__str__").unwrap(); Error::LockFailed(why.extract().unwrap()) } } else if err.is_instance_of::(py) { Error::FileExists( std::path::PathBuf::from( value.getattr("path").unwrap().extract::().unwrap(), ), value.getattr("extra").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::LockContention( value .getattr("lock") .unwrap() .call_method0("__str__") .unwrap() .extract() .unwrap(), value.getattr("msg").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::NotImplemented } else if err.is_instance_of::(py) { Error::NoSuchRevisionInTree( value.getattr("revision_id").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::MissingNestedTree(std::path::PathBuf::from( value.getattr("path").unwrap().extract::().unwrap(), )) } else if err.is_instance_of::(py) { Error::ImmortalLimbo(std::path::PathBuf::from( value .getattr("limbo_dir") .unwrap() .extract::() .unwrap(), )) } else if err.is_instance_of::(py) { Error::MalformedTransform(value.getattr("conflicts").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::TransformRenameFailed( std::path::PathBuf::from( value .getattr("from_path") .unwrap() .extract::() .unwrap(), ), std::path::PathBuf::from( value .getattr("to_path") .unwrap() .extract::() .unwrap(), ), value.getattr("why").unwrap().extract().unwrap(), std::io::Error::from_raw_os_error( value.getattr("errno").unwrap().extract::().unwrap(), ), ) } else if err.is_instance_of::(py) { Error::UnexpectedHttpStatus { url: value .getattr("path") .unwrap() .extract::() .unwrap() .parse() .unwrap(), code: value.getattr("code").unwrap().extract().unwrap(), extra: value.getattr("extra").unwrap().extract().unwrap(), headers: value.getattr("headers").unwrap().extract().unwrap(), } } else if err.is_instance_of::(py) { Error::Timeout } else if err.is_instance_of::(py) { Error::BadHttpRequest( value .getattr("path") .unwrap() .extract::() .unwrap() .parse() .unwrap(), value.getattr("reason").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::TransportNotPossible(value.getattr("msg").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { let format = value.getattr("format").unwrap(); let controldir = value.getattr("controldir").unwrap(); Error::IncompatibleFormat( if let Ok(format) = format.extract::() { format } else { format .call_method0("get_format_string") .unwrap() .extract() .unwrap() }, if let Ok(controldir) = controldir.extract::() { controldir } else { controldir .call_method0("get_format_string") .unwrap() .extract() .unwrap() }, ) } else if err.is_instance_of::(py) { Error::NoSuchRevision(value.getattr("revision").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::NoSuchProject(value.getattr("project").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::ForkingDisabled(value.getattr("project").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::ProjectCreationTimeout( value.getattr("project").unwrap().extract().unwrap(), value.getattr("timeout").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::GitLabConflict(value.getattr("reason").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::ConflictsInTree } else if err.is_instance_of::(py) { Error::SourceNotDerivedFromTarget } else if BreezyConnectionError .as_ref() .and_then(|cls| { Python::with_gil(|py| Some(err.is_instance_bound(py, cls.bind(py)))) }) .unwrap_or(false) { Error::ConnectionError(err.to_string()) } else if err.is_instance_of::(py) { Error::ReadOnly } else if err.is_instance_of::(py) { Error::RedirectRequested { source: value .getattr("source") .unwrap() .extract::() .unwrap() .parse() .unwrap(), target: value .getattr("target") .unwrap() .extract::() .unwrap() .parse() .unwrap(), is_permanent: value.getattr("is_permanent").unwrap().extract().unwrap(), } } else if err.is_instance_of::(py) { Error::NoRoundtrippingSupport } else if err.is_instance_of::(py) { Error::NoCompatibleInter // Intentionally sorted below the more specific errors } else if err.is_instance_of::(py) { Error::InvalidHttpResponse( value.getattr("path").unwrap().extract().unwrap(), value.getattr("msg").unwrap().extract().unwrap(), value.getattr("orig_error").unwrap().extract().unwrap(), value.getattr("headers").unwrap().extract().unwrap(), ) } else if err.is_instance_of::(py) { Error::TransportError(value.getattr("msg").unwrap().extract().unwrap()) } else if err.is_instance_of::(py) { Error::BranchReferenceLoop } else { if std::env::var("BRZ_ERROR").is_ok() { // Print backtrace err.print(py); } Self::Other(err) } }) } } impl From for PyErr { fn from(e: Error) -> Self { match e { Error::Other(e) => e, Error::UnknownFormat(s) => UnknownFormatError::new_err((s,)), Error::NotBranchError(path, details) => NotBranchError::new_err((path, details)), Error::NoColocatedBranchSupport => { Python::with_gil(|py| NoColocatedBranchSupport::new_err((py.None(),))) } Error::DependencyNotPresent(library, error) => { DependencyNotPresent::new_err((library, error)) } Error::PermissionDenied(path, reason) => PermissionDenied::new_err((path, reason)), Error::UnsupportedProtocol(url, error) => UnsupportedProtocol::new_err((url, error)), Error::UnusableRedirect(source, target, reason) => { UnusableRedirect::new_err((source, target, reason)) } Error::ConnectionError(e) => pyo3::exceptions::PyConnectionError::new_err((e,)), Error::InvalidURL(path, reason) => InvalidURL::new_err((path, reason)), Error::TransportError(e) => TransportError::new_err((e,)), Error::UnsupportedFormat(s) => UnsupportedFormatError::new_err((s,)), Error::UnsupportedVcs(s) => UnsupportedVcs::new_err((s,)), Error::RemoteGitError(e) => RemoteGitError::new_err((e,)), Error::IncompleteRead(partial, expected) => Python::with_gil(|py| { let bytes = pyo3::types::PyBytes::new_bound(py, partial.as_slice()); IncompleteRead::new_err((bytes.unbind(), expected)) }), Error::LineEndingError(e) => LineEndingError::new_err((e,)), Error::InvalidHttpResponse(status, msg, orig_error, headers) => { InvalidHttpResponse::new_err((status, msg, orig_error, headers)) } Error::AlreadyControlDir(path) => { AlreadyControlDirError::new_err((path.to_string_lossy().to_string(),)) } Error::AlreadyBranch(path) => { AlreadyBranchError::new_err((path.to_string_lossy().to_string(),)) } Error::DivergedBranches => { Python::with_gil(|py| DivergedBranches::new_err((py.None(), py.None()))) } Error::WorkspaceDirty(p) => WorkspaceDirty::new_err((p.to_string_lossy().to_string(),)), Error::NoSuchFile(p) => NoSuchFile::new_err(p.to_string_lossy().to_string()), Error::PointlessCommit => PointlessCommit::new_err(()), Error::NoWhoami => NoWhoami::new_err(()), Error::NoSuchTag(tag) => NoSuchTag::new_err((tag,)), Error::TagAlreadyExists(tag) => TagAlreadyExists::new_err((tag,)), Error::Socket(e) => { pyo3::import_exception!(socket, error); error::new_err((e.raw_os_error().unwrap(),)) } Error::ForgeLoginRequired => { Python::with_gil(|py| ForgeLoginRequired::new_err((py.None(),))) } Error::UnsupportedForge(url) => UnsupportedForge::new_err((url.to_string(),)), Error::ForgeProjectExists(name) => AlreadyControlDirError::new_err((name.to_string(),)), Error::MergeProposalExists(source, _target) => { Python::with_gil(|py| MergeProposalExists::new_err((source.to_string(), py.None()))) } Error::UnsupportedOperation(mname, tname) => { UnsupportedOperation::new_err((mname, tname)) } Error::ProtectedBranchHookDeclined(msg) => ProtectedBranchHookDeclined::new_err((msg,)), Error::NoRepositoryPresent => { Python::with_gil(|py| NoRepositoryPresent::new_err((py.None(),))) } Error::LockFailed(why) => Python::with_gil(|py| LockFailed::new_err((py.None(), why))), Error::FileExists(p, extra) => { FileExists::new_err((p.to_string_lossy().to_string(), extra)) } Error::LockContention(_lock, msg) => { Python::with_gil(|py| LockContention::new_err((py.None(), msg))) } Error::NotImplemented => pyo3::exceptions::PyNotImplementedError::new_err(()), Error::NoSuchRevisionInTree(rev) => { Python::with_gil(|py| NoSuchRevisionInTree::new_err((py.None(), rev.to_string()))) } Error::MissingNestedTree(p) => { MissingNestedTree::new_err((p.to_string_lossy().to_string(),)) } Error::ImmortalLimbo(p) => ImmortalLimbo::new_err((p.to_string_lossy().to_string(),)), Error::MalformedTransform(conflicts) => { MalformedTransform::new_err((Python::with_gil(|py| conflicts.to_object(py)),)) } Error::TransformRenameFailed(from_path, to_path, why, error) => { TransformRenameFailed::new_err(( from_path.to_string_lossy().to_string(), to_path.to_string_lossy().to_string(), why, PyErr::from(error), )) } Error::UnexpectedHttpStatus { url, code, extra, headers, } => UnexpectedHttpStatus::new_err((url.to_string(), code, extra, headers)), Error::Timeout => pyo3::exceptions::PyTimeoutError::new_err(()), Error::BadHttpRequest(url, reason) => { BadHttpRequest::new_err((url.to_string(), reason)) } Error::TransportNotPossible(e) => TransportNotPossible::new_err((e,)), Error::IncompatibleFormat(a, b) => IncompatibleFormat::new_err((a, b)), Error::NoSuchRevision(rev) => { Python::with_gil(|py| NoSuchRevision::new_err((py.None(), rev.to_string()))) } Error::NoSuchProject(p) => NoSuchProject::new_err((p,)), Error::ForkingDisabled(p) => ForkingDisabled::new_err((p,)), Error::ProjectCreationTimeout(p, t) => ProjectCreationTimeout::new_err((p, t)), Error::GitLabConflict(p) => GitLabConflict::new_err((p,)), Error::ConflictsInTree => ConflictsInTree::new_err(()), Error::SourceNotDerivedFromTarget => SourceNotDerivedFromTarget::new_err(()), Error::BranchReferenceLoop => BranchReferenceLoop::new_err(()), Error::ReadOnly => Python::with_gil(|py| ReadOnlyError::new_err((py.None(),))), Error::RedirectRequested { source, target, is_permanent, } => RedirectRequested::new_err((source.to_string(), target.to_string(), is_permanent)), Error::NoRoundtrippingSupport => { Python::with_gil(|py| NoRoundtrippingSupport::new_err((py.None(), py.None()))) } Error::NoCompatibleInter => { Python::with_gil(|py| NoCompatibleInter::new_err((py.None(), py.None()))) } } } } #[test] fn test_error_unknownformat() { let e = Error::UnknownFormat("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of UnknownFormatError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_notbrancherror() { let e = Error::NotBranchError("foo".to_string(), Some("bar".to_string())); let p: PyErr = e.into(); // Verify that p is an instance of NotBranchError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_nocolocatedbranchsupport() { let e = Error::NoColocatedBranchSupport; let p: PyErr = e.into(); // Verify that p is an instance of NoColocatedBranchSupport Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_dependencynotpresent() { let e = Error::DependencyNotPresent("foo".to_string(), "bar".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of DependencyNotPresent Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_permissiondenied() { let e = Error::PermissionDenied(std::path::PathBuf::from("foo"), Some("bar".to_string())); let p: PyErr = e.into(); // Verify that p is an instance of PermissionDenied Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_unsupportedprotocol() { let e = Error::UnsupportedProtocol("foo".to_string(), Some("bar".to_string())); let p: PyErr = e.into(); // Verify that p is an instance of UnsupportedProtocol Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_unusableredirect() { let e = Error::UnusableRedirect("foo".to_string(), "bar".to_string(), "baz".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of UnusableRedirect Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_connectionerror() { let e = Error::ConnectionError("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of PyConnectionError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_invalidurl() { let e = Error::InvalidURL("foo".to_string(), Some("bar".to_string())); let p: PyErr = e.into(); // Verify that p is an instance of InvalidURL Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_transporterror() { let e = Error::TransportError("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of TransportError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_unsupportedformat() { let e = Error::UnsupportedFormat("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of UnsupportedFormatError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_unsupportedvcs() { let e = Error::UnsupportedVcs("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of UnsupportedVcs Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_remotegiterror() { let e = Error::RemoteGitError("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of RemoteGitError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_incompleteread() { let e = Error::IncompleteRead(vec![1, 2, 3], Some(4)); let p: PyErr = e.into(); // Verify that p is an instance of IncompleteRead Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_lineendingerror() { let e = Error::LineEndingError("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of LineEndingError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_invalidhttpresponse() { let e = Error::InvalidHttpResponse( "foo".to_string(), "bar".to_string(), Some("baz".to_string()), std::collections::HashMap::new(), ); let p: PyErr = e.into(); // Verify that p is an instance of InvalidHttpResponse Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_alreadyexists() { let e = Error::AlreadyControlDir(std::path::PathBuf::from("foo")); let p: PyErr = e.into(); // Verify that p is an instance of AlreadyControlDirError Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_divergedbranches() { let e = Error::DivergedBranches; let p: PyErr = e.into(); // Verify that p is an instance of DivergedBranches Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] #[ignore] // WorkspaceDirty takes a tree argument, which is not implemented fn test_error_workspacedirty() { let e = Error::WorkspaceDirty(std::path::PathBuf::from("foo")); let p: PyErr = e.into(); // Verify that p is an instance of WorkspaceDirty Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_nosuchfile() { let e = Error::NoSuchFile(std::path::PathBuf::from("foo")); let p: PyErr = e.into(); // Verify that p is an instance of NoSuchFile Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_pointlesscommit() { let e = Error::PointlessCommit; let p: PyErr = e.into(); // Verify that p is an instance of PointlessCommit Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_nowhoami() { let e = Error::NoWhoami; let p: PyErr = e.into(); // Verify that p is an instance of NoWhoami Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_nosuchtag() { let e = Error::NoSuchTag("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of NoSuchTag Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_tagalreadyexists() { let e = Error::TagAlreadyExists("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of TagAlreadyExists Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_socket() { let e = Error::Socket(std::io::Error::from_raw_os_error(0)); let p: PyErr = e.into(); // Verify that p is an instance of error Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_other() { let e = Error::Other(PyErr::new::((("foo",),))); let p: PyErr = e.into(); // Verify that p is an instance of error Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_forge_login_required() { let e = Error::ForgeLoginRequired; let p: PyErr = e.into(); // Verify that p is an instance of ForgeLoginRequired Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_unsupported_forge() { let e = Error::UnsupportedForge("http://example.com".parse().unwrap()); let p: PyErr = e.into(); // Verify that p is an instance of UnsupportedForge Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_error_forge_project_exists() { let e = Error::ForgeProjectExists("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of AlreadyControlDirError Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_merge_proposal_exists() { let e = Error::MergeProposalExists( "http://source.com".parse().unwrap(), Some("http://target.com".parse().unwrap()), ); let p: PyErr = e.into(); // Verify that p is an instance of MergeProposalExists Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] #[ignore] // UnsupportedOperation takes two arguments, which is not implemented fn test_error_unsupported_operation() { let e = Error::UnsupportedOperation("foo".to_string(), "bar".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of UnsupportedOperation Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_protected_branch_hook_declined() { let e = Error::ProtectedBranchHookDeclined("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of ProtectedBranchHookDeclined Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] #[ignore] // NoRepositoryPresent takes an argument, which is not implemented fn test_error_no_repository_present() { let e = Error::NoRepositoryPresent; let p: PyErr = e.into(); // Verify that p is an instance of NoRepositoryPresent Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] #[ignore] // LockFailed takes a lockfile argument, which is not implemented fn test_error_lock_failed() { let e = Error::LockFailed("bar".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of LockFailed Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_file_exists() { let e = Error::FileExists(std::path::PathBuf::from("foo"), Some("bar".to_string())); let p: PyErr = e.into(); // Verify that p is an instance of FileExists Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_lock_contention() { let e = Error::LockContention("foo".to_string(), "bar".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of LockContention Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_error_notimplementederror() { let e = Error::NotImplemented; let p: PyErr = e.into(); // Verify that p is an instance of PyNotImplementedError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_missing_nested_tree() { let e = Error::MissingNestedTree(std::path::PathBuf::from("foo")); let p: PyErr = e.into(); // Verify that p is an instance of MissingNestedTree Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_immortal_limbo() { let e = Error::ImmortalLimbo(std::path::PathBuf::from("foo")); let p: PyErr = e.into(); // Verify that p is an instance of ImmortalLimbo Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_malformed_transform() { let e = Error::MalformedTransform(vec![]); let p: PyErr = e.into(); // Verify that p is an instance of MalformedTransform Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_transform_rename_failed() { let e = Error::TransformRenameFailed( std::path::PathBuf::from("foo"), std::path::PathBuf::from("bar"), "baz".to_string(), std::io::Error::new(std::io::ErrorKind::NotFound, "foo"), ); let p: PyErr = e.into(); // Verify that p is an instance of TransformRenameFailed Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p,); }); } #[test] fn test_unexpected_http_status() { let e = Error::UnexpectedHttpStatus { url: url::Url::parse("http://example.com").unwrap(), code: 404, extra: Some("bar".to_string()), headers: std::collections::HashMap::new(), }; let p: PyErr = e.into(); // Verify that p is an instance of UnexpectedHttpStatus Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_timeout() { let e = Error::Timeout; let p: PyErr = e.into(); // Verify that p is an instance of PyTimeoutError Python::with_gil(|py| { assert!(p.is_instance_of::(py)); }); } #[test] fn test_bad_http_request() { let e = Error::BadHttpRequest("http://example.com".parse().unwrap(), "foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of BadHttpRequest Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_transport_not_possible() { let e = Error::TransportNotPossible("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of TransportNotPossible Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_incompatible_format() { let e = Error::IncompatibleFormat("foo".to_string(), "bar".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of IncompatibleFormat Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_no_such_project() { let e = Error::NoSuchProject("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of NoSuchProject Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_forking_disabled() { let e = Error::ForkingDisabled("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of ForkingDisabled Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_gitlab_conflict() { let e = Error::GitLabConflict("foo".to_string()); let p: PyErr = e.into(); // Verify that p is an instance of GitLabConflict Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_conflicts_in_tree() { let e = Error::ConflictsInTree; let p: PyErr = e.into(); // Verify that p is an instance of ConflictsInTree Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_project_creation_timeout() { let e = Error::ProjectCreationTimeout("foo".to_string(), chrono::Duration::seconds(0)); let p: PyErr = e.into(); // Verify that p is an instance of ProjectCreationTimeout Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_already_branch() { let e = Error::AlreadyBranch(std::path::PathBuf::from("foo")); let p: PyErr = e.into(); // Verify that p is an instance of AlreadyBranchError Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } #[test] fn test_redirect_requested() { let e = Error::RedirectRequested { source: "http://example.com".parse().unwrap(), target: "http://example.com".parse().unwrap(), is_permanent: true, }; let p: PyErr = e.into(); // Verify that p is an instance of RedirectRequested Python::with_gil(|py| { assert!(p.is_instance_of::(py), "{}", p); }); } breezyshim-0.1.227/src/export.rs000064400000000000000000000014311046102023000146330ustar 00000000000000//! Export a tree to a directory. use 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>, ) -> Result<(), crate::error::Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.export").unwrap(); let export = m.getattr("export").unwrap(); let kwargs = PyDict::new_bound(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.227/src/foreign.rs000064400000000000000000000002251046102023000147430ustar 00000000000000#[derive(PartialEq, Eq, Debug, Clone)] pub enum VcsType { Bazaar, Git, Hg, Svn, Fossil, Darcs, Cvs, Arch, Svk, } breezyshim-0.1.227/src/forge.rs000064400000000000000000000537061046102023000144300ustar 00000000000000//! Code hosting services and merge proposals. use crate::branch::{py_tag_selector, Branch, GenericBranch}; use crate::error::Error; use crate::revisionid::RevisionId; use pyo3::conversion::ToPyObject; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyDict; use std::hash::Hash; pub struct Forge(PyObject); impl Clone for Forge { fn clone(&self) -> Self { Forge(Python::with_gil(|py| self.0.clone_ref(py))) } } impl From for Forge { fn from(obj: PyObject) -> Self { Forge(obj) } } impl std::fmt::Debug for MergeProposal { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Just print the URL for now let mut s = f.debug_struct("MergeProposal"); if let Ok(url) = self.url() { s.field("url", &url); } s.finish() } } impl std::fmt::Display for MergeProposal { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let url = self.url().unwrap(); write!(f, "{}", url) } } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] 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 std::fmt::Display for MergeProposalStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { MergeProposalStatus::All => write!(f, "all"), MergeProposalStatus::Open => write!(f, "open"), MergeProposalStatus::Merged => write!(f, "merged"), MergeProposalStatus::Closed => write!(f, "closed"), } } } impl ToPyObject for MergeProposalStatus { fn to_object(&self, py: Python) -> PyObject { self.to_string().to_object(py) } } impl FromPyObject<'_> for MergeProposalStatus { fn extract_bound(ob: &Bound) -> 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 ),))), } } } pub struct MergeProposal(PyObject); impl Clone for MergeProposal { fn clone(&self) -> Self { MergeProposal(Python::with_gil(|py| self.0.clone_ref(py))) } } impl From for MergeProposal { fn from(obj: PyObject) -> Self { MergeProposal(obj) } } impl MergeProposal { pub fn from_url(url: &url::Url) -> Result { get_proposal_by_url(url) } pub fn reopen(&self) -> Result<(), crate::error::Error> { Python::with_gil(|py| { self.0.call_method0(py, "reopen")?; Ok(()) }) } pub fn close(&self) -> Result<(), crate::error::Error> { Python::with_gil(|py| { self.0.call_method0(py, "close")?; Ok(()) }) } pub fn url(&self) -> Result { Python::with_gil(|py| { let url = self.0.getattr(py, "url")?; Ok(url.extract::(py)?.parse().unwrap()) }) } pub fn is_merged(&self) -> Result { Python::with_gil(|py| { let is_merged = self.0.call_method0(py, "is_merged")?; is_merged.extract(py).map_err(|e| e.into()) }) } pub fn is_closed(&self) -> Result { Python::with_gil(|py| { let is_closed = self.0.call_method0(py, "is_closed")?; is_closed.extract(py).map_err(|e| e.into()) }) } pub fn get_title(&self) -> Result, crate::error::Error> { Python::with_gil(|py| { let title = self.0.call_method0(py, "get_title")?; title.extract(py).map_err(|e| e.into()) }) } pub fn set_title(&self, title: Option<&str>) -> Result<(), crate::error::Error> { Python::with_gil(|py| { self.0.call_method1(py, "set_title", (title,))?; Ok(()) }) } pub fn get_commit_message(&self) -> Result, crate::error::Error> { Python::with_gil(|py| { let commit_message = self.0.call_method0(py, "get_commit_message")?; commit_message.extract(py).map_err(|e| e.into()) }) } pub fn set_commit_message( &self, commit_message: Option<&str>, ) -> Result<(), crate::error::Error> { Python::with_gil(|py| { self.0 .call_method1(py, "set_commit_message", (commit_message,))?; Ok(()) }) } pub fn get_target_branch_url(&self) -> Result, crate::error::Error> { 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| e.into()) }) } pub fn get_source_branch_url(&self) -> Result, crate::error::Error> { 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| e.into()) }) } pub fn get_description(&self) -> Result, crate::error::Error> { Python::with_gil(|py| { let description = self.0.call_method0(py, "get_description")?; description.extract(py).map_err(|e| e.into()) }) } pub fn set_description(&self, description: Option<&str>) -> Result<(), crate::error::Error> { Python::with_gil(|py| { self.0.call_method1(py, "set_description", (description,))?; Ok(()) }) } pub fn can_be_merged(&self) -> Result { Python::with_gil(|py| { let can_be_merged = self.0.call_method0(py, "can_be_merged")?; can_be_merged.extract(py).map_err(|e| e.into()) }) } 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(()) }) } pub fn get_web_url(&self) -> Result { Python::with_gil(|py| { let web_url = self.0.call_method0(py, "get_web_url")?; web_url .extract::(py)? .parse::() .map_err(|e| e.into()) }) } pub fn get_merged_by(&self) -> Result, crate::error::Error> { Python::with_gil(|py| { let merged_by = self.0.call_method0(py, "get_merged_by")?; merged_by.extract(py).map_err(|e| e.into()) }) } pub fn get_merged_at( &self, ) -> Result>, crate::error::Error> { Python::with_gil(|py| { let merged_at = self.0.call_method0(py, "get_merged_at")?; merged_at .extract::>>(py) .map_err(|e| e.into()) }) } } #[pyclass] pub struct ProposalBuilder(PyObject, Py); impl ProposalBuilder { pub fn description(self, description: &str) -> Self { Python::with_gil(|py| { self.1 .bind(py) .set_item("description", description) .unwrap(); }); self } pub fn labels(self, labels: &[&str]) -> Self { Python::with_gil(|py| { self.1.bind(py).set_item("labels", labels).unwrap(); }); self } pub fn reviewers(self, reviewers: &[&str]) -> Self { Python::with_gil(|py| { self.1.bind(py).set_item("reviewers", reviewers).unwrap(); }); self } pub fn allow_collaboration(self, allow_collaboration: bool) -> Self { Python::with_gil(|py| { self.1 .bind(py) .set_item("allow_collaboration", allow_collaboration) .unwrap(); }); self } pub fn title(self, title: &str) -> Self { Python::with_gil(|py| { self.1.bind(py).set_item("title", title).unwrap(); }); self } pub fn commit_message(self, commit_message: &str) -> Self { Python::with_gil(|py| { self.1 .bind(py) .set_item("commit_message", commit_message) .unwrap(); }); self } pub fn build(self) -> Result { Python::with_gil(|py| { let kwargs = self.1; let proposal = self.0 .call_method_bound(py, "create_proposal", (), Some(kwargs.bind(py)))?; Ok(MergeProposal::from(proposal)) }) } } impl Forge { pub fn get_proposal_by_url( &self, url: &url::Url, ) -> Result { 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 get_web_url(&self, branch: &dyn Branch) -> Result { Python::with_gil(|py| { let url = self .to_object(py) .call_method1(py, "get_web_url", (&branch.to_object(py),))? .extract::(py) .unwrap(); Ok(url.parse::().unwrap()) }) } 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) .bind(py) .get_type() .name() .unwrap() .to_string() }) } pub fn forge_name(&self) -> String { Python::with_gil(|py| { self.to_object(py) .bind(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 supports_merge_proposal_labels(&self) -> bool { Python::with_gil(|py| { let supports_merge_proposal_labels = self .to_object(py) .getattr(py, "supports_merge_proposal_labels") .unwrap(); supports_merge_proposal_labels.extract(py).unwrap() }) } pub fn get_proposer( &self, from_branch: &dyn Branch, to_branch: &dyn Branch, ) -> Result { 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_bound(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_bound( py, "iter_my_proposals", (status.to_object(py), author), None, )? .bind(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]>, ) -> Result, crate::error::Error> { Python::with_gil(|py| { let kwargs = PyDict::new_bound(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_bound( py, "get_derived_branch", (main_branch.to_object(py), name), Some(&kwargs), )?; Ok(Box::new(GenericBranch::new(branch)) as Box) }) } pub fn iter_proposals( &self, source_branch: &dyn Branch, target_branch: &dyn Branch, status: MergeProposalStatus, ) -> Result, crate::error::Error> { Python::with_gil(move |py| { let kwargs = PyDict::new_bound(py); kwargs.set_item("status", status.to_string())?; let proposal_iter: PyObject = self .0 .call_method_bound( py, "iter_proposals", (&source_branch.to_object(py), &target_branch.to_object(py)), Some(&kwargs), )? .extract(py)?; let mut ret = Vec::new(); loop { match proposal_iter.call_method0(py, "__next__") { Ok(proposal) => { ret.push(MergeProposal::from(proposal)); } Err(e) => { if e.is_instance_of::(py) { break; } else { return Err(e.into()); } } } } Ok(ret.into_iter()) }) } pub fn publish_derived( &self, local_branch: &dyn Branch, base_branch: &dyn Branch, name: &str, overwrite: Option, owner: Option<&str>, revision_id: Option<&RevisionId>, tag_selector: Option bool>>, ) -> Result<(Box, url::Url), crate::error::Error> { Python::with_gil(|py| { let kwargs = PyDict::new_bound(py); kwargs.set_item("local_branch", local_branch.to_object(py))?; kwargs.set_item("base_branch", base_branch.to_object(py))?; kwargs.set_item("name", name)?; if let Some(overwrite) = overwrite { kwargs.set_item("overwrite", overwrite)?; } if let Some(owner) = owner { kwargs.set_item("owner", owner)?; } if let Some(revision_id) = revision_id { kwargs.set_item("revision_id", revision_id)?; } 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_bound(py, "publish_derived", (), Some(&kwargs))? .extract(py)?; Ok(( Box::new(GenericBranch::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() }) } pub fn get_user_url(&self, user: &str) -> Result { Python::with_gil(|py| { let url = self .to_object(py) .call_method1(py, "get_user_url", (user,)) .unwrap() .extract::(py) .unwrap(); Ok(url.parse::().unwrap()) }) } pub fn get_current_user(&self) -> Result, crate::error::Error> { Python::with_gil(|py| { let user = self .to_object(py) .call_method0(py, "get_current_user") .unwrap() .extract::>(py) .unwrap(); Ok(user) }) } } impl std::fmt::Debug for Forge { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut s = f.debug_struct("Forge"); if let Ok(base_url) = self.base_url().to_string().parse::() { s.field("base_url", &base_url); } s.finish() } } impl std::fmt::Display for Forge { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let base_url = self.base_url(); write!(f, "{}", base_url) } } impl FromPyObject<'_> for Forge { fn extract_bound(ob: &Bound) -> 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_bound("breezy.forge").unwrap(); let forge = m.call_method1("get_forge", (branch.to_object(py),))?; Ok(Forge(forge.to_object(py))) }) } pub fn get_forge_by_hostname(hostname: &str) -> Result { Python::with_gil(|py| { let m = py.import_bound("breezy.forge").unwrap(); let forge = m.call_method1("get_forge_by_hostname", (hostname,))?; Ok(Forge(forge.to_object(py))) }) } pub fn determine_title(description: &str) -> Result { Python::with_gil(|py| { let m = py.import_bound("breezy.forge").unwrap(); let title = match m.call_method1("determine_title", (description,)) { Ok(title) => title, Err(e) => return Err(e.to_string()), }; match title.extract::() { Ok(title) => Ok(title), Err(e) => Err(e.to_string()), } }) } pub fn iter_forge_instances() -> impl Iterator { let ret = Python::with_gil(|py| { let m = py.import_bound("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_bound("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_bound("breezy.forge").unwrap(); let proposal = m.call_method1("get_proposal_by_url", (url.to_string(),))?; Ok(MergeProposal::from(proposal.to_object(py))) }) } #[cfg(test)] mod tests { #[test] fn test_determine_title() { let description = "This is a test description"; let title = super::determine_title(description).unwrap(); assert_eq!(title, "This is a test description"); } #[test] fn test_determine_title_invalid() { let description = ""; assert_eq!( "ValueError: ", super::determine_title(description).unwrap_err() ); } } breezyshim-0.1.227/src/fossil.rs000064400000000000000000000030041046102023000146070ustar 00000000000000//! Support for detecting Fossil repositories. //! //! This module provides a prober for detecting Fossil repositories, but //! currently does not provide any additional functionality. use crate::controldir::Prober; use pyo3::exceptions::PyModuleNotFoundError; use pyo3::prelude::*; pub struct RemoteFossilProber(PyObject); impl RemoteFossilProber { pub fn new() -> Option { Python::with_gil(|py| { let m = match py.import_bound("breezy.plugins.fossil") { Ok(m) => m, Err(e) => { if e.is_instance_of::(py) { return None; } else { e.print_and_set_sys_last_vars(py); panic!("Failed to import breezy.plugins.fossil"); } } }; let prober = m .getattr("RemoteFossilProber") .expect("Failed to get RemoteFossilProber"); Some(Self(prober.to_object(py))) }) } } impl FromPyObject<'_> for RemoteFossilProber { fn extract_bound(obj: &Bound) -> PyResult { Ok(Self(obj.to_object(obj.py()))) } } impl ToPyObject for RemoteFossilProber { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Prober for RemoteFossilProber {} #[cfg(test)] mod tests { use super::*; #[test] fn test_remote_fossil_prober() { let _ = RemoteFossilProber::new(); } } breezyshim-0.1.227/src/git.rs000064400000000000000000000044341046102023000141030ustar 00000000000000//! Git version control system support. use crate::controldir::Prober; use pyo3::exceptions::PyModuleNotFoundError; use pyo3::prelude::*; pub struct RemoteGitProber(PyObject); pub const ZERO_SHA: &[u8] = b"0000000000000000000000000000000000000000"; impl RemoteGitProber { pub fn new() -> Option { Python::with_gil(|py| { let m = match py.import_bound("breezy.git") { Ok(m) => m, Err(e) => { if e.is_instance_of::(py) { return None; } else { e.print_and_set_sys_last_vars(py); panic!("Failed to import breezy.git"); } } }; let prober = m .getattr("RemoteGitProber") .expect("Failed to get GitProber"); Some(Self(prober.to_object(py))) }) } } impl FromPyObject<'_> for RemoteGitProber { fn extract_bound(obj: &Bound) -> PyResult { Ok(Self(obj.to_object(obj.py()))) } } impl ToPyObject for RemoteGitProber { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Prober for RemoteGitProber {} pub struct BareLocalGitControlDirFormat(PyObject); impl BareLocalGitControlDirFormat { pub fn new() -> Self { Python::with_gil(|py| { let m = py .import_bound("breezy.git") .expect("Failed to import breezy.git"); let format = m .getattr("BareLocalGitControlDirFormat") .expect("Failed to get BareLocalGitControlDirFormat"); Self( format .call0() .expect("Failed to create BareLocalGitControlDirFormat") .to_object(py), ) }) } } impl ToPyObject for BareLocalGitControlDirFormat { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl crate::controldir::AsFormat for BareLocalGitControlDirFormat { fn as_format(&self) -> Option { Some(Python::with_gil(|py| { crate::controldir::ControlDirFormat::from(self.0.clone_ref(py)) })) } } breezyshim-0.1.227/src/github.rs000064400000000000000000000012601046102023000145740ustar 00000000000000//! Basic support for interacting with GitHub. use pyo3::prelude::*; pub fn retrieve_github_token() -> String { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.github.forge").unwrap(); let token = m.call_method0("retrieve_github_token").unwrap(); token.extract().unwrap() }) } pub fn login() -> PyResult<()> { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.github.cmds").unwrap(); let cmd = m.getattr("cmd_github_login").unwrap(); let cmd_gl = cmd.call0().unwrap(); cmd_gl.call_method0("_setup_outf").unwrap(); cmd_gl.call_method0("run").unwrap(); Ok(()) }) } breezyshim-0.1.227/src/gitlab.rs000064400000000000000000000007131046102023000145560ustar 00000000000000//! Basic support for interacting with GitLab use pyo3::prelude::*; pub fn login(url: &url::Url) -> PyResult<()> { Python::with_gil(|py| { let m = py.import_bound("breezy.plugins.gitlab.cmds").unwrap(); let cmd = m.getattr("cmd_gitlab_login").unwrap(); let cmd_gl = cmd.call0().unwrap(); cmd_gl.call_method0("_setup_outf").unwrap(); cmd_gl.call_method1("run", (url.as_str(),)).unwrap(); Ok(()) }) } breezyshim-0.1.227/src/gpg.rs000064400000000000000000000125031046102023000140710ustar 00000000000000//! GPG related functions and types. use crate::repository::Repository; use crate::RevisionId; use pyo3::import_exception; use pyo3::prelude::*; #[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 GPGStrategy { pub fn new(branch_config: &crate::config::BranchConfig) -> Self { Python::with_gil(|py| { let gpg = PyModule::import_bound(py, "breezy.gpg").unwrap(); let gpg_strategy = gpg.getattr("GPGStrategy").unwrap(); let branch_config = branch_config.to_object(py); let strategy = gpg_strategy.call1((branch_config,)).unwrap(); GPGStrategy(strategy.to_object(py)) }) } pub fn set_acceptable_keys(&self, keys: &[String]) { Python::with_gil(|py| { self.0 .call_method1(py, "set_acceptable_keys", (keys.join(","),)) .unwrap(); }) } } impl ToPyObject for GPGStrategy { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl FromPyObject<'_> for GPGStrategy { fn extract_bound(ob: &Bound) -> PyResult { Ok(GPGStrategy(ob.to_object(ob.py()))) } } #[derive(Debug)] pub enum VerificationResult { Valid(String), KeyMissing(String), NotValid(String), NotSigned, Expired(String), } impl VerificationResult { pub fn key(&self) -> Option<&str> { match self { VerificationResult::Valid(key) => Some(key), VerificationResult::KeyMissing(key) => Some(key), VerificationResult::NotValid(key) => Some(key), VerificationResult::Expired(key) => Some(key), _ => None, } } pub fn is_valid(&self) -> bool { matches!(self, VerificationResult::Valid(_)) } pub fn is_key_missing(&self) -> bool { matches!(self, VerificationResult::KeyMissing(_)) } pub fn is_not_valid(&self) -> bool { matches!(self, VerificationResult::NotValid(_)) } pub fn is_not_signed(&self) -> bool { matches!(self, VerificationResult::NotSigned) } pub fn is_expired(&self) -> bool { matches!(self, VerificationResult::Expired(_)) } } pub fn bulk_verify_signatures( repository: &Repository, revids: &[&RevisionId], strategy: &GPGStrategy, ) -> Result, Error> { Python::with_gil(|py| { let gpg = PyModule::import_bound(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() }) .unwrap(); let (_count, result, _all_verifiable) = r .extract::<(PyObject, Vec<(RevisionId, isize, String)>, bool)>() .unwrap(); let result: Vec<(RevisionId, VerificationResult)> = result .into_iter() .map(|(revid, status, key)| { let status = match status { 0 => VerificationResult::Valid(key), 1 => VerificationResult::KeyMissing(key), 2 => VerificationResult::NotValid(key), 3 => VerificationResult::NotSigned, 4 => VerificationResult::Expired(key), _ => panic!("unexpected status: {}", status), }; (revid, status) }) .collect::>(); Ok(result) }) } pub struct GPGContext(PyObject); pub struct GPGKey { pub fpr: String, } impl FromPyObject<'_> for GPGKey { fn extract_bound(ob: &Bound) -> PyResult { Ok(GPGKey { fpr: ob.getattr("fpr").unwrap().extract().unwrap(), }) } } impl GPGContext { pub fn new() -> Self { Python::with_gil(|py| { let gpg = PyModule::import_bound(py, "gpg").unwrap(); let gpg_context = gpg.getattr("Context").unwrap(); let context = gpg_context.call0().unwrap(); GPGContext(context.to_object(py)) }) } pub fn keylist(&self, secret: bool) -> Vec { Python::with_gil(|py| { self.0 .call_method1(py, "keylist", (secret,)) .unwrap() .extract::>(py) .unwrap() }) } pub fn key_export_minimal(&self, key: &str) -> Vec { Python::with_gil(|py| { self.0 .call_method1(py, "key_export_minimal", (key,)) .unwrap() .extract::>(py) .unwrap() }) } } breezyshim-0.1.227/src/graph.rs000064400000000000000000000047451046102023000144260ustar 00000000000000//! Graph traversal operations on revision graphs. use 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_bound(ob: &Bound) -> 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.into_value(py) .getattr(py, "revision_id") .unwrap() .extract::>(py) .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.227/src/hooks.rs000064400000000000000000000024621046102023000144420ustar 00000000000000//! Hooks use 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_bound(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) -> Result<(), crate::error::Error> { Python::with_gil(|py| { let entrypoint = self.0.bind(py).get_item(name)?; entrypoint.call_method0("clear")?; Ok(()) }) } pub fn add(&self, name: &str, func: Hook) -> Result<(), crate::error::Error> { Python::with_gil(|py| { let entrypoint = self.0.bind(py).get_item(name)?; entrypoint.call_method1("add", (func.0,))?; Ok(()) }) } pub fn get(&self, name: &str) -> Result, crate::error::Error> { Python::with_gil(|py| { let entrypoint = self.0.bind(py).get_item(name)?; Ok(entrypoint .extract::>()? .into_iter() .map(Hook) .collect()) }) } } breezyshim-0.1.227/src/interrepository.rs000064400000000000000000000067771046102023000166150ustar 00000000000000//! Operations between repositories. use crate::error::Error; use crate::repository::Repository; use crate::RevisionId; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyDict}; use std::collections::HashMap; pub struct PyInterRepository(PyObject); impl ToPyObject for PyInterRepository { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl InterRepository for PyInterRepository {} pub fn get(source: &Repository, target: &Repository) -> Result, Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.repository")?; let interrepo = m.getattr("InterRepository")?; let inter_repository = interrepo.call_method1("get", (source.to_object(py), target.to_object(py)))?; Ok(Box::new(PyInterRepository(inter_repository.to_object(py))) as Box) }) } pub trait InterRepository: ToPyObject { fn get_source(&self) -> Repository { Python::with_gil(|py| -> PyResult { let source = self.to_object(py).getattr(py, "source")?; Ok(Repository::new(source.to_object(py))) }) .unwrap() } fn get_target(&self) -> Repository { Python::with_gil(|py| -> PyResult { let target = self.to_object(py).getattr(py, "target")?; Ok(Repository::new(target.to_object(py))) }) .unwrap() } // TODO: This should really be on InterGitRepository fn fetch_refs( &self, get_changed_refs: std::sync::Mutex< Box< dyn FnMut( &HashMap, (Vec, Option)>, ) -> HashMap, (Vec, Option)> + Send, >, >, lossy: bool, overwrite: bool, ) -> Result<(), Error> { Python::with_gil(|py| { let get_changed_refs = pyo3::types::PyCFunction::new_closure_bound( py, None, None, move |args, _kwargs| { let refs = args .extract::<(HashMap, (Vec, Option)>,)>() .unwrap() .0; // Call get_changed_refs let result = if let Ok(mut get_changed_refs) = get_changed_refs.lock() { get_changed_refs(&refs) } else { refs }; Python::with_gil(|py| -> PyResult { let ret = PyDict::new_bound(py); for (k, (v, r)) in result { ret.set_item( PyBytes::new_bound(py, k.as_slice()), ( PyBytes::new_bound(py, v.as_slice()), r.map(|r| r.into_py(py)), ), )?; } // We need to change the return type since pyo3::Python can't be sent between // threads Ok(ret.into_py(py)) }) }, ) .unwrap(); self.to_object(py).call_method1( py, "fetch_refs", (get_changed_refs, lossy, overwrite), )?; Ok(()) }) } } breezyshim-0.1.227/src/intertree.rs000064400000000000000000000016111046102023000153130ustar 00000000000000//! Operations between two trees. use 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_bound("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.227/src/launchpad.rs000064400000000000000000000032461046102023000152570ustar 00000000000000//! Launchpad login and related functions use pyo3::prelude::*; pub fn login(url: &url::Url) { Python::with_gil(|py| -> PyResult<()> { let m = py.import_bound("breezy.plugins.launchpad.cmds")?; let cmd = m.getattr("cmd_launchpad_login")?; let cmd_lp = cmd.call0()?; cmd_lp.call_method0("_setup_outf")?; cmd_lp.call_method1("run", (url.as_str(),))?; let lp_api = py.import_bound("breezy.plugins.launchpad.lp_api")?; let lp_uris = uris()?; let lp_service_root = lp_uris .iter() .find(|(_key, root)| { url.host_str() == Some(root) || url.host_str() == Some(root.trim_end_matches('/')) }) .unwrap() .1; let kwargs = pyo3::types::PyDict::new_bound(py); kwargs.set_item("version", "devel")?; lp_api.call_method("connect_launchpad", (lp_service_root,), Some(&kwargs))?; Ok(()) }) .unwrap() } pub fn uris() -> PyResult> { Python::with_gil(|py| { let m = py.import_bound("launchpadlib")?; match m.getattr("uris") { Ok(lp_uris) => lp_uris .getattr("web_roots") .unwrap() .extract::>(), Err(e) if e.is_instance_of::(py) => { log::warn!("launchpadlib is not installed, unable to log in to launchpad"); Ok(std::collections::HashMap::new()) } Err(e) => { panic!("Failed to import launchpadlib: {}", e); } } }) } breezyshim-0.1.227/src/lib.rs000064400000000000000000000105111046102023000140570ustar 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(&"https://code.launchpad.net/brz".parse().unwrap()).unwrap(); //! println!("Last revision: {:?}", b.last_revision()); //! ``` pub mod bazaar; pub mod branch; pub mod clean_tree; pub mod commit; pub mod config; pub mod controldir; pub mod cvs; pub mod darcs; pub mod delta; pub mod diff; #[cfg(feature = "dirty-tracker")] pub mod dirty_tracker; pub mod error; pub mod export; pub mod foreign; pub mod forge; pub mod fossil; pub mod git; pub mod github; pub mod gitlab; pub mod gpg; pub mod graph; pub mod hooks; pub mod interrepository; pub mod intertree; pub mod launchpad; pub mod location; pub mod lock; pub mod mercurial; pub mod merge; pub mod osutils; pub mod patches; pub mod plugin; pub mod rename_map; pub mod repository; pub mod revisionid; pub mod status; pub mod subversion; pub mod tags; pub mod testing; pub mod transform; pub mod transport; pub mod tree; pub mod ui; pub mod urlutils; pub mod version; pub mod workingtree; pub mod workspace; #[cfg(feature = "debian")] pub mod debian; pub use branch::Branch; pub use controldir::{ControlDir, Prober}; pub use forge::{get_forge, Forge, MergeProposal, MergeProposalStatus}; pub use lock::Lock; use pyo3::exceptions::PyImportError; use pyo3::prelude::*; 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_bound("breezy.git").unwrap(); }) } pub fn init_bzr() { pyo3::Python::with_gil(|py| { py.import_bound("breezy.bzr").unwrap(); }) } #[cfg(feature = "auto-initialize")] #[ctor::ctor] fn ensure_initialized() { init(); } const MINIMUM_VERSION: (usize, usize, usize) = (3, 3, 6); static INIT_BREEZY: Once = Once::new(); pub fn init() { INIT_BREEZY.call_once(|| { pyo3::prepare_freethreaded_python(); let (major, minor, micro) = pyo3::Python::with_gil(|py| match py.import_bound("breezy") { Ok(breezy) => { let (major, minor, micro, _releaselevel, _serial): ( usize, usize, usize, String, usize, ) = breezy.getattr("version_info").unwrap().extract().unwrap(); (major, minor, micro) } Err(e) => { if e.is_instance_of::(py) { panic!("Breezy is not installed. Please install Breezy first."); } else { Err::<(), pyo3::PyErr>(e).unwrap(); unreachable!() } } }); if (major, minor, micro) < MINIMUM_VERSION { panic!( "Breezy version {} is too old, please upgrade to at least {}.", format!("{}.{}.{}", major, minor, micro), format!( "{}.{}.{}", MINIMUM_VERSION.0, MINIMUM_VERSION.1, MINIMUM_VERSION.2 ) ); } if major >= 4 { log::warn!("Support for Breezy 4.0 is experimental and incomplete."); } init_git(); init_bzr(); // Work around a breezy bug pyo3::Python::with_gil(|py| { let m = py.import_bound("breezy.controldir").unwrap(); let f = m.getattr("ControlDirFormat").unwrap(); f.call_method0("known_formats").unwrap(); }); // Prevent race conditions pyo3::Python::with_gil(|py| { let m = py.import_bound("breezy.config").unwrap(); m.call_method0("GlobalStack").unwrap(); m.call_method1("LocationStack", ("file:///",)).unwrap(); }); }); } pub type Result = std::result::Result; breezyshim-0.1.227/src/location.rs000064400000000000000000000053751046102023000151350ustar 00000000000000//! UI-layer location handling use pyo3::prelude::*; use url::Url; pub fn cvs_to_url(cvsroot: &str) -> Url { Python::with_gil(|py| { let breezy_location = py.import_bound("breezy.location").unwrap(); breezy_location .call_method1("cvs_to_url", (cvsroot,)) .unwrap() .extract::() .unwrap() .parse() .unwrap() }) } #[test] fn test_cvs_to_url() { assert_eq!( cvs_to_url(":pserver:anonymous@localhost:/var/lib/cvs"), Url::parse("cvs+pserver://anonymous@localhost/var/lib/cvs").unwrap() ); } pub fn rcp_location_to_url(rcp_location: &str) -> Result { Python::with_gil(|py| { let breezy_location = py.import_bound("breezy.location").unwrap(); Ok(breezy_location .call_method1("rcp_location_to_url", (rcp_location,)) .map_err(|e| e.to_string())? .extract::() .unwrap() .parse() .unwrap()) }) } #[test] fn test_rcp_location_to_url() { assert_eq!( rcp_location_to_url("user@host:/path/to/repo").unwrap(), Url::parse("ssh://user@host/path/to/repo").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_bound(py, self.to_string().as_str()).to_object(py) }) } } #[test] fn test_as_location_url() { Python::with_gil(|py| { assert_eq!( Url::parse("ssh://user@host/path/to/repo") .unwrap() .as_ref() .as_location() .extract::(py) .unwrap(), "ssh://user@host/path/to/repo" ); }); } impl AsLocation for &str { fn as_location(&self) -> PyObject { Python::with_gil(|py| pyo3::types::PyString::new_bound(py, self).to_object(py)) } } #[test] fn test_as_location_str() { Python::with_gil(|py| { assert_eq!( "ssh://user@host/path/to/repo" .as_location() .extract::(py) .unwrap(), "ssh://user@host/path/to/repo" ); }); } impl AsLocation for &std::path::Path { fn as_location(&self) -> PyObject { Python::with_gil(|py| { pyo3::types::PyString::new_bound(py, self.to_str().unwrap()).to_object(py) }) } } #[test] fn test_as_location_path() { Python::with_gil(|py| { assert_eq!( std::path::Path::new("/path/to/repo") .as_location() .extract::(py) .unwrap(), "/path/to/repo" ); }); } breezyshim-0.1.227/src/lock.rs000064400000000000000000000006761046102023000142540ustar 00000000000000//! Locking of Breezy objects. use 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.227/src/mercurial.rs000064400000000000000000000026441046102023000153040ustar 00000000000000//! Mercurial prober. //! //! This allows detecting Mercurial repositories, but does not provide any //! functionality to interact with them. use crate::controldir::Prober; use pyo3::exceptions::PyModuleNotFoundError; use pyo3::prelude::*; pub struct SmartHgProber(PyObject); impl SmartHgProber { pub fn new() -> Option { Python::with_gil(|py| { let m = match py.import_bound("breezy.plugins.hg") { Ok(m) => m, Err(e) => { if e.is_instance_of::(py) { return None; } else { e.print_and_set_sys_last_vars(py); panic!("Failed to import breezy.plugins.hg"); } } }; let prober = m .getattr("SmartHgProber") .expect("Failed to get SmartHgProber"); Some(Self(prober.to_object(py))) }) } } impl FromPyObject<'_> for SmartHgProber { fn extract_bound(obj: &Bound) -> PyResult { Ok(Self(obj.to_object(obj.py()))) } } impl ToPyObject for SmartHgProber { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Prober for SmartHgProber {} #[cfg(test)] mod tests { use super::*; #[test] fn test_smart_hg_prober() { let _ = SmartHgProber::new(); } } breezyshim-0.1.227/src/merge.rs000064400000000000000000000114541046102023000144170ustar 00000000000000//! Tree merging. use 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_bound("breezy.merge").unwrap(); let cls = m.getattr("Merger").unwrap(); let kwargs = PyDict::new_bound(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) -> Result, crate::error::Error> { 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) } } }) .map_err(Into::into) } pub fn set_other_revision( &mut self, other_revision: &RevisionId, other_branch: &dyn Branch, ) -> Result<(), crate::error::Error> { 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, ) -> Result<(), crate::error::Error> { 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_bound("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) -> Result { 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_bound("breezy.merge").unwrap(); let cls = m.getattr("Merger").unwrap(); let kwargs = PyDict::new_bound(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) -> Result { 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.227/src/osutils.rs000064400000000000000000000004771046102023000150250ustar 00000000000000//! OS-specific utilities. use std::path::Path; pub fn is_inside(dir: &Path, fname: &Path) -> bool { fname.starts_with(dir) } pub fn is_inside_any(dir_list: &[&Path], fname: &Path) -> bool { for dirname in dir_list { if is_inside(dirname, fname) { return true; } } false } breezyshim-0.1.227/src/patches.rs000064400000000000000000000157531046102023000147550ustar 00000000000000//! Patching support for Breezy. use crate::transform::TreeTransform; use crate::tree::Tree; use patchkit::unified::{HunkLine, UnifiedPatch}; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyList}; fn py_patches(iter_patches: impl Iterator) -> PyResult { Python::with_gil(|py| { let m = py.import_bound("breezy.patches")?; let patchc = m.getattr("Patch")?; let hunkc = m.getattr("Hunk")?; let insertlinec = m.getattr("InsertLine")?; let removelinec = m.getattr("RemoveLine")?; let contextlinec = m.getattr("ContextLine")?; let mut ret = vec![]; for patch in iter_patches { let pypatch = patchc.call1(( PyBytes::new_bound(py, &patch.orig_name), PyBytes::new_bound(py, &patch.mod_name), patch.orig_ts, patch.mod_ts, ))?; let pyhunks = pypatch.getattr("hunks")?; for hunk in patch.hunks { let pyhunk = hunkc.call1(( hunk.orig_pos, hunk.orig_range, hunk.mod_pos, hunk.mod_range, hunk.tail, ))?; pyhunks.call_method1("append", (&pyhunk,))?; let pylines = pyhunk.getattr("lines")?; for line in hunk.lines { pylines.call_method1( "append", (match line { HunkLine::ContextLine(l) => { contextlinec.call1((PyBytes::new_bound(py, l.as_slice()),))? } HunkLine::InsertLine(l) => { insertlinec.call1((PyBytes::new_bound(py, l.as_slice()),))? } HunkLine::RemoveLine(l) => { removelinec.call1((PyBytes::new_bound(py, l.as_slice()),))? } },), )?; } } ret.push(pypatch); } Ok(PyList::new_bound(py, ret.iter()).into_py(py)) }) } /// Apply patches to a TreeTransform. /// /// # Arguments /// * `tt`: TreeTransform instance /// * `patches`: List of patches /// * `prefix`: Number leading path segments to strip pub fn apply_patches( tt: &TreeTransform, patches: impl Iterator, prefix: Option, ) -> crate::Result<()> { Python::with_gil(|py| { let patches = py_patches(patches)?; let m = py.import_bound("breezy.tree")?; let apply_patches = m.getattr("apply_patches")?; apply_patches.call1((tt.to_object(py), patches, prefix))?; Ok(()) }) } pub struct AppliedPatches(PyObject, PyObject); impl AppliedPatches { pub fn new( tree: &dyn Tree, patches: Vec, prefix: Option, ) -> crate::Result { let (ap, tree) = Python::with_gil(|py| -> Result<_, PyErr> { let patches = py_patches(patches.into_iter())?; let m = py.import_bound("breezy.patches")?; let c = m.getattr("AppliedPatches")?; let ap = c.call1((tree.to_object(py), patches, prefix))?; let tree = ap.call_method0("__enter__")?; Ok((ap.to_object(py), tree.to_object(py))) })?; Ok(Self(tree, ap)) } } impl Drop for AppliedPatches { fn drop(&mut self) { Python::with_gil(|py| -> Result<(), PyErr> { self.1 .call_method1(py, "__exit__", (py.None(), py.None(), py.None()))?; Ok(()) }) .unwrap(); } } impl ToPyObject for AppliedPatches { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Tree for AppliedPatches {} #[cfg(test)] mod applied_patches_tests { use super::*; use crate::controldir::ControlDirFormat; use crate::tree::Tree; use serial_test::serial; #[test] #[serial] fn test_apply_simple() { let env = crate::testing::TestEnv::new(); let td = tempfile::tempdir().unwrap(); let tree = crate::controldir::create_standalone_workingtree( td.path(), &ControlDirFormat::default(), ) .unwrap(); std::fs::write(td.path().join("a"), "a\n").unwrap(); tree.add(&[std::path::Path::new("a")]).unwrap(); tree.build_commit() .message("Add a") .reporter(&crate::commit::NullCommitReporter::new()) .commit() .unwrap(); let patch = UnifiedPatch::parse_patch(patchkit::unified::splitlines( br#"--- a/a +++ b/a @@ -1 +1 @@ -a +b "#, )) .unwrap(); let newtree = crate::patches::AppliedPatches::new(&tree, vec![patch], None).unwrap(); assert_eq!( b"b\n".to_vec(), newtree.get_file_text(std::path::Path::new("a")).unwrap() ); std::mem::drop(newtree); std::mem::drop(env); } #[test] #[serial] fn test_apply_delete() { let env = crate::testing::TestEnv::new(); let td = tempfile::tempdir().unwrap(); let tree = crate::controldir::create_standalone_workingtree( td.path(), &ControlDirFormat::default(), ) .unwrap(); std::fs::write(td.path().join("a"), "a\n").unwrap(); tree.add(&[std::path::Path::new("a")]).unwrap(); tree.build_commit() .reporter(&crate::commit::NullCommitReporter::new()) .message("Add a") .commit() .unwrap(); let patch = UnifiedPatch::parse_patch(patchkit::unified::splitlines( br#"--- a/a +++ /dev/null @@ -1 +0,0 @@ -a "#, )) .unwrap(); let newtree = crate::patches::AppliedPatches::new(&tree, vec![patch], None).unwrap(); assert!(!newtree.has_filename(std::path::Path::new("a"))); std::mem::drop(env); } #[test] #[serial] fn test_apply_add() { let env = crate::testing::TestEnv::new(); let td = tempfile::tempdir().unwrap(); let tree = crate::controldir::create_standalone_workingtree( td.path(), &ControlDirFormat::default(), ) .unwrap(); std::fs::write(td.path().join("a"), "a\n").unwrap(); tree.add(&[std::path::Path::new("a")]).unwrap(); tree.build_commit() .reporter(&crate::commit::NullCommitReporter::new()) .message("Add a") .commit() .unwrap(); let patch = UnifiedPatch::parse_patch(patchkit::unified::splitlines( br#"--- /dev/null +++ b/b @@ -0,0 +1 @@ +b "#, )) .unwrap(); let newtree = crate::patches::AppliedPatches::new(&tree, vec![patch], None).unwrap(); assert_eq!( b"b\n".to_vec(), newtree.get_file_text(std::path::Path::new("b")).unwrap() ); std::mem::drop(env); } } breezyshim-0.1.227/src/plugin.rs000064400000000000000000000012661046102023000146160ustar 00000000000000//! Plugin loading and management. use pyo3::exceptions::PyRuntimeError; use pyo3::prelude::*; pub fn load_plugins() -> bool { Python::with_gil(|py| { let m = py.import_bound("breezy.plugin").unwrap(); match m.call_method0("load_plugins") { Ok(_) => true, Err(e) if e.is_instance_of::(py) && e.to_string().contains("Breezy already initialized") => { false } Err(e) => panic!("Error loading plugins: {}", e), } }) } #[cfg(test)] mod tests { use super::*; #[test] fn test_load_plugins() { load_plugins(); } } breezyshim-0.1.227/src/rename_map.rs000064400000000000000000000011311046102023000154130ustar 00000000000000//! Detect renames between two trees based on file contents. use crate::tree::{MutableTree, Tree}; use pyo3::prelude::*; pub fn guess_renames( from_tree: &dyn Tree, mutable_tree: &dyn MutableTree, ) -> Result<(), crate::error::Error> { pyo3::Python::with_gil(|py| -> Result<(), pyo3::PyErr> { let m = py.import_bound("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(()) }) .map_err(Into::into) } breezyshim-0.1.227/src/repository.rs000064400000000000000000000226721046102023000155430ustar 00000000000000//! Repository handling //! //! A repository is a collection of revisions and their associated data. use crate::controldir::ControlDir; use crate::delta::TreeDelta; use crate::foreign::VcsType; use crate::graph::Graph; use crate::location::AsLocation; use crate::lock::Lock; use crate::revisionid::RevisionId; use crate::tree::RevisionTree; use chrono::DateTime; use chrono::TimeZone; use pyo3::exceptions::PyStopIteration; use pyo3::prelude::*; use pyo3::types::PyDict; pub struct RepositoryFormat(PyObject); impl Clone for RepositoryFormat { fn clone(&self) -> Self { Python::with_gil(|py| RepositoryFormat(self.0.clone_ref(py))) } } impl RepositoryFormat { pub fn supports_chks(&self) -> bool { Python::with_gil(|py| { self.0 .getattr(py, "supports_chks") .unwrap() .extract(py) .unwrap() }) } } pub struct Repository(PyObject); impl Clone for Repository { fn clone(&self) -> Self { Python::with_gil(|py| Repository(self.0.clone_ref(py))) } } #[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_opt(self.timezone).unwrap(); tz.timestamp_opt(self.timestamp as i64, 0).unwrap() } } impl ToPyObject for Revision { fn to_object(&self, py: Python) -> PyObject { let kwargs = PyDict::new_bound(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_bound("breezy.revision") .unwrap() .getattr("Revision") .unwrap() .call((), Some(&kwargs)) .unwrap() .to_object(py) } } impl FromPyObject<'_> for Revision { fn extract_bound(ob: &Bound) -> 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 vcs_type(&self) -> VcsType { Python::with_gil(|py| { if self.to_object(py).getattr(py, "_git").is_ok() { VcsType::Git } else { VcsType::Bazaar } }) } pub fn get_user_url(&self) -> url::Url { Python::with_gil(|py| { self.0 .getattr(py, "user_url") .unwrap() .extract::(py) .unwrap() .parse() .unwrap() }) } pub fn user_transport(&self) -> crate::transport::Transport { Python::with_gil(|py| { crate::transport::Transport::new(self.0.getattr(py, "user_transport").unwrap()) }) } pub fn control_transport(&self) -> crate::transport::Transport { Python::with_gil(|py| { crate::transport::Transport::new(self.0.getattr(py, "control_transport").unwrap()) }) } pub fn fetch( &self, other_repository: &Repository, stop_revision: Option<&RevisionId>, ) -> Result<(), crate::error::Error> { 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) -> Result { 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) -> Result { Python::with_gil(|py| { self.0 .call_method1(py, "get_revision", (revision_id.clone(),))? .extract(py) }) .map_err(|e| e.into()) } // TODO: This should really be on ForeignRepository pub fn lookup_bzr_revision_id( &self, revision_id: &RevisionId, ) -> Result<(Vec,), crate::error::Error> { Python::with_gil(|py| { self.0 .call_method1(py, "lookup_bzr_revision_id", (revision_id.clone(),))? .extract::<(Vec, PyObject)>(py) }) .map_err(|e| e.into()) .map(|(v, _m)| (v,)) } pub fn lookup_foreign_revision_id( &self, foreign_revid: &[u8], ) -> Result { Python::with_gil(|py| { self.0 .call_method1(py, "lookup_foreign_revision_id", (foreign_revid,))? .extract(py) }) .map_err(|e| e.into()) } pub fn lock_read(&self) -> Result { Python::with_gil(|py| { Ok(Lock::from( self.to_object(py).call_method0(py, "lock_read")?, )) }) } pub fn lock_write(&self) -> Result { Python::with_gil(|py| { Ok(Lock::from( self.to_object(py).call_method0(py, "lock_write")?, )) }) } } pub fn open(base: impl AsLocation) -> Result { Python::with_gil(|py| { let o = py .import_bound("breezy.repository")? .getattr("Repository")? .call_method1("open", (base.as_location(),))?; Ok(Repository::new(o.into())) }) } #[cfg(test)] mod repository_tests { use crate::controldir::ControlDirFormat; #[test] fn test_simple() { let td = tempfile::tempdir().unwrap(); let _dir = crate::controldir::create_standalone_workingtree( td.path(), &ControlDirFormat::default(), ) .unwrap(); let _repo = crate::repository::open(td.path()).unwrap(); } #[test] fn test_clone() { let td = tempfile::tempdir().unwrap(); let _dir = crate::controldir::create_standalone_workingtree( td.path(), &ControlDirFormat::default(), ) .unwrap(); let repo = crate::repository::open(td.path()).unwrap(); let _repo2 = repo.clone(); } } breezyshim-0.1.227/src/revisionid.rs000064400000000000000000000074601046102023000154750ustar 00000000000000//! Revision ID type and related functions. use 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()) } pub fn as_str(&self) -> &str { std::str::from_utf8(&self.0).unwrap() } } #[cfg(feature = "sqlx")] use sqlx::{postgres::PgTypeInfo, Postgres}; #[cfg(feature = "sqlx")] impl sqlx::Type for RevisionId { fn type_info() -> PgTypeInfo { >::type_info() } } #[cfg(feature = "sqlx")] impl sqlx::Encode<'_, Postgres> for RevisionId { fn encode_by_ref( &self, buf: &mut sqlx::postgres::PgArgumentBuffer, ) -> Result> { sqlx::Encode::::encode_by_ref(&self.as_str(), buf) } } #[cfg(feature = "sqlx")] impl sqlx::Decode<'_, Postgres> for RevisionId { fn decode( value: sqlx::postgres::PgValueRef<'_>, ) -> Result> { let s: &str = sqlx::Decode::::decode(value)?; Ok(RevisionId::from(s.as_bytes())) } } impl From> for RevisionId { fn from(value: Vec) -> Self { Self(value) } } impl From<&[u8]> for RevisionId { fn from(value: &[u8]) -> Self { Self(value.to_vec()) } } 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_bound(ob: &Bound) -> PyResult { let bytes = ob.extract::>()?; Ok(Self(bytes)) } } impl ToPyObject for RevisionId { fn to_object(&self, py: Python) -> PyObject { pyo3::types::PyBytes::new_bound(py, &self.0).to_object(py) } } impl IntoPy for RevisionId { fn into_py(self, py: Python) -> PyObject { pyo3::types::PyBytes::new_bound(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:"; #[cfg(test)] mod tests { use super::*; #[test] fn test_revision_id() { let id = RevisionId::null(); assert!(id.is_null()); assert!(!id.is_reserved()); } #[test] fn test_revision_id_from_vec() { let id = RevisionId::from(b"test".to_vec()); assert!(!id.is_null()); assert!(!id.is_reserved()); } #[test] fn test_reserved_revision_id() { let id = RevisionId::from(b":test".to_vec()); assert!(!id.is_null()); assert!(id.is_reserved()); } #[test] fn test_as_bytes() { let id = RevisionId::from(b"test".to_vec()); assert_eq!(id.as_bytes(), b"test"); } } breezyshim-0.1.227/src/status.rs000064400000000000000000000005111046102023000146330ustar 00000000000000//! Status reporting functions. use crate::tree::WorkingTree; use pyo3::prelude::*; pub fn show_tree_status(wt: &WorkingTree) -> crate::Result<()> { Python::with_gil(|py| { let m = py.import_bound("breezy.status")?; let f = m.getattr("show_tree_status")?; f.call1((&wt.0,))?; Ok(()) }) } breezyshim-0.1.227/src/subversion.rs000064400000000000000000000027171046102023000155210ustar 00000000000000//! Subversion repository prober. //! //! This module provides a prober for Subversion repositories, but no actual //! implementation is provided. use crate::controldir::Prober; use pyo3::exceptions::PyModuleNotFoundError; use pyo3::prelude::*; pub struct SvnRepositoryProber(PyObject); impl SvnRepositoryProber { pub fn new() -> Option { Python::with_gil(|py| { let m = match py.import_bound("breezy.plugins.svn") { Ok(m) => m, Err(e) => { if e.is_instance_of::(py) { return None; } else { e.print_and_set_sys_last_vars(py); panic!("Failed to import breezy.plugins.svn"); } } }; let prober = m .getattr("SvnRepositoryProber") .expect("Failed to get SvnRepositoryProber"); Some(Self(prober.to_object(py))) }) } } impl FromPyObject<'_> for SvnRepositoryProber { fn extract_bound(obj: &Bound) -> PyResult { Ok(Self(obj.to_object(obj.py()))) } } impl ToPyObject for SvnRepositoryProber { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } impl Prober for SvnRepositoryProber {} #[cfg(test)] mod tests { use super::*; #[test] fn test_new() { let _ = SvnRepositoryProber::new(); } } breezyshim-0.1.227/src/tags.rs000064400000000000000000000031171046102023000142530ustar 00000000000000//! Revision tags use crate::error::Error; use 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) } } impl Tags { pub fn get_reverse_tag_dict( &self, ) -> Result>, crate::error::Error> { Python::with_gil(|py| self.0.call_method0(py, "get_reverse_tag_dict")?.extract(py)) .map_err(Into::into) } pub fn get_tag_dict(&self) -> Result, crate::error::Error> { Python::with_gil(|py| self.0.call_method0(py, "get_tag_dict")?.extract(py)) .map_err(Into::into) } 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.227/src/testing.rs000064400000000000000000000106261046102023000147750ustar 00000000000000//! Test utilities for the Breezy Rust bindings. use pyo3::prelude::*; use std::collections::HashMap; use std::fs; use std::path::PathBuf; use tempfile::TempDir; pub struct TestEnv { pub temp_dir: TempDir, pub working_dir: PathBuf, pub home_dir: PathBuf, pub old_cwd: PathBuf, pub old_env: HashMap>, } impl TestEnv { pub fn new() -> Self { let temp_dir = TempDir::new().unwrap(); let working_dir = temp_dir.path().join("test"); fs::create_dir(&working_dir).unwrap(); let home_dir = temp_dir.path().join("home"); fs::create_dir(&home_dir).unwrap(); let mut old_env = HashMap::new(); let old_cwd = std::env::current_dir().unwrap(); old_env.insert("HOME".to_string(), std::env::var("HOME").ok()); old_env.insert("BRZ_EMAIL".to_string(), std::env::var("BRZ_EMAIL").ok()); old_env.insert("BRZ_HOME".to_string(), std::env::var("BRZ_HOME").ok()); let brz_email = "Joe Tester "; let breezy_home = home_dir.join(".config/breezy"); std::env::set_current_dir(&working_dir).unwrap(); std::env::set_var("HOME", &home_dir); std::env::set_var("BRZ_EMAIL", brz_email); std::env::set_var("BRZ_HOME", &breezy_home); pyo3::Python::with_gil(|py| { let os = py.import_bound("os").unwrap(); os.call_method1("chdir", (working_dir.to_str().unwrap(),)) .unwrap(); let environ = os.getattr("environ").unwrap(); environ .set_item("HOME", home_dir.to_str().unwrap()) .unwrap(); environ.set_item("BRZ_EMAIL", brz_email).unwrap(); environ .set_item("BRZ_HOME", breezy_home.to_str().unwrap()) .unwrap(); }); fs::create_dir_all(&breezy_home).unwrap(); fs::write( breezy_home.join("breezy.conf"), r#" [DEFAULT] email = Joe Tester "#, ) .unwrap(); Self { temp_dir, home_dir, working_dir, old_cwd, old_env, } } } impl Drop for TestEnv { fn drop(&mut self) { for (key, value) in self.old_env.drain() { if let Some(value) = value.as_ref() { std::env::set_var(&key, value); } else { std::env::remove_var(&key); } Python::with_gil(|py| { let os = py.import_bound("os").unwrap(); let environ = os.getattr("environ").unwrap(); if let Some(value) = value { environ.set_item(key, value).unwrap(); } else { environ.del_item(key).unwrap(); } }); } let _ = std::env::set_current_dir(&self.old_cwd); } } impl Default for TestEnv { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use super::*; use serial_test::serial; #[test] #[serial] fn test_testenv() { let env = TestEnv::new(); assert_eq!(env.home_dir, env.temp_dir.path().join("home")); assert_eq!(env.working_dir, env.temp_dir.path().join("test")); assert_eq!( std::env::current_dir().unwrap(), env.working_dir.canonicalize().unwrap() ); assert_eq!( std::env::var("HOME").unwrap(), env.home_dir.to_str().unwrap() ); assert_eq!( std::env::var("BRZ_EMAIL").unwrap(), "Joe Tester " ); Python::with_gil(|py| { let os = py.import_bound("os").unwrap(); assert_eq!( os.call_method0("getcwd") .unwrap() .extract::() .unwrap(), env.working_dir.canonicalize().unwrap(), ); assert_eq!( os.call_method1("getenv", ("HOME",)) .unwrap() .extract::() .unwrap(), env.home_dir.to_str().unwrap() ); assert_eq!( os.call_method1("getenv", ("BRZ_EMAIL",)) .unwrap() .extract::() .unwrap(), "Joe Tester " ); }); } } breezyshim-0.1.227/src/transform.rs000064400000000000000000000201301046102023000153220ustar 00000000000000//! Tree transformation API. use crate::tree::{PathBuf, Tree}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyTuple; use pyo3::types::PyTupleMethods; 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_bound(_ob: &Bound) -> PyResult { Ok(TreeChange {}) } } pub struct Conflict(PyObject); impl Clone for Conflict { fn clone(&self) -> Self { Python::with_gil(|py| Conflict(self.0.clone_ref(py))) } } impl Conflict { pub fn associated_filenames(&self) -> Result, crate::error::Error> { let mut v: Vec = vec![]; Python::with_gil(|py| { let ret = self.0.getattr(py, "associated_filenames")?; for item in ret.bind(py).iter()? { v.push(item?.extract()?); } Ok(v) }) } pub fn describe(&self) -> Result { Python::with_gil(|py| { let ret = self.0.call_method0(py, "describe")?; Ok(ret.extract(py)?) }) } pub fn cleanup(&self, tree: &dyn Tree) -> Result<(), crate::error::Error> { Python::with_gil(|py| { self.0.call_method1(py, "cleanup", (tree.to_object(py),))?; Ok(()) }) } } 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 finalize(&self) -> Result<(), crate::error::Error> { Python::with_gil(|py| { self.to_object(py).call_method0(py, "finalize")?; Ok(()) }) } pub fn iter_changes( &self, ) -> Result>, crate::error::Error> { let mut v: Vec = vec![]; Python::with_gil(|py| { let ret = self.to_object(py).call_method0(py, "iter_changes")?; for item in ret.bind(py).iter()? { v.push(item?.extract()?); } Ok(Box::new(v.into_iter()) as Box>) }) } pub fn cooked_conflicts(&self) -> Result, crate::error::Error> { let mut v: Vec = vec![]; Python::with_gil(|py| { let ret = self.to_object(py).getattr(py, "cooked_conflicts")?; for item in ret.bind(py).iter()? { v.push(Conflict(item?.into())); } Ok(v) }) } pub fn get_preview_tree(&self) -> Result { 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_bound(ob: &Bound) -> PyResult { Ok(TreeTransform(ob.clone().unbind())) } } #[derive(PartialEq, Eq, Hash, Clone, Debug)] pub struct TransId(String); impl FromPyObject<'_> for TransId { fn extract_bound(ob: &Bound) -> PyResult { Ok(TransId(ob.extract::()?)) } } impl ToPyObject for TransId { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } #[derive(PartialEq, Eq, Hash, Clone, Debug)] pub enum RawConflict { UnversionedExecutability(TransId), NonFileExecutability(TransId), Overwrite(TransId, String), ParentLoop(TransId), UnversionedParent(TransId), VersioningNoContents(TransId), VersioningBadKind(TransId), Duplicate(TransId, TransId, String), MissingParent(TransId), NonDirectoryParent(TransId), } impl ToPyObject for RawConflict { fn to_object(&self, py: Python) -> PyObject { match self { RawConflict::UnversionedExecutability(id) => { PyTuple::new_bound(py, &[("unversioned executability", id.to_object(py))]) .to_object(py) } RawConflict::NonFileExecutability(id) => { PyTuple::new_bound(py, &[("non-file executability", id.to_object(py))]) .to_object(py) } RawConflict::Overwrite(id, path) => { PyTuple::new_bound(py, &[("overwrite", id.to_object(py), path.to_object(py))]) .to_object(py) } RawConflict::ParentLoop(id) => { PyTuple::new_bound(py, &[("parent loop", id.to_object(py))]).to_object(py) } RawConflict::UnversionedParent(id) => { PyTuple::new_bound(py, &[("unversioned parent", id.to_object(py))]).to_object(py) } RawConflict::VersioningNoContents(id) => { PyTuple::new_bound(py, &[("versioning no contents", id.to_object(py))]) .to_object(py) } RawConflict::VersioningBadKind(id) => { PyTuple::new_bound(py, &[("versioning bad kind", id.to_object(py))]).to_object(py) } RawConflict::Duplicate(id1, id2, path) => PyTuple::new_bound( py, &[( "duplicate", id1.to_object(py), id2.to_object(py), path.to_object(py), )], ) .to_object(py), RawConflict::MissingParent(id) => { PyTuple::new_bound(py, &[("missing parent", id.to_object(py))]).to_object(py) } RawConflict::NonDirectoryParent(id) => { PyTuple::new_bound(py, &[("non-directory parent", id.to_object(py))]).to_object(py) } } } } impl FromPyObject<'_> for RawConflict { fn extract_bound(ob: &Bound) -> PyResult { let tuple = ob.extract::>()?; match tuple.get_item(0)?.extract::()?.as_str() { "unversioned executability" => Ok(Self::UnversionedExecutability(TransId( tuple.get_item(1)?.extract::()?, ))), "non-file executability" => Ok(Self::NonFileExecutability(TransId( tuple.get_item(1)?.extract::()?, ))), "overwrite" => Ok(Self::Overwrite( TransId(tuple.get_item(1)?.extract::()?), tuple.get_item(2)?.extract::()?, )), "parent loop" => Ok(Self::ParentLoop(TransId( tuple.get_item(1)?.extract::()?, ))), "unversioned parent" => Ok(Self::UnversionedParent(TransId( tuple.get_item(1)?.extract::()?, ))), "versioning no contents" => Ok(Self::VersioningNoContents(TransId( tuple.get_item(1)?.extract::()?, ))), "versioning bad kind" => Ok(Self::VersioningBadKind(TransId( tuple.get_item(1)?.extract::()?, ))), "duplicate" => Ok(Self::Duplicate( TransId(tuple.get_item(1)?.extract::()?), TransId(tuple.get_item(2)?.extract::()?), tuple.get_item(3)?.extract::()?, )), "missing parent" => Ok(Self::MissingParent(TransId( tuple.get_item(1)?.extract::()?, ))), "non-directory parent" => Ok(Self::NonDirectoryParent(TransId( tuple.get_item(1)?.extract::()?, ))), _ => Err(PyErr::new::(format!( "Unknown conflict type: {}", tuple.get_item(0)?.extract::()? ))), } } } breezyshim-0.1.227/src/transport.rs000064400000000000000000000062411046102023000153520ustar 00000000000000//! Transport module use crate::error::Error; use pyo3::prelude::*; use pyo3::types::PyDict; use std::path::{Path, PathBuf}; 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() }) } pub fn local_abspath(&self, path: &Path) -> Result { pyo3::Python::with_gil(|py| { Ok(self .0 .call_method1(py, "local_abspath", (path,)) .unwrap() .extract::(py) .unwrap()) }) } pub fn has(&self, path: &str) -> Result { pyo3::Python::with_gil(|py| { Ok(self .0 .call_method1(py, "has", (path,))? .extract::(py) .unwrap()) }) } pub fn ensure_base(&self) -> Result<(), Error> { pyo3::Python::with_gil(|py| { self.0.call_method0(py, "ensure_base")?; Ok(()) }) } pub fn create_prefix(&self) -> Result<(), Error> { pyo3::Python::with_gil(|py| { self.0.call_method0(py, "create_prefix")?; Ok(()) }) } pub fn clone(&self, path: &str) -> Result { pyo3::Python::with_gil(|py| { let o = self.0.call_method1(py, "clone", (path,))?; Ok(Transport(o.to_object(py))) }) } } impl FromPyObject<'_> for Transport { fn extract_bound(obj: &Bound) -> PyResult { Ok(Transport(obj.to_object(obj.py()))) } } impl ToPyObject for Transport { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } pub fn get_transport( url: &url::Url, possible_transports: Option<&mut Vec>, ) -> Result { pyo3::Python::with_gil(|py| { let urlutils = py.import_bound("breezy.transport").unwrap(); let kwargs = PyDict::new_bound(py); kwargs.set_item( "possible_transports", possible_transports.map(|t| { t.iter() .map(|t| t.0.clone_ref(py)) .collect::>() }), )?; let o = urlutils.call_method("get_transport", (url.to_string(),), Some(&kwargs))?; Ok(Transport(o.to_object(py))) }) } breezyshim-0.1.227/src/tree.rs000064400000000000000000000515131046102023000142570ustar 00000000000000//! Trees use crate::branch::Branch; use crate::error::Error; use crate::lock::Lock; use crate::revisionid::RevisionId; use pyo3::prelude::*; pub type Path = std::path::Path; pub type PathBuf = std::path::PathBuf; #[derive(Debug, PartialEq, Clone, Eq)] 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 => "+", } } } impl std::fmt::Display for Kind { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Kind::File => write!(f, "file"), Kind::Directory => write!(f, "directory"), Kind::Symlink => write!(f, "symlink"), Kind::TreeReference => write!(f, "tree-reference"), } } } impl std::str::FromStr for Kind { type Err = String; fn from_str(s: &str) -> Result { match s { "file" => Ok(Kind::File), "directory" => Ok(Kind::Directory), "symlink" => Ok(Kind::Symlink), "tree-reference" => Ok(Kind::TreeReference), n => { return Err(format!("Invalid kind: {}", n)); } } } } 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_bound(ob: &Bound) -> 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_bound(ob: &Bound) -> PyResult { let kind: String = ob.getattr("kind")?.extract()?; match kind.as_str() { "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), } } } pub trait Tree: ToPyObject { fn get_tag_dict(&self) -> Result, Error> { 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) }) .map_err(|e: PyErr| -> Error { e.into() }) } 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_symlink_target(&self, path: &Path) -> Result { Python::with_gil(|py| { let target = self .to_object(py) .call_method1(py, "get_symlink_target", (path,))?; target.extract(py).map_err(|e| e.into()) }) } 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 kind(&self, path: &Path) -> Result { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "kind", (path,)) .unwrap() .extract(py) .map_err(|e| e.into()) }) } 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_bound(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_bound( 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_bound(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_bound( 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 struct GenericTree(PyObject); impl ToPyObject for GenericTree { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl From for GenericTree { fn from(obj: PyObject) -> Self { GenericTree(obj) } } impl Tree for GenericTree {} pub trait MutableTree: Tree { fn add(&self, files: &[&Path]) -> Result<(), Error> { for f in files { assert!(f.is_relative()); } Python::with_gil(|py| -> Result<(), PyErr> { self.to_object(py).call_method1( py, "add", (files.iter().map(|p| p.to_path_buf()).collect::>(),), )?; Ok(()) }) .map_err(|e| e.into()) } fn lock_write(&self) -> Result { Python::with_gil(|py| { let lock = self.to_object(py).call_method0(py, "lock_write")?; Ok(Lock::from(lock)) }) } fn put_file_bytes_non_atomic(&self, path: &Path, data: &[u8]) -> Result<(), Error> { assert!(path.is_relative()); 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> { assert!(path.is_relative()); Python::with_gil(|py| -> Result<(), PyErr> { self.to_object(py).call_method1(py, "mkdir", (path,))?; Ok(()) }) .map_err(|e| e.into()) } fn remove(&self, files: &[&std::path::Path]) -> Result<(), Error> { for f in files { assert!(f.is_relative()); } Python::with_gil(|py| -> Result<(), PyErr> { self.to_object(py).call_method1( py, "remove", (files.iter().map(|p| p.to_path_buf()).collect::>(),), )?; Ok(()) }) .map_err(|e| e.into()) } fn as_tree(&self) -> &dyn Tree; } 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 {} impl Clone for RevisionTree { fn clone(&self) -> Self { Python::with_gil(|py| RevisionTree(self.0.clone_ref(py))) } } impl RevisionTree { pub fn repository(&self) -> crate::repository::Repository { Python::with_gil(|py| { let repository = self.to_object(py).getattr(py, "_repository").unwrap(); crate::repository::Repository::new(repository) }) } pub fn get_revision_id(&self) -> RevisionId { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "get_revision_id") .unwrap() .extract(py) .unwrap() }) } pub fn get_parent_ids(&self) -> Vec { Python::with_gil(|py| { self.to_object(py) .call_method0(py, "get_parent_ids") .unwrap() .extract(py) .unwrap() }) } } #[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_bound(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_bound(obj: &Bound) -> PyResult { fn from_bool(o: &Bound) -> PyResult { if let Ok(b) = o.extract::() { Ok(b != 0) } else { o.extract::() } } fn from_opt_bool_tuple(o: &Bound) -> PyResult<(Option, Option)> { let tuple = o.extract::<(Option>, Option>)>()?; Ok(( tuple.0.map(|o| from_bool(&o.as_borrowed())).transpose()?, tuple.1.map(|o| from_bool(&o.as_borrowed())).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_ref(py) } } 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 { fn as_tree(&self) -> &dyn Tree { self } } pub use crate::workingtree::WorkingTree; #[cfg(test)] mod tests { use super::*; use crate::controldir::{create_standalone_workingtree, ControlDirFormat}; #[test] fn test_remove() { let td = tempfile::tempdir().unwrap(); let wt = create_standalone_workingtree(td.path(), &ControlDirFormat::default()).unwrap(); let path = td.path().join("foo"); std::fs::write(&path, b"").unwrap(); wt.add(&[(std::path::Path::new("foo"))]).unwrap(); wt.build_commit() .message("Initial commit") .reporter(&crate::commit::NullCommitReporter::new()) .commit() .unwrap(); assert!(wt.has_filename(&path)); wt.remove(&[Path::new("foo")]).unwrap(); assert!(!wt.is_versioned(&path)); std::mem::drop(td); } } breezyshim-0.1.227/src/ui.rs000064400000000000000000000036671046102023000137440ustar 00000000000000//! UI Factory use pyo3::prelude::*; pub trait UIFactory: ToPyObject {} pub struct SilentUIFactory(PyObject); impl SilentUIFactory { pub fn new() -> Self { Python::with_gil(|py| { SilentUIFactory( py.import_bound("breezy.ui") .unwrap() .getattr("SilentUIFactory") .unwrap() .call0() .unwrap() .to_object(py), ) }) } } impl Default for SilentUIFactory { fn default() -> Self { Self::new() } } pub struct GenericUIFactory(PyObject); impl ToPyObject for GenericUIFactory { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl UIFactory for GenericUIFactory {} impl ToPyObject for SilentUIFactory { fn to_object(&self, py: Python) -> PyObject { self.0.clone_ref(py) } } impl UIFactory for SilentUIFactory {} pub fn install_ui_factory(factory: &dyn UIFactory) { Python::with_gil(|py| { let m = py.import_bound("breezy.ui").unwrap(); m.setattr("ui_factory", factory.to_object(py)).unwrap(); }); } pub fn get_ui_factory() -> Box { Box::new(GenericUIFactory(Python::with_gil(|py| { let m = py.import_bound("breezy.ui").unwrap(); m.getattr("ui_factory").unwrap().to_object(py) }))) as Box } pub fn with_silent_ui_factory(f: impl FnOnce() -> R) -> R { let old_factory = get_ui_factory(); let new_factory = SilentUIFactory::new(); install_ui_factory(&new_factory); let r = f(); install_ui_factory(old_factory.as_ref()); r } #[cfg(test)] mod tests { use super::*; #[test] fn test_create_silent_factory() { let _ = SilentUIFactory::new(); } #[test] fn test_run_with_silent_factory() { with_silent_ui_factory(|| { crate::version::version(); }); } } breezyshim-0.1.227/src/urlutils.rs000064400000000000000000000067361046102023000152120ustar 00000000000000//! URL manipulation utilities. use pyo3::prelude::*; pub fn join_segment_parameters( url: &url::Url, parameters: std::collections::HashMap, ) -> url::Url { pyo3::Python::with_gil(|py| { let urlutils = py.import_bound("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_bound("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() }) } fn char_is_safe(c: char) -> bool { c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' } pub fn escape(relpath: &[u8], safe: Option<&str>) -> String { let mut result = String::new(); let safe = safe.unwrap_or("/~").as_bytes(); for b in relpath { if char_is_safe(char::from(*b)) || safe.contains(b) { result.push(char::from(*b)); } else { result.push_str(&format!("%{:02X}", *b)); } } result } pub fn escape_utf8(relpath: &str, safe: Option<&str>) -> String { escape(relpath.as_bytes(), safe) } pub fn unescape_utf8(url: &str) -> String { use percent_encoding::percent_decode_str; percent_decode_str(url) .decode_utf8() .map(|s| s.to_string()) .unwrap_or_else(|_| url.to_string()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_escape() { assert_eq!(escape(b"blah", None), "blah"); assert_eq!(escape(b"blah", Some("")), "blah"); assert_eq!(escape(b"blah", Some("/~")), "blah"); assert_eq!(escape(b"la/bla", None), "la/bla"); assert_eq!(escape(b"la/bla", Some("")), "la%2Fbla"); assert_eq!(escape_utf8("la/bla", Some("/")), "la/bla"); } #[test] fn test_unescape() { assert_eq!(unescape_utf8("blah"), "blah"); assert_eq!(unescape_utf8("la%2Fbla"), "la/bla"); } #[test] fn test_split_segment_parameters() { let url = url::Url::parse("http://example.com/blah,a=1,b=2").unwrap(); let (result_url, result_parameters) = split_segment_parameters(&url); assert_eq!( result_url, url::Url::parse("http://example.com/blah").unwrap() ); let mut expected_parameters = std::collections::HashMap::new(); expected_parameters.insert("a".to_string(), "1".to_string()); expected_parameters.insert("b".to_string(), "2".to_string()); assert_eq!(result_parameters, expected_parameters); } #[test] fn test_join_segment_parameters() { let url = url::Url::parse("http://example.com/blah").unwrap(); let mut parameters = std::collections::HashMap::new(); parameters.insert("a".to_string(), "1".to_string()); parameters.insert("b".to_string(), "2".to_string()); let result = join_segment_parameters(&url, parameters); assert_eq!( result, url::Url::parse("http://example.com/blah,a=1,b=2").unwrap() ); } } breezyshim-0.1.227/src/version.rs000064400000000000000000000046121046102023000150030ustar 00000000000000//! Version information for the Breezy library. use 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_bound("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, } }) } #[test] fn test_version_serialize() { let v = Version { major: 1, minor: 2, micro: 3, level: ReleaseLevel::Final, serial: 0, }; assert_eq!(v.to_string(), "1.2.3"); } #[test] fn test_version() { version().to_string(); } breezyshim-0.1.227/src/workingtree.rs000064400000000000000000000256271046102023000156670ustar 00000000000000//! Working trees use crate::branch::{Branch, GenericBranch}; use crate::controldir::ControlDir; use crate::error::Error; use crate::tree::{MutableTree, RevisionTree, Tree}; use crate::RevisionId; use pyo3::prelude::*; use std::path::{Path, PathBuf}; pub struct WorkingTree(pub PyObject); impl Clone for WorkingTree { fn clone(&self) -> Self { Python::with_gil(|py| WorkingTree(self.0.clone_ref(py))) } } impl ToPyObject for WorkingTree { fn to_object(&self, py: Python) -> PyObject { self.0.to_object(py) } } pub struct CommitBuilder(WorkingTree, Py); impl From for CommitBuilder { fn from(wt: WorkingTree) -> Self { Python::with_gil(|py| { let kwargs = pyo3::types::PyDict::new_bound(py); CommitBuilder(wt, kwargs.into()) }) } } impl CommitBuilder { pub fn committer(self, committer: &str) -> Self { Python::with_gil(|py| { self.1.bind(py).set_item("committer", committer).unwrap(); }); self } pub fn message(self, message: &str) -> Self { Python::with_gil(|py| { self.1.bind(py).set_item("message", message).unwrap(); }); self } pub fn specific_files(self, specific_files: &[&Path]) -> Self { let specific_files: Vec = specific_files.iter().map(|x| x.to_path_buf()).collect(); Python::with_gil(|py| { self.1 .bind(py) .set_item("specific_files", specific_files) .unwrap(); }); self } pub fn allow_pointless(self, allow_pointless: bool) -> Self { Python::with_gil(|py| { self.1 .bind(py) .set_item("allow_pointless", allow_pointless) .unwrap(); }); self } pub fn reporter(self, reporter: &dyn crate::commit::CommitReporter) -> Self { Python::with_gil(|py| { self.1.bind(py).set_item("reporter", reporter).unwrap(); }); self } pub fn commit(self) -> Result { Python::with_gil(|py| { Ok(self .0 .to_object(py) .call_method_bound(py, "commit", (), Some(self.1.bind(py)))? .extract(py) .unwrap()) }) } } impl WorkingTree { pub fn is_control_filename(&self, path: &Path) -> bool { Python::with_gil(|py| { self.to_object(py) .call_method1(py, "is_control_filename", (path,)) .unwrap() .extract(py) .unwrap() }) } /// 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(GenericBranch::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) }) } #[deprecated = "Use ::open instead"] pub fn open(path: &Path) -> Result { open(path) } #[deprecated = "Use ::open_containing instead"] pub fn open_containing(path: &Path) -> Result<(WorkingTree, PathBuf), Error> { open_containing(path) } pub fn basis_tree(&self) -> Result { Python::with_gil(|py| { let tree = self.to_object(py).call_method0(py, "basis_tree")?; Ok(RevisionTree(tree)) }) } pub fn revision_tree(&self, revision_id: &RevisionId) -> Result, Error> { Python::with_gil(|py| { let tree = self.to_object(py).call_method1( py, "revision_tree", (revision_id.to_object(py),), )?; Ok(Box::new(RevisionTree(tree))) }) } pub fn get_tag_dict(&self) -> Result, Error> { 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) }) .map_err(|e: PyErr| -> Error { e.into() }) } 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 build_commit(&self) -> CommitBuilder { CommitBuilder::from(self.clone()) } #[deprecated = "Use build_commit instead"] pub fn commit( &self, message: &str, allow_pointless: Option, committer: Option<&str>, specific_files: Option<&[&Path]>, ) -> Result { let mut builder = self.build_commit().message(message); if let Some(specific_files) = specific_files { builder = builder.specific_files(specific_files); } if let Some(allow_pointless) = allow_pointless { builder = builder.allow_pointless(allow_pointless); } if let Some(committer) = committer { builder = builder.committer(committer); } builder.commit() } 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, overwrite: Option, stop_revision: Option<&RevisionId>, local: Option, ) -> Result<(), Error> { Python::with_gil(|py| { let kwargs = { let kwargs = pyo3::types::PyDict::new_bound(py); if let Some(overwrite) = overwrite { kwargs.set_item("overwrite", overwrite).unwrap(); } if let Some(stop_revision) = stop_revision { kwargs .set_item("stop_revision", stop_revision.to_object(py)) .unwrap(); } if let Some(local) = local { kwargs.set_item("local", local).unwrap(); } kwargs }; self.to_object(py) .call_method_bound(py, "pull", (source.to_object(py),), Some(&kwargs)) }) .map_err(|e| e.into()) .map(|_| ()) } pub fn merge_from_branch( &self, source: &dyn Branch, to_revision: Option<&RevisionId>, ) -> Result<(), Error> { Python::with_gil(|py| { let kwargs = { let kwargs = pyo3::types::PyDict::new_bound(py); if let Some(to_revision) = to_revision { kwargs .set_item("to_revision", to_revision.to_object(py)) .unwrap(); } kwargs }; self.to_object(py).call_method_bound( py, "merge_from_branch", (source.to_object(py),), Some(&kwargs), ) }) .map_err(|e| e.into()) .map(|_| ()) } pub fn update(&self, revision: Option<&RevisionId>) -> Result<(), Error> { Python::with_gil(|py| { let kwargs = { let kwargs = pyo3::types::PyDict::new_bound(py); kwargs.set_item("revision", revision.to_object(py)).unwrap(); kwargs }; self.to_object(py) .call_method_bound(py, "update", (), Some(&kwargs)) }) .map_err(|e| e.into()) .map(|_| ()) } pub fn safe_relpath_files( &self, file_list: &[&Path], canonicalize: bool, apply_view: bool, ) -> Result, Error> { Python::with_gil(|py| { let result = self.to_object(py).call_method1( py, "safe_relpath_files", ( file_list .iter() .map(|x| x.to_path_buf()) .collect::>(), canonicalize, apply_view, ), )?; Ok(result.extract(py)?) }) } } pub fn open(path: &Path) -> Result { Python::with_gil(|py| { let m = py.import_bound("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), Error> { Python::with_gil(|py| { let m = py.import_bound("breezy.workingtree")?; let c = m.getattr("WorkingTree")?; let (wt, p): (Bound, String) = c.call_method1("open_containing", (path,))?.extract()?; Ok((WorkingTree(wt.to_object(py)), PathBuf::from(p))) }) } impl From for WorkingTree { fn from(obj: PyObject) -> Self { WorkingTree(obj) } } impl Tree for WorkingTree {} impl MutableTree for WorkingTree { fn as_tree(&self) -> &dyn Tree { self } } breezyshim-0.1.227/src/workspace.rs000064400000000000000000000035031046102023000153120ustar 00000000000000//! Convenience functions for automated operations on a VCS tree #[cfg(feature = "dirty-tracker")] use crate::dirty_tracker::{DirtyTreeTracker, State as DirtyTrackerState}; use crate::error::Error; use crate::tree::{Tree, WorkingTree}; use pyo3::prelude::*; #[cfg(feature = "dirty-tracker")] pub fn reset_tree_with_dirty_tracker( local_tree: &WorkingTree, basis_tree: Option<&dyn Tree>, subpath: Option<&std::path::Path>, dirty_tracker: Option<&mut DirtyTreeTracker>, ) -> Result<(), Error> { if let Some(dirty_tracker) = dirty_tracker { if dirty_tracker.state() == DirtyTrackerState::Clean { return Ok(()); } // TODO: Only reset those files that are dirty } reset_tree(local_tree, basis_tree, subpath) } pub fn reset_tree( local_tree: &WorkingTree, basis_tree: Option<&dyn Tree>, subpath: Option<&std::path::Path>, ) -> Result<(), Error> { Python::with_gil(|py| { let workspace_m = py.import_bound("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)); reset_tree.call1((local_tree, basis_tree, subpath))?; Ok(()) }) } pub fn check_clean_tree( local_tree: &WorkingTree, basis_tree: &dyn Tree, subpath: &std::path::Path, ) -> Result<(), Error> { Python::with_gil(|py| { let workspace_m = py.import_bound("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(()) }) }