python-merge3-0.0.8/.github/0000755000000000000000000000000014023137703012506 5ustar00python-merge3-0.0.8/.gitignore0000644000000000000000000000002514023137703013133 0ustar00*~ *.pyc __pycache__ python-merge3-0.0.8/AUTHORS0000644000000000000000000000027614023137703012223 0ustar00merge3 was originally written by Martin Pool as part of Bazaar (https://www.bazaar-vcs.org/) and split out into a separate package by Jelmer Vernooij python-merge3-0.0.8/COPYING0000644000000000000000000004325414023137703012211 0ustar00 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. python-merge3-0.0.8/MANIFEST.in0000644000000000000000000000006314023137703012703 0ustar00include README.rst include AUTHORS include COPYING python-merge3-0.0.8/README.rst0000644000000000000000000000131414023137703012634 0ustar00A Python implementation of 3-way merge of texts. Given BASE, OTHER, THIS, tries to produce a combined text incorporating the changes from both BASE->OTHER and BASE->THIS. All three will typically be sequences of lines. Usage ===== From the command-line:: $ echo foo > mine $ echo bar > base $ echo blah > other $ python -m merge3 mine base other > merged $ cat merged Or from Python:: >>> import merge3 >>> m3 = merge3.Merge3( ... ['common\n', 'base\n'], ... ['common\n', 'a\n'], ... ['common\n', 'b\n']) >>> list(m3.merge_annotated()) ['u | common\n', '<<<<\n', 'A | a\n', '----\n', 'B | b\n', '>>>>\n'] python-merge3-0.0.8/merge3/0000755000000000000000000000000014023137703012330 5ustar00python-merge3-0.0.8/releaser.conf0000644000000000000000000000052114023137703013615 0ustar00name: "merge3" timeout_days: 5 tag_name: "v$VERSION" verify_command: "python3 setup.py test" update_version { path: "setup.py" match: "^ version=\"(.*)\"," new_line: " version=\"$VERSION\"," } update_version { path: "merge3/__init__.py" match: "^__version__ = \((.*)\)$" new_line: "__version__ = $TUPLED_VERSION" } python-merge3-0.0.8/setup.py0000755000000000000000000000221714023137703012665 0ustar00#!/usr/bin/env python3 # encoding: utf-8 from setuptools import setup with open('README.rst', 'r') as f: long_description = f.read() setup(name="merge3", description="Python implementation of 3-way merge.", long_description=long_description, long_description_content_type='text/x-rst', version="0.0.8", maintainer="Breezy Developers", maintainer_email="team@breezy-vcs.org", license="GNU GPLv2 or later", url="https://www.breezy-vcs.org/", packages=['merge3'], test_suite='merge3.test_merge3', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', # noqa 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: POSIX', ]) python-merge3-0.0.8/.github/workflows/0000755000000000000000000000000014023137703014543 5ustar00python-merge3-0.0.8/.github/workflows/pythonpackage.yml0000644000000000000000000000162614023137703020130 0ustar00--- name: Python package on: [push, pull_request] jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: [2.7, 3.6, 3.7, 3.8, pypy3] exclude: - os: windows-latest python-version: 2.7 fail-fast: false steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -U pip coverage codecov flake8 patiencediff - name: Style checks run: | python -m flake8 - name: Test suite run run: | python -m unittest merge3.test_merge3 env: PYTHONHASHSEED: random python-merge3-0.0.8/merge3/__init__.py0000644000000000000000000004527014023137703014451 0ustar00# Copyright (C) 2005-2010 Canonical Ltd # # 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 from __future__ import absolute_import # mbp: "you know that thing where cvs gives you conflict markers?" # s: "i hate that." __version__ = (0, 0, 8) class CantReprocessAndShowBase(Exception): """Can't reprocess and show base.""" def intersect(ra, rb): """Given two ranges return the range where they intersect or None. >>> intersect((0, 10), (0, 6)) (0, 6) >>> intersect((0, 10), (5, 15)) (5, 10) >>> intersect((0, 10), (10, 15)) >>> intersect((0, 9), (10, 15)) >>> intersect((0, 9), (7, 15)) (7, 9) """ # preconditions: (ra[0] <= ra[1]) and (rb[0] <= rb[1]) sa = max(ra[0], rb[0]) sb = min(ra[1], rb[1]) if sa < sb: return sa, sb else: return None def compare_range(a, astart, aend, b, bstart, bend): """Compare a[astart:aend] == b[bstart:bend], without slicing. """ if (aend-astart) != (bend-bstart): return False for ia, ib in zip(range(astart, aend), range(bstart, bend)): if a[ia] != b[ib]: return False else: return True class Merge3(object): """3-way merge of texts. Given BASE, OTHER, THIS, tries to produce a combined text incorporating the changes from both BASE->OTHER and BASE->THIS. All three will typically be sequences of lines.""" def __init__(self, base, a, b, is_cherrypick=False, sequence_matcher=None): """Constructor. :param base: lines in BASE :param a: lines in A :param b: lines in B :param is_cherrypick: flag indicating if this merge is a cherrypick. When cherrypicking b => a, matches with b and base do not conflict. :param sequence_matcher: Sequence matcher to use (defaults to difflib.SequenceMatcher) """ if sequence_matcher is None: import difflib sequence_matcher = difflib.SequenceMatcher self.base = base self.a = a self.b = b self.is_cherrypick = is_cherrypick self.sequence_matcher = sequence_matcher def _uses_bytes(self): if len(self.a) > 0: return isinstance(self.a[0], bytes) elif len(self.base) > 0: return isinstance(self.base[0], bytes) elif len(self.b) > 0: return isinstance(self.b[0], bytes) else: return False def merge_lines(self, name_a=None, name_b=None, name_base=None, start_marker='<<<<<<<', mid_marker='=======', end_marker='>>>>>>>', base_marker=None, reprocess=False): """Return merge in cvs-like form. """ if base_marker and reprocess: raise CantReprocessAndShowBase() if self._uses_bytes(): if len(self.a) > 0: if self.a[0].endswith(b'\r\n'): newline = b'\r\n' elif self.a[0].endswith(b'\r'): newline = b'\r' else: newline = b'\n' else: newline = b'\n' if isinstance(start_marker, str): start_marker = start_marker.encode() if isinstance(end_marker, str): end_marker = end_marker.encode() if isinstance(mid_marker, str): mid_marker = mid_marker.encode() if base_marker is not None and isinstance(base_marker, str): base_marker = base_marker.encode() if name_a: if isinstance(name_a, str): name_a = name_a.encode() start_marker = start_marker + b' ' + name_a if name_b: if isinstance(name_b, str): name_b = name_b.encode() end_marker = end_marker + b' ' + name_b if name_base and base_marker: if isinstance(name_base, str): name_base = name_base.encode() base_marker = base_marker + b' ' + name_base else: if len(self.a) > 0: if self.a[0].endswith('\r\n'): newline = '\r\n' elif self.a[0].endswith('\r'): newline = '\r' else: newline = '\n' else: newline = '\n' if name_a: start_marker = start_marker + ' ' + name_a if name_b: end_marker = end_marker + ' ' + name_b if name_base and base_marker: base_marker = base_marker + ' ' + name_base merge_regions = self.merge_regions() if reprocess is True: merge_regions = self.reprocess_merge_regions(merge_regions) for t in merge_regions: what = t[0] if what == 'unchanged': for i in range(t[1], t[2]): yield self.base[i] elif what == 'a' or what == 'same': for i in range(t[1], t[2]): yield self.a[i] elif what == 'b': for i in range(t[1], t[2]): yield self.b[i] elif what == 'conflict': yield start_marker + newline for i in range(t[3], t[4]): yield self.a[i] if base_marker is not None: yield base_marker + newline for i in range(t[1], t[2]): yield self.base[i] yield mid_marker + newline for i in range(t[5], t[6]): yield self.b[i] yield end_marker + newline else: raise ValueError(what) def merge_annotated(self): """Return merge with conflicts, showing origin of lines. Most useful for debugging merge. """ UNCHANGED = 'u' SEP = ' | ' CONFLICT_START = '<<<<\n' CONFLICT_MID = '----\n' CONFLICT_END = '>>>>\n' WIN_A = 'a' WIN_B = 'b' if self._uses_bytes(): UNCHANGED = UNCHANGED.encode() SEP = SEP.encode() CONFLICT_START = CONFLICT_START.encode() CONFLICT_MID = CONFLICT_MID.encode() CONFLICT_END = CONFLICT_END.encode() WIN_A = WIN_A.encode() WIN_B = WIN_B.encode() for t in self.merge_regions(): what = t[0] if what == 'unchanged': for i in range(t[1], t[2]): yield UNCHANGED + SEP + self.base[i] elif what == 'a' or what == 'same': for i in range(t[1], t[2]): yield WIN_A.lower() + SEP + self.a[i] elif what == 'b': for i in range(t[1], t[2]): yield WIN_B.lower() + SEP + self.b[i] elif what == 'conflict': yield CONFLICT_START for i in range(t[3], t[4]): yield WIN_A.upper() + SEP + self.a[i] yield CONFLICT_MID for i in range(t[5], t[6]): yield WIN_B.upper() + SEP + self.b[i] yield CONFLICT_END else: raise ValueError(what) def merge_groups(self): """Yield sequence of line groups. Each one is a tuple: 'unchanged', lines Lines unchanged from base 'a', lines Lines taken from a 'same', lines Lines taken from a (and equal to b) 'b', lines Lines taken from b 'conflict', base_lines, a_lines, b_lines Lines from base were changed to either a or b and conflict. """ for t in self.merge_regions(): what = t[0] if what == 'unchanged': yield what, self.base[t[1]:t[2]] elif what == 'a' or what == 'same': yield what, self.a[t[1]:t[2]] elif what == 'b': yield what, self.b[t[1]:t[2]] elif what == 'conflict': yield (what, self.base[t[1]:t[2]], self.a[t[3]:t[4]], self.b[t[5]:t[6]]) else: raise ValueError(what) def merge_regions(self): """Return sequences of matching and conflicting regions. This returns tuples, where the first value says what kind we have: 'unchanged', start, end Take a region of base[start:end] 'same', astart, aend b and a are different from base but give the same result 'a', start, end Non-clashing insertion from a[start:end] Method is as follows: The two sequences align only on regions which match the base and both descendents. These are found by doing a two-way diff of each one against the base, and then finding the intersections between those regions. These "sync regions" are by definition unchanged in both and easily dealt with. The regions in between can be in any of three cases: conflicted, or changed on only one side. """ # section a[0:ia] has been disposed of, etc iz = ia = ib = 0 for (zmatch, zend, amatch, aend, bmatch, bend) in self.find_sync_regions(): matchlen = zend - zmatch # invariants: # matchlen >= 0 # matchlen == (aend - amatch) # matchlen == (bend - bmatch) len_a = amatch - ia len_b = bmatch - ib # len_base = zmatch - iz # invariants: # assert len_a >= 0 # assert len_b >= 0 # assert len_base >= 0 # print 'unmatched a=%d, b=%d' % (len_a, len_b) if len_a or len_b: # try to avoid actually slicing the lists same = compare_range(self.a, ia, amatch, self.b, ib, bmatch) if same: yield 'same', ia, amatch else: equal_a = compare_range(self.a, ia, amatch, self.base, iz, zmatch) equal_b = compare_range(self.b, ib, bmatch, self.base, iz, zmatch) if equal_a and not equal_b: yield 'b', ib, bmatch elif equal_b and not equal_a: yield 'a', ia, amatch elif not equal_a and not equal_b: if self.is_cherrypick: for node in self._refine_cherrypick_conflict( iz, zmatch, ia, amatch, ib, bmatch): yield node else: yield ( 'conflict', iz, zmatch, ia, amatch, ib, bmatch) else: raise AssertionError( "can't handle a=b=base but unmatched") ia = amatch ib = bmatch iz = zmatch # if the same part of the base was deleted on both sides # that's OK, we can just skip it. if matchlen > 0: # invariants: # assert ia == amatch # assert ib == bmatch # assert iz == zmatch yield 'unchanged', zmatch, zend iz = zend ia = aend ib = bend def _refine_cherrypick_conflict(self, zstart, zend, astart, aend, bstart, bend): """When cherrypicking b => a, ignore matches with b and base.""" # Do not emit regions which match, only regions which do not match matcher = self.sequence_matcher( None, self.base[zstart:zend], self.b[bstart:bend]) matches = matcher.get_matching_blocks() last_base_idx = 0 last_b_idx = 0 last_b_idx = 0 yielded_a = False for base_idx, b_idx, match_len in matches: # conflict_z_len = base_idx - last_base_idx conflict_b_len = b_idx - last_b_idx # There are no lines in b which conflict, so skip it if conflict_b_len == 0: pass else: if yielded_a: yield ('conflict', zstart + last_base_idx, zstart + base_idx, aend, aend, bstart + last_b_idx, bstart + b_idx) else: # The first conflict gets the a-range yielded_a = True yield ( 'conflict', zstart + last_base_idx, zstart + base_idx, astart, aend, bstart + last_b_idx, bstart + b_idx) last_base_idx = base_idx + match_len last_b_idx = b_idx + match_len if last_base_idx != zend - zstart or last_b_idx != bend - bstart: if yielded_a: yield ('conflict', zstart + last_base_idx, zstart + base_idx, aend, aend, bstart + last_b_idx, bstart + b_idx) else: # The first conflict gets the a-range yielded_a = True yield ('conflict', zstart + last_base_idx, zstart + base_idx, astart, aend, bstart + last_b_idx, bstart + b_idx) if not yielded_a: yield ('conflict', zstart, zend, astart, aend, bstart, bend) def reprocess_merge_regions(self, merge_regions): """Where there are conflict regions, remove the agreed lines. Lines where both A and B have made the same changes are eliminated. """ for region in merge_regions: if region[0] != "conflict": yield region continue type, iz, zmatch, ia, amatch, ib, bmatch = region a_region = self.a[ia:amatch] b_region = self.b[ib:bmatch] matches = self.sequence_matcher( None, a_region, b_region).get_matching_blocks() next_a = ia next_b = ib for region_ia, region_ib, region_len in matches[:-1]: region_ia += ia region_ib += ib reg = self.mismatch_region(next_a, region_ia, next_b, region_ib) if reg is not None: yield reg yield 'same', region_ia, region_len+region_ia next_a = region_ia + region_len next_b = region_ib + region_len reg = self.mismatch_region(next_a, amatch, next_b, bmatch) if reg is not None: yield reg @staticmethod def mismatch_region(next_a, region_ia, next_b, region_ib): if next_a < region_ia or next_b < region_ib: return 'conflict', None, None, next_a, region_ia, next_b, region_ib def find_sync_regions(self): """Return a list of sync regions, where both descendents match the base. Generates a list of (base1, base2, a1, a2, b1, b2). There is always a zero-length sync region at the end of all the files. """ ia = ib = 0 amatches = self.sequence_matcher( None, self.base, self.a).get_matching_blocks() bmatches = self.sequence_matcher( None, self.base, self.b).get_matching_blocks() len_a = len(amatches) len_b = len(bmatches) sl = [] while ia < len_a and ib < len_b: abase, amatch, alen = amatches[ia] bbase, bmatch, blen = bmatches[ib] # there is an unconflicted block at i; how long does it # extend? until whichever one ends earlier. i = intersect((abase, abase+alen), (bbase, bbase+blen)) if i: intbase = i[0] intend = i[1] intlen = intend - intbase # found a match of base[i[0], i[1]]; this may be less than # the region that matches in either one # assert intlen <= alen # assert intlen <= blen # assert abase <= intbase # assert bbase <= intbase asub = amatch + (intbase - abase) bsub = bmatch + (intbase - bbase) aend = asub + intlen bend = bsub + intlen # assert self.base[intbase:intend] == self.a[asub:aend], \ # (self.base[intbase:intend], self.a[asub:aend]) # assert self.base[intbase:intend] == self.b[bsub:bend] sl.append((intbase, intend, asub, aend, bsub, bend)) # advance whichever one ends first in the base text if (abase + alen) < (bbase + blen): ia += 1 else: ib += 1 intbase = len(self.base) abase = len(self.a) bbase = len(self.b) sl.append((intbase, intbase, abase, abase, bbase, bbase)) return sl def find_unconflicted(self): """Return a list of ranges in base that are not conflicted.""" am = self.sequence_matcher( None, self.base, self.a).get_matching_blocks() bm = self.sequence_matcher( None, self.base, self.b).get_matching_blocks() unc = [] while am and bm: # there is an unconflicted block at i; how long does it # extend? until whichever one ends earlier. a1 = am[0][0] a2 = a1 + am[0][2] b1 = bm[0][0] b2 = b1 + bm[0][2] i = intersect((a1, a2), (b1, b2)) if i: unc.append(i) if a2 < b2: del am[0] else: del bm[0] return unc python-merge3-0.0.8/merge3/__main__.py0000644000000000000000000000341714023137703014427 0ustar00# Copyright (C) 2021 Jelmer Vernooij # # 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 from __future__ import absolute_import from . import Merge3 def main(argv): import argparse parser = argparse.ArgumentParser() # as for diff3 and meld the syntax is "MINE BASE OTHER" parser.add_argument( 'mine', type=argparse.FileType('rt'), help='My text') parser.add_argument( 'base', type=argparse.FileType('rt'), help='Base text') parser.add_argument( 'other', type=argparse.FileType('rt'), help='Other text') parser.add_argument( '--annotated', action='store_true', help='Show annotated view.') args = parser.parse_args() m3 = Merge3( args.base.readlines(), args.mine.readlines(), args.other.readlines()) if args.annotated: sys.stdout.writelines(m3.merge_annotated()) else: sys.stdout.writelines( m3.merge_lines( name_a=args.mine.name, name_b=args.other.name, name_base=args.base.name)) if __name__ == '__main__': import sys sys.exit(main(sys.argv)) python-merge3-0.0.8/merge3/test_merge3.py0000644000000000000000000004373314023137703015135 0ustar00# Copyright (C) 2005-2011, 2016 Canonical Ltd # # 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 import merge3 import unittest import sys if sys.version_info[0] == 3: import struct int2byte = struct.Struct(">B").pack from io import StringIO else: int2byte = chr from StringIO import StringIO def split_lines(t): return StringIO(t).readlines() ############################################################ # test case data from the gnu diffutils manual # common base TZU = split_lines(""" The Nameless is the origin of Heaven and Earth; The named is the mother of all things. Therefore let there always be non-being, so we may see their subtlety, And let there always be being, so we may see their outcome. The two are the same, But after they are produced, they have different names. They both may be called deep and profound. Deeper and more profound, The door of all subtleties! """) LAO = split_lines(""" The Way that can be told of is not the eternal Way; The name that can be named is not the eternal name. The Nameless is the origin of Heaven and Earth; The Named is the mother of all things. Therefore let there always be non-being, so we may see their subtlety, And let there always be being, so we may see their outcome. The two are the same, But after they are produced, they have different names. """) TAO = split_lines(""" The Way that can be told of is not the eternal Way; The name that can be named is not the eternal name. The Nameless is the origin of Heaven and Earth; The named is the mother of all things. Therefore let there always be non-being, so we may see their subtlety, And let there always be being, so we may see their result. The two are the same, But after they are produced, they have different names. -- The Way of Lao-Tzu, tr. Wing-tsit Chan """) MERGED_RESULT = split_lines(""" The Way that can be told of is not the eternal Way; The name that can be named is not the eternal name. The Nameless is the origin of Heaven and Earth; The Named is the mother of all things. Therefore let there always be non-being, so we may see their subtlety, And let there always be being, so we may see their result. The two are the same, But after they are produced, they have different names. <<<<<<< LAO ======= -- The Way of Lao-Tzu, tr. Wing-tsit Chan >>>>>>> TAO """) class TestMerge3(unittest.TestCase): def test_no_changes(self): """No conflicts because nothing changed""" m3 = merge3.Merge3(['aaa', 'bbb'], ['aaa', 'bbb'], ['aaa', 'bbb']) self.assertEqual(m3.find_unconflicted(), [(0, 2)]) self.assertEqual( list(m3.find_sync_regions()), [(0, 2, 0, 2, 0, 2), (2, 2, 2, 2, 2, 2)]) self.assertEqual(list(m3.merge_regions()), [('unchanged', 0, 2)]) self.assertEqual(list(m3.merge_groups()), [('unchanged', ['aaa', 'bbb'])]) def test_front_insert(self): m3 = merge3.Merge3([b'zz'], [b'aaa', b'bbb', b'zz'], [b'zz']) # todo: should use a sentinal at end as from get_matching_blocks # to match without zz self.assertEqual(list(m3.find_sync_regions()), [(0, 1, 2, 3, 0, 1), (1, 1, 3, 3, 1, 1), ]) self.assertEqual(list(m3.merge_regions()), [('a', 0, 2), ('unchanged', 0, 1)]) self.assertEqual(list(m3.merge_groups()), [('a', [b'aaa', b'bbb']), ('unchanged', [b'zz'])]) def test_null_insert(self): m3 = merge3.Merge3([], ['aaa', 'bbb'], []) # todo: should use a sentinal at end as from get_matching_blocks # to match without zz self.assertEqual(list(m3.find_sync_regions()), [(0, 0, 2, 2, 0, 0)]) self.assertEqual(list(m3.merge_regions()), [('a', 0, 2)]) self.assertEqual(list(m3.merge_lines()), ['aaa', 'bbb']) def test_no_conflicts(self): """No conflicts because only one side changed""" m3 = merge3.Merge3(['aaa', 'bbb'], ['aaa', '111', 'bbb'], ['aaa', 'bbb']) self.assertEqual(m3.find_unconflicted(), [(0, 1), (1, 2)]) self.assertEqual(list(m3.find_sync_regions()), [(0, 1, 0, 1, 0, 1), (1, 2, 2, 3, 1, 2), (2, 2, 3, 3, 2, 2), ]) self.assertEqual(list(m3.merge_regions()), [('unchanged', 0, 1), ('a', 1, 2), ('unchanged', 1, 2), ]) def test_append_a(self): m3 = merge3.Merge3(['aaa\n', 'bbb\n'], ['aaa\n', 'bbb\n', '222\n'], ['aaa\n', 'bbb\n']) self.assertEqual(''.join(m3.merge_lines()), 'aaa\nbbb\n222\n') def test_append_b(self): m3 = merge3.Merge3(['aaa\n', 'bbb\n'], ['aaa\n', 'bbb\n'], ['aaa\n', 'bbb\n', '222\n']) self.assertEqual(''.join(m3.merge_lines()), 'aaa\nbbb\n222\n') def test_append_agreement(self): m3 = merge3.Merge3(['aaa\n', 'bbb\n'], ['aaa\n', 'bbb\n', '222\n'], ['aaa\n', 'bbb\n', '222\n']) self.assertEqual(''.join(m3.merge_lines()), 'aaa\nbbb\n222\n') def test_append_clash(self): m3 = merge3.Merge3(['aaa\n', 'bbb\n'], ['aaa\n', 'bbb\n', '222\n'], ['aaa\n', 'bbb\n', '333\n']) ml = m3.merge_lines(name_a='a', name_b='b', start_marker='<<', mid_marker='--', end_marker='>>') self.assertEqual(''.join(ml), '''\ aaa bbb << a 222 -- 333 >> b ''') def test_insert_agreement(self): m3 = merge3.Merge3(['aaa\n', 'bbb\n'], ['aaa\n', '222\n', 'bbb\n'], ['aaa\n', '222\n', 'bbb\n']) ml = m3.merge_lines(name_a='a', name_b='b', start_marker='<<', mid_marker='--', end_marker='>>') self.assertEqual(''.join(ml), 'aaa\n222\nbbb\n') def test_insert_clash(self): """Both try to insert lines in the same place.""" m3 = merge3.Merge3(['aaa\n', 'bbb\n'], ['aaa\n', '111\n', 'bbb\n'], ['aaa\n', '222\n', 'bbb\n']) self.assertEqual(m3.find_unconflicted(), [(0, 1), (1, 2)]) self.assertEqual(list(m3.find_sync_regions()), [(0, 1, 0, 1, 0, 1), (1, 2, 2, 3, 2, 3), (2, 2, 3, 3, 3, 3), ]) self.assertEqual(list(m3.merge_regions()), [('unchanged', 0, 1), ('conflict', 1, 1, 1, 2, 1, 2), ('unchanged', 1, 2)]) self.assertEqual(list(m3.merge_groups()), [('unchanged', ['aaa\n']), ('conflict', [], ['111\n'], ['222\n']), ('unchanged', ['bbb\n']), ]) ml = m3.merge_lines(name_a='a', name_b='b', start_marker='<<', mid_marker='--', end_marker='>>') self.assertEqual(''.join(ml), '''\ aaa << a 111 -- 222 >> b bbb ''') def test_replace_clash(self): """Both try to insert lines in the same place.""" m3 = merge3.Merge3(['aaa', '000', 'bbb'], ['aaa', '111', 'bbb'], ['aaa', '222', 'bbb']) self.assertEqual(m3.find_unconflicted(), [(0, 1), (2, 3)]) self.assertEqual(list(m3.find_sync_regions()), [(0, 1, 0, 1, 0, 1), (2, 3, 2, 3, 2, 3), (3, 3, 3, 3, 3, 3), ]) def test_replace_multi(self): """Replacement with regions of different size.""" m3 = merge3.Merge3([b'aaa', b'000', b'000', b'bbb'], [b'aaa', b'111', b'111', b'111', b'bbb'], [b'aaa', b'222', b'222', b'222', b'222', b'bbb']) self.assertEqual(m3.find_unconflicted(), [(0, 1), (3, 4)]) self.assertEqual(list(m3.find_sync_regions()), [(0, 1, 0, 1, 0, 1), (3, 4, 4, 5, 5, 6), (4, 4, 5, 5, 6, 6), ]) def test_merge_poem(self): """Test case from diff3 manual""" m3 = merge3.Merge3(TZU, LAO, TAO) ml = list(m3.merge_lines('LAO', 'TAO')) self.assertEqual(ml, MERGED_RESULT) def test_merge_poem_bytes(self): """Test case from diff3 manual""" m3 = merge3.Merge3( [line.encode() for line in TZU], [line.encode() for line in LAO], [line.encode() for line in TAO]) ml = list(m3.merge_lines('LAO', 'TAO')) self.assertEqual( ml, [line.encode() for line in MERGED_RESULT]) def test_minimal_conflicts_common(self): """Reprocessing""" base_text = ("a\n" * 20).splitlines(True) this_text = ("a\n"*10 + "b\n" * 10).splitlines(True) other_text = ("a\n"*10 + "c\n" + "b\n" * 8 + "c\n").splitlines(True) m3 = merge3.Merge3(base_text, other_text, this_text) m_lines = m3.merge_lines('OTHER', 'THIS', reprocess=True) merged_text = "".join(list(m_lines)) optimal_text = ( "a\n" * 10 + "<<<<<<< OTHER\nc\n" "=======\n" + ">>>>>>> THIS\n" + 8 * "b\n" + "<<<<<<< OTHER\nc\n" + "=======\n" + 2 * "b\n" + ">>>>>>> THIS\n") self.assertEqual(optimal_text, merged_text) def test_cherrypick(self): base_text = "ba\nb\n" this_text = "ba\n" other_text = "a\nb\nc\n" m3 = merge3.Merge3( base_text.splitlines(True), other_text.splitlines(True), this_text.splitlines(True)) self.assertEqual(m3.find_unconflicted(), []) self.assertEqual(list(m3.find_sync_regions()), [(2, 2, 3, 3, 1, 1)]) def test_minimal_conflicts_common_with_patiencediff(self): """Reprocessing""" try: import patiencediff except ImportError: self.skipTest('patiencediff not available') base_text = ("a\n" * 20).splitlines(True) this_text = ("a\n"*10 + "b\n" * 10).splitlines(True) other_text = ("a\n"*10 + "c\n" + "b\n" * 8 + "c\n").splitlines(True) m3 = merge3.Merge3( base_text, other_text, this_text, sequence_matcher=patiencediff.PatienceSequenceMatcher) m_lines = m3.merge_lines( 'OTHER', 'THIS', reprocess=True) merged_text = "".join(list(m_lines)) optimal_text = ( "a\n" * 10 + "<<<<<<< OTHER\nc\n" + 8 * "b\n" + "c\n=======\n" + 10 * "b\n" + ">>>>>>> THIS\n") self.assertEqual(optimal_text, merged_text) def test_minimal_conflicts_unique(self): def add_newline(s): """Add a newline to each entry in the string""" return [(x+'\n') for x in s] base_text = add_newline("abcdefghijklm") this_text = add_newline("abcdefghijklmNOPQRSTUVWXYZ") other_text = add_newline("abcdefghijklm1OPQRSTUVWXY2") m3 = merge3.Merge3(base_text, other_text, this_text) m_lines = m3.merge_lines('OTHER', 'THIS', reprocess=True) merged_text = "".join(list(m_lines)) optimal_text = ''.join( add_newline("abcdefghijklm") + ["<<<<<<< OTHER\n1\n=======\nN\n>>>>>>> THIS\n"] + add_newline('OPQRSTUVWXY') + ["<<<<<<< OTHER\n2\n=======\nZ\n>>>>>>> THIS\n"] ) self.assertEqual(optimal_text, merged_text) def test_minimal_conflicts_nonunique(self): def add_newline(s): """Add a newline to each entry in the string""" return [(x+'\n') for x in s] base_text = add_newline("abacddefgghij") this_text = add_newline("abacddefgghijkalmontfprz") other_text = add_newline("abacddefgghijknlmontfprd") m3 = merge3.Merge3(base_text, other_text, this_text) m_lines = m3.merge_lines('OTHER', 'THIS', reprocess=True) merged_text = "".join(list(m_lines)) optimal_text = ''.join( add_newline("abacddefgghijk") + ["<<<<<<< OTHER\nn\n=======\na\n>>>>>>> THIS\n"] + add_newline('lmontfpr') + ["<<<<<<< OTHER\nd\n=======\nz\n>>>>>>> THIS\n"] ) self.assertEqual(optimal_text, merged_text) def test_reprocess_and_base(self): """Reprocessing and showing base breaks correctly""" base_text = ("a\n" * 20).splitlines(True) this_text = ("a\n"*10+"b\n" * 10).splitlines(True) other_text = ("a\n"*10+"c\n"+"b\n" * 8 + "c\n").splitlines(True) m3 = merge3.Merge3(base_text, other_text, this_text) m_lines = m3.merge_lines('OTHER', 'THIS', reprocess=True, base_marker='|||||||') self.assertRaises(merge3.CantReprocessAndShowBase, list, m_lines) def test_dos_text(self): base_text = 'a\r\n' this_text = 'b\r\n' other_text = 'c\r\n' m3 = merge3.Merge3(base_text.splitlines(True), other_text.splitlines(True), this_text.splitlines(True)) m_lines = m3.merge_lines('OTHER', 'THIS') self.assertEqual( '<<<<<<< OTHER\r\nc\r\n=======\r\nb\r\n' '>>>>>>> THIS\r\n'.splitlines(True), list(m_lines)) def test_mac_text(self): base_text = 'a\r' this_text = 'b\r' other_text = 'c\r' m3 = merge3.Merge3(base_text.splitlines(True), other_text.splitlines(True), this_text.splitlines(True)) m_lines = m3.merge_lines('OTHER', 'THIS') self.assertEqual( '<<<<<<< OTHER\rc\r=======\rb\r' '>>>>>>> THIS\r'.splitlines(True), list(m_lines)) def test_merge3_cherrypick(self): base_text = "a\nb\n" this_text = "a\n" other_text = "a\nb\nc\n" # When cherrypicking, lines in base are not part of the conflict m3 = merge3.Merge3(base_text.splitlines(True), this_text.splitlines(True), other_text.splitlines(True), is_cherrypick=True) m_lines = m3.merge_lines() self.assertEqual('a\n<<<<<<<\n=======\nc\n>>>>>>>\n', ''.join(m_lines)) # This is not symmetric m3 = merge3.Merge3(base_text.splitlines(True), other_text.splitlines(True), this_text.splitlines(True), is_cherrypick=True) m_lines = m3.merge_lines() self.assertEqual('a\n<<<<<<<\nb\nc\n=======\n>>>>>>>\n', ''.join(m_lines)) def test_merge3_cherrypick_w_mixed(self): base_text = 'a\nb\nc\nd\ne\n' this_text = 'a\nb\nq\n' other_text = 'a\nb\nc\nd\nf\ne\ng\n' # When cherrypicking, lines in base are not part of the conflict m3 = merge3.Merge3(base_text.splitlines(True), this_text.splitlines(True), other_text.splitlines(True), is_cherrypick=True) m_lines = m3.merge_lines() self.assertEqual('a\n' 'b\n' '<<<<<<<\n' 'q\n' '=======\n' 'f\n' '>>>>>>>\n' '<<<<<<<\n' '=======\n' 'g\n' '>>>>>>>\n', ''.join(m_lines)) def test_allow_objects(self): """Objects other than strs may be used with Merge3. merge_groups and merge_regions work with non-str input. Methods that return lines like merge_lines fail. """ base = [(int2byte(x), int2byte(x)) for x in bytearray(b'abcde')] a = [(int2byte(x), int2byte(x)) for x in bytearray(b'abcdef')] b = [(int2byte(x), int2byte(x)) for x in bytearray(b'Zabcde')] m3 = merge3.Merge3(base, a, b) self.assertEqual( [('b', 0, 1), ('unchanged', 0, 5), ('a', 5, 6)], list(m3.merge_regions())) self.assertEqual( [('b', [(b'Z', b'Z')]), ('unchanged', [ (int2byte(x), int2byte(x)) for x in bytearray(b'abcde')]), ('a', [(b'f', b'f')])], list(m3.merge_groups()))