├── .dir-locals.el ├── .ghci ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── ChangeLog.md ├── LICENSE ├── README.md ├── git-mediate.cabal ├── src ├── Conflict.hs ├── Environment.hs ├── Git.hs ├── Main.hs ├── OptUtils.hs ├── Opts.hs ├── PPDiff.hs ├── Resolution.hs ├── ResolutionOpts.hs ├── Setup.hs ├── SideDiff.hs ├── StrUtils.hs └── Version.hs ├── stack.yaml └── test ├── config └── test ├── run_tests ├── spaces └── test └── untabify └── test /.dir-locals.el: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Peaker/git-mediate/5ac7e9d61c52ac82cc19f7efaafcb7a23ec017d6/.dir-locals.el -------------------------------------------------------------------------------- /.ghci: -------------------------------------------------------------------------------- 1 | :set -Wall 2 | :set -isrc -idist/build/autogen -idist/build/git-mediate/autogen 3 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | types: [synchronize, opened, reopened] 7 | push: 8 | branches: [main] 9 | schedule: 10 | # additionally run once per week (At 00:00 on Sunday) to maintain cache 11 | - cron: '0 0 * * 0' 12 | 13 | jobs: 14 | stack: 15 | name: ghc ${{ matrix.ghc }} / ${{ matrix.os }} 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | stack: ["3.1.1"] 20 | ghc: ["9.6.6"] 21 | os: ["ubuntu-latest"] 22 | 23 | runs-on: ${{ matrix.os }} 24 | 25 | steps: 26 | - uses: actions/checkout@v4 27 | 28 | - uses: haskell/actions/setup@v2.4 29 | name: Setup Haskell Stack 30 | with: 31 | ghc-version: ${{ matrix.ghc }} 32 | stack-version: ${{ matrix.stack }} 33 | 34 | - uses: actions/cache@v4.0.2 35 | if: ${{ matrix.os == 'ubuntu-latest' }} 36 | name: Cache ~/.stack 37 | with: 38 | path: ~/.stack 39 | key: ${{ runner.os }}-${{ matrix.ghc }}-stack 40 | 41 | - name: Install Haskell dependencies 42 | run: | 43 | stack build --system-ghc --test --bench --no-run-tests --no-run-benchmarks --only-dependencies 44 | 45 | - name: Build 46 | run: | 47 | stack build --system-ghc --test --bench --no-run-tests --no-run-benchmarks 48 | 49 | - name: Test 50 | # Running the tests only on Linux should suffice 51 | if: ${{ matrix.os == 'ubuntu-latest' }} 52 | run: | 53 | stack test --system-ghc 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /dist/ 2 | /dist-newstyle/ 3 | *.hi 4 | *.o 5 | *.p_hi 6 | *.p_o 7 | *.dyn_hi 8 | *.dyn_o 9 | *.i_o 10 | *.i_hi 11 | .stack-work/ 12 | /stack.yaml.lock 13 | tags 14 | .ghcid 15 | .vscode/ 16 | .envrc 17 | .DS_Store 18 | -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | ## 1.1.0 / 2024.09.20 2 | 3 | * `--split-markers` option to help users split large conflicts to smaller parts 4 | * `--lines-added-around` option to auto-resolve conflicts of line added from different sides 5 | * Command-line options are are also parsed from the `GIT_MEDIATE_OPTIONS` environment variables 6 | * Can disable auto-resolution with the `--no-trivial`, `--no-reduce`, and `--no-line-endings` flags 7 | * Improved `--editor` support for VS Code and Xcode 8 | * Fixed handling of filenames containing spaces and special characters 9 | 10 | ## 1.0.9 / 2023.07.25 11 | 12 | * Do not warn when git is set to use `zdiff3` conflict style 13 | * Resolve line ending conventions changes (i.e changes from Unix/Windows line endings) 14 | * Preserve file modes when resolving conflicts (i.e executable scripts remain executable) 15 | * Handle changes in `git status` formatting for files in spaces in their names 16 | * `--context` option for `-d` mode to control size of context shown around diff 17 | * Fixed parsing of conflicts with nested recursive conflicts 18 | * `--editor` goes to the location of the first conflict in the file 19 | 20 | ## 1.0.8.1 / 2020.10.13 21 | 22 | * First release on Debian (entered Debian unstable at 2023.07.20) 23 | * Build maintenance (anti-bitrot) 24 | 25 | ## 1.0.6 / 2020.01.07 26 | 27 | * `--merge-file` option to merge specific file, even if file is not marked as conflicted 28 | * Reduce add/add conflicts with matching prefix/suffix lines 29 | * Add support for `--untabify` 30 | 31 | ## 1.0.5 / 2018.07.24 32 | 33 | * Windows compatibility fixes 34 | 35 | ## 1.0.1 / 2018.07.24 36 | 37 | * Conflict headers for `-d` option (i.e "### Conflict 3 of 7") 38 | * Improved error message when not running inside a git repository 39 | 40 | ## 1.0 / 2016.12.20 41 | 42 | * Renamed to `git-mediate` 43 | * First release on Hackage 44 | * Add `--version` flag 45 | 46 | ## 0.3.2.4 / 2016.12.20 47 | 48 | * Reduce conflicts when first or last lines match in all parts 49 | 50 | ## 0.3.2.1 / 2015.12.25 51 | 52 | * `--diff2` option to dump diffs in `diff2` format 53 | * Fix bug in modify/delete conflicts when not running from the repo's root 54 | 55 | ## 0.3.1.2 / 2015.09.20 56 | 57 | * Better error reporting for conflict parsing errors 58 | 59 | ## 0.3.1.1 / 2015.09.01 60 | 61 | * Support modify/delete conflicts 62 | 63 | ## 0.3.0.3 / 2015.08.16 64 | 65 | * `-d` option also prints the diffs markers 66 | * Support add/add conflicts 67 | * Fixed bug with submodule conflicts 68 | 69 | ## 0.3.0.1 / 2015.06.06 70 | 71 | * Detect git using `diff2` conflict style and add `-s` option to switch to `diff3` style 72 | * Fixed bug with filenames containing spaces 73 | 74 | ## 0.2.0.2 / 2015.02.03 75 | 76 | * Support for terminals without color 77 | 78 | ## 0.2.0.1 / 2015.01.12 79 | 80 | * Don't keep `.bk` backups files for content before resolution 81 | 82 | ## 0.2 / 2014.12.18 83 | 84 | * `-d` option for displaying the remaining conflicts 85 | 86 | ## 0.1.0.1 / 2014.12.10 87 | 88 | * Conflict also resolves if both sides match (regardless of base also matching) 89 | 90 | ## Development started / 2014.12.1 91 | 92 | * Tool developed started originally as "resolve-trivial-conflicts" 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # git-mediate [![Hackage version](https://img.shields.io/hackage/v/git-mediate.svg?label=Hackage)](https://hackage.haskell.org/package/git-mediate) [![homebrew](https://img.shields.io/homebrew/v/git-mediate.svg)](https://formulae.brew.sh/formula/git-mediate) 2 | 3 | ## Introduction 4 | 5 | Handling conflicts is difficult! 6 | 7 | One useful way to handle them, is to use git's diff3 conflict style: 8 | 9 | ```shell 10 | git config --global merge.conflictstyle diff3 11 | ``` 12 | 13 | And then when you get a conflict, it looks like: 14 | 15 | Unconflicted stuff 16 | 17 | <<<<<<< HEAD 18 | Version A changes 19 | ||||||| 20 | Base version 21 | ======= Version B 22 | Version B changes 23 | >>>>>>> 24 | 25 | More unconflicted stuff here 26 | 27 | Then you are supposed to manually merge the useful changes in the top and bottom parts, relative to the base version. 28 | 29 | A useful way to do this is to figure out which of the changes (Version A or Version B) is a simpler change. 30 | 31 | Perhaps one of the versions just added a small comment above the code section: 32 | 33 | Unconflicted stuff 34 | 35 | <<<<<<< HEAD 36 | Added a comment here 37 | BASE 38 | ||||||| 39 | BASE 40 | ======= Version B 41 | BASE and complex changes here 42 | >>>>>>> 43 | 44 | More unconflicted stuff here 45 | 46 | One easy thing to do, mechanically, is to apply the simple change to 47 | the other 2 versions. Thus, it becomes: 48 | 49 | Unconflicted stuff 50 | 51 | <<<<<<< HEAD 52 | Added a comment here 53 | BASE 54 | ||||||| 55 | Added a comment here 56 | BASE 57 | ======= Version B 58 | Added a comment here 59 | BASE and complex changes here 60 | >>>>>>> 61 | 62 | More unconflicted stuff here 63 | 64 | Now, you can run this little utility: git-mediate, which will see 65 | the conflict has become trivial (only one side changed anything) and 66 | select that side appropriately. 67 | 68 | When all conflicts have been resolved in a file, "git add" will be 69 | used on it automatically. 70 | 71 | ### Simpler case 72 | 73 | You might just resolve the conflicts manually and remove the merge markers from all of the conflicts. 74 | 75 | In such a case, just run git-mediate, and it will "git add" the 76 | file for you. 77 | 78 | ## Installation 79 | 80 | ### Using package managers 81 | 82 | * macOS: `brew install git-mediate` 83 | * Linux (debian): `apt-get install git-mediate` 84 | 85 | ### Using haskell-stack 86 | 87 | 1. Install [haskell stack](https://docs.haskellstack.org/en/stable/) 88 | 2. Run: `stack install git-mediate` 89 | 90 | ### From sources 91 | 92 | Clone it: 93 | 94 | git clone https://github.com/Peaker/git-mediate 95 | cd git-mediate 96 | 97 | Option #1: Build & install using stack: `stack install` (make sure you installed [haskell stack](https://docs.haskellstack.org/en/stable/)) 98 | 99 | Option #2: Build & install using cabal: `cabal install` (make sure `~/.cabal/bin` is in your `$PATH`) 100 | 101 | ## Use 102 | 103 | Call the git-mediate from a git repository with conflicts. 104 | 105 | ## Additional features 106 | 107 | ### Open editor 108 | 109 | You can use the `-e` flag to invoke your `$EDITOR` on every conflicted file that could not be automatically resolved. 110 | 111 | ### Show conflict diffs 112 | 113 | Sometimes, the conflict is just a giant block of incomprehensible text next to another giant block of incomprehensible text. 114 | 115 | You can use the `-d` flag to show the conflict in diff-from-base form. Then, you can manually apply the changes you see in both the base and wherever needed, and use git-mediate again to make sure you've updated everything appropriately. 116 | 117 | ## License 118 | 119 | Copyright (C) 2014-2024 Eyal Lotem 120 | 121 | This program is free software; you can redistribute it and/or modify 122 | it under the terms of the GNU General Public License as published by 123 | the Free Software Foundation; version 2 of the License only. 124 | 125 | This program is distributed in the hope that it will be useful, 126 | but WITHOUT ANY WARRANTY; without even the implied warranty of 127 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 128 | GNU General Public License for more details. 129 | 130 | You should have received a copy of the GNU General Public License 131 | along with this program. If not, see . 132 | -------------------------------------------------------------------------------- /git-mediate.cabal: -------------------------------------------------------------------------------- 1 | -- Initial git-mediate.cabal generated by cabal init. For 2 | -- further documentation, see https://cabal.readthedocs.io/ 3 | 4 | name: git-mediate 5 | version: 1.1.0 6 | synopsis: Tool to help resolving git conflicts 7 | description: Git conflict resolution has never been easier 8 | . 9 | When encountering a conflict, you can sometimes 10 | imagine: if only I could have applied one of 11 | these patches BEFORE the other rather than 12 | concurrently, I wouldn't be in this mess! 13 | . 14 | Well, with git-mediate, you can! 15 | . 16 | 17 | In any conflicted state - git-mediate shows you 18 | the 2 diffs involved. By applying these diffs to 19 | the base version and the other version, you 20 | emulate the situation where the patch had already 21 | existed when the other had been applied. 22 | . 23 | Reapply git-mediate, it will validate that you've 24 | indeed applied it correctly, and bam: conflict 25 | disappeared! 26 | . 27 | Git-mediate also lets you handle modify/delete 28 | conflicts (there's no sane way in git to show 29 | what the modification actually was) 30 | . 31 | Git-mediate also streamlines jumping to the 32 | conflicts with your editor, either with the `-e` 33 | option to invoke your editor, or via the standard 34 | line number format, which is parsed by all major 35 | editors, to allow use of "jump to next error" 36 | keys. 37 | . 38 | Git-mediate especially shines with automatic 39 | source transformation tools such as renamers. 40 | . 41 | In a conflicted state, re-apply a rename that 42 | caused the conflict, run git-mediate without 43 | opening any files, and the conflicts are gone! 44 | 45 | homepage: https://github.com/Peaker/git-mediate 46 | license: GPL-2 47 | license-file: LICENSE 48 | author: Eyal Lotem 49 | maintainer: eyal.lotem@gmail.com 50 | -- copyright: 51 | category: Development 52 | build-type: Simple 53 | extra-source-files: stack.yaml 54 | ChangeLog.md 55 | README.md 56 | cabal-version: >=1.10 57 | 58 | source-repository head 59 | type: git 60 | location: https://github.com/Peaker/git-mediate 61 | 62 | executable git-mediate 63 | main-is: Main.hs 64 | other-modules: Conflict 65 | , Environment 66 | , Git 67 | , Opts 68 | , OptUtils 69 | , PPDiff 70 | , Resolution 71 | , ResolutionOpts 72 | , SideDiff 73 | , StrUtils 74 | , Version 75 | , Paths_git_mediate 76 | ghc-options: -O2 -Wall 77 | -- other-extensions: 78 | build-depends: base >=4.16 && <5 79 | , base-compat >= 0.8.2 80 | , containers 81 | , mtl >=2.1 82 | , directory >=1.2 83 | , process >=1.2 84 | , filepath >=1.3 85 | , unix-compat >=0.4.2.0 86 | , Diff >=0.4 87 | , ansi-terminal >=0.6.2 88 | , optparse-applicative >=0.11 89 | , generic-data >=0.8.2 90 | , split 91 | hs-source-dirs: src 92 | default-language: Haskell2010 93 | -------------------------------------------------------------------------------- /src/Conflict.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleContexts, NoImplicitPrelude, DeriveTraversable, NamedFieldPuns #-} 2 | {-# LANGUAGE DerivingVia, DeriveGeneric, OverloadedRecordDot, LambdaCase #-} 3 | 4 | module Conflict 5 | ( Conflict(..), Sides(..), SrcContent(..) 6 | , setEachBody, setStrings 7 | , pretty, prettyLines 8 | , parse 9 | ) where 10 | 11 | import Control.Monad.State (MonadState, evalStateT, state) 12 | import Control.Monad.Writer (runWriter, tell) 13 | import Data.Maybe (fromMaybe) 14 | import GHC.Generics (Generic1) 15 | import Generic.Data (Generically1(..)) 16 | 17 | import Prelude.Compat 18 | 19 | data Sides a = Sides 20 | { sideA :: a 21 | , sideBase :: a 22 | , sideB :: a 23 | } 24 | deriving (Functor, Foldable, Traversable, Show, Eq, Ord, Generic1) 25 | deriving (Applicative) via Generically1 Sides 26 | 27 | data SrcContent = SrcContent 28 | { lineNo :: Int 29 | , content :: String 30 | } 31 | deriving (Show) 32 | 33 | data Conflict = Conflict 34 | { markers :: Sides SrcContent -- The markers at the beginning of sections 35 | , markerEnd :: SrcContent -- The ">>>>>>>...." marker at the end of the conflict 36 | , bodies :: Sides [String] 37 | } 38 | deriving (Show) 39 | 40 | setBodies :: (Sides [String] -> Sides [String]) -> Conflict -> Conflict 41 | setBodies f c = c{bodies = f c.bodies} 42 | 43 | setEachBody :: ([String] -> [String]) -> Conflict -> Conflict 44 | setEachBody = setBodies . fmap 45 | 46 | setStrings :: (String -> String) -> Conflict -> Conflict 47 | setStrings = setEachBody . map 48 | 49 | prettyLines :: Conflict -> [String] 50 | prettyLines c = 51 | concat ((:) . content <$> c.markers <*> c.bodies) <> [c.markerEnd.content] 52 | 53 | pretty :: Conflict -> String 54 | pretty = unlines . prettyLines 55 | 56 | breakUpToMarker :: 57 | MonadState [SrcContent] m => 58 | Char -> Maybe Int -> m [SrcContent] 59 | breakUpToMarker c mCount = 60 | state (break cond) 61 | where 62 | count = fromMaybe 7 mCount 63 | prefix = replicate count c 64 | cond l = 65 | pre == prefix && rightCount 66 | where 67 | (pre, post) = splitAt count l.content 68 | rightCount = 69 | case (mCount, post) of 70 | (Just{}, x:_) -> c /= x 71 | _ -> True 72 | 73 | readHead :: MonadState [a] m => m (Maybe a) 74 | readHead = state f 75 | where 76 | f [] = (Nothing, []) 77 | f (l:ls) = (Just l, ls) 78 | 79 | tryReadUpToMarker :: 80 | MonadState [SrcContent] m => 81 | Char -> Maybe Int -> m ([SrcContent], Maybe SrcContent) 82 | tryReadUpToMarker c mCount = 83 | (,) <$> breakUpToMarker c mCount <*> readHead 84 | 85 | readUpToMarker :: 86 | MonadState [SrcContent] m => 87 | Char -> Maybe Int -> m ([SrcContent], SrcContent) 88 | readUpToMarker c mCount = 89 | tryReadUpToMarker c mCount >>= 90 | \case 91 | (ls, Just h) -> pure (ls, h) 92 | (ls, Nothing) -> 93 | error $ concat 94 | [ "Parse error: failed reading up to marker: " 95 | , show c, ", got:" 96 | , concatMap (\l -> "\n" ++ show l.lineNo ++ "\t" ++ l.content) $ take 5 ls 97 | ] 98 | 99 | parseConflict :: MonadState [SrcContent] m => SrcContent -> m Conflict 100 | parseConflict markerA = 101 | do 102 | (linesA, markerBase) <- readUpToMarker '|' markerCount 103 | (linesBase, markerB) <- readUpToMarker '=' markerCount 104 | (linesB , markerEnd) <- readUpToMarker '>' markerCount 105 | pure Conflict 106 | { markers = Sides markerA markerBase markerB 107 | , markerEnd 108 | , bodies = fmap (.content) <$> Sides linesA linesBase linesB 109 | } 110 | where 111 | markerCount = Just (length (takeWhile (== '<') markerA.content)) 112 | 113 | parseFromNumberedLines :: [SrcContent] -> [Either String Conflict] 114 | parseFromNumberedLines = 115 | snd . runWriter . evalStateT loop 116 | where 117 | loop = 118 | do 119 | (ls, mMarkerA) <- tryReadUpToMarker '<' Nothing 120 | tell $ map (Left . (.content)) ls 121 | case mMarkerA of 122 | Nothing -> pure () 123 | Just markerA -> 124 | do 125 | tell . pure . Right =<< parseConflict markerA 126 | loop 127 | 128 | parse :: String -> [Either String Conflict] 129 | parse = parseFromNumberedLines . zipWith SrcContent [1 ..] . lines 130 | -------------------------------------------------------------------------------- /src/Environment.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE NoImplicitPrelude, OverloadedRecordDot #-} 2 | 3 | module Environment 4 | ( checkConflictStyle, shouldUseColorByTerminal, openEditor 5 | ) where 6 | 7 | import qualified Control.Exception as E 8 | import Control.Monad (when, unless) 9 | import Data.Functor ((<&>)) 10 | import Opts (Options(..)) 11 | import PPDiff (ColorEnable(..)) 12 | import StrUtils (stripNewline) 13 | import System.Console.ANSI (hSupportsANSI) 14 | import System.IO (stdout) 15 | import System.Environment (getEnv) 16 | import System.Exit (ExitCode(..)) 17 | import System.Process (callProcess, readProcessWithExitCode) 18 | 19 | import Prelude.Compat 20 | 21 | shouldUseColorByTerminal :: IO ColorEnable 22 | shouldUseColorByTerminal = 23 | hSupportsANSI stdout 24 | <&> \istty -> if istty then EnableColor else DisableColor 25 | 26 | getConflictStyle :: IO String 27 | getConflictStyle = 28 | do 29 | (exitCode, output, _) <- readProcessWithExitCode "git" ["config", "merge.conflictstyle"] stdin 30 | case exitCode of 31 | ExitSuccess -> pure $ stripNewline output 32 | ExitFailure 1 -> pure "unset" 33 | ExitFailure _ -> E.throwIO exitCode 34 | where 35 | stdin = "" 36 | 37 | setConflictStyle :: IO () 38 | setConflictStyle = 39 | callProcess "git" ["config", "--global", "merge.conflictstyle", "diff3"] 40 | 41 | checkConflictStyle :: Options -> IO () 42 | checkConflictStyle opts = 43 | do 44 | conflictStyle <- getConflictStyle 45 | unless (conflictStyle `elem` ["diff3", "zdiff3"]) $ 46 | do 47 | unless opts.shouldSetConflictStyle $ 48 | fail $ concat 49 | [ "merge.conflictstyle must be diff3 but is " 50 | , show conflictStyle 51 | , ". Use -s to automatically set it globally" 52 | ] 53 | setConflictStyle 54 | 55 | newConflictStyle <- getConflictStyle 56 | when (newConflictStyle /= "diff3") $ 57 | fail $ concat 58 | [ "Attempt to set conflict style failed. Perhaps you have" 59 | , " an incorrect merge.conflictstyle configuration " 60 | , "specified in your per-project .git/config?" 61 | ] 62 | 63 | openEditor :: Options -> FilePath -> Int -> IO () 64 | openEditor opts path lineNo 65 | | opts.shouldUseEditor = 66 | do 67 | editor <- getEnv "EDITOR" 68 | let cmdOpts = 69 | case editor of 70 | "code" -> ["--goto", path <> ":" <> show lineNo] 71 | "xed" -> ["-l", show lineNo, path] 72 | _ -> ["+" <> show lineNo, path] 73 | callProcess editor cmdOpts 74 | | otherwise = pure () 75 | -------------------------------------------------------------------------------- /src/Git.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE NoImplicitPrelude, OverloadedRecordDot #-} 2 | 3 | module Git 4 | ( StatusLine(..), StatusCode, getStatus, getRootDir, getCdUp, add 5 | , makeFilesMatchingPrefixes 6 | ) where 7 | 8 | import Control.Monad (when, filterM) 9 | import Data.Foldable (asum) 10 | import Data.List.Split (splitOn) 11 | import Data.Maybe (mapMaybe) 12 | import StrUtils ((), stripNewline) 13 | import System.Directory (getCurrentDirectory) 14 | import System.Exit (ExitCode(..), exitWith) 15 | import System.FilePath (makeRelative, joinPath, splitPath) 16 | import System.IO (hPutStr, stderr) 17 | import qualified System.PosixCompat.Files as PosixFiles 18 | import System.Process (callProcess, readProcess, readProcessWithExitCode) 19 | 20 | import Prelude.Compat 21 | 22 | type StatusCode = (Char, Char) 23 | 24 | data StatusLine = StatusLine 25 | { statusCode :: StatusCode 26 | , statusArgs :: String 27 | } 28 | 29 | parseStatusZ :: [String] -> Either String [StatusLine] 30 | parseStatusZ [""] = Right [] 31 | parseStatusZ (('R':' ':dst):_src:rest) = 32 | -- We don't currently do anything with rename statuses so _src is ignored 33 | (StatusLine ('R', ' ') dst :) <$> parseStatusZ rest 34 | -- TODO: Which other statuses have two fields? 35 | parseStatusZ ((x:y:' ':arg):rest) = (StatusLine (x, y) arg :) <$> parseStatusZ rest 36 | parseStatusZ part = Left ("Cannot parse status -z part: " <> show part) 37 | 38 | getStatus :: IO [StatusLine] 39 | getStatus = 40 | do 41 | (resCode, statusZ, statusStderr) <- 42 | readProcessWithExitCode "git" ["status", "-z"] "" 43 | when (resCode /= ExitSuccess) $ do 44 | -- Print git's error message. Usually - 45 | -- "fatal: Not a git repository (or any of the parent directories): .git" 46 | hPutStr stderr statusStderr 47 | exitWith resCode 48 | case parseStatusZ $ splitOn "\0" statusZ of 49 | Right res -> pure res 50 | Left err -> 51 | do 52 | hPutStr stderr err 53 | exitWith (ExitFailure 1) 54 | 55 | getRootDir :: IO FilePath 56 | getRootDir = 57 | do 58 | cwd <- getCurrentDirectory 59 | relativePath cwd . stripNewline 60 | <$> readProcess "git" ["rev-parse", "--show-toplevel"] "" 61 | 62 | relativePath :: FilePath -> FilePath -> FilePath 63 | relativePath base path 64 | | rel /= path = rel 65 | | revRel /= base = 66 | joinPath $ replicate (length (splitPath revRel)) ".." 67 | | otherwise = path 68 | where 69 | rel = makeRelative base path 70 | revRel = makeRelative path base 71 | 72 | add :: FilePath -> IO () 73 | add fileName = callProcess "git" ["add", "--", fileName] 74 | 75 | -- TODO: Is this different from getRootDir? 76 | getCdUp :: IO FilePath 77 | getCdUp = takeWhile (/= '\0') . stripNewline <$> readProcess "git" ["rev-parse", "--show-cdup"] "" 78 | 79 | makeFilesMatchingPrefixes :: IO ([Git.StatusCode] -> IO [FilePath]) 80 | makeFilesMatchingPrefixes = 81 | do 82 | statusPorcelain <- Git.getStatus 83 | rootDir <- Git.getRootDir 84 | let rootRelativeFiles = 85 | filterM (fmap not . isDirectory) . map (rootDir ) 86 | let decode x = 87 | case reads x of 88 | [(r, "")] -> r 89 | _ -> x 90 | let firstMatchingStatus :: [Git.StatusCode] -> Git.StatusLine -> Maybe String 91 | firstMatchingStatus statuses = 92 | fmap decode . asum . traverse matchStatus statuses 93 | let filesMatchingStatuses :: [Git.StatusCode] -> IO [FilePath] 94 | filesMatchingStatuses statuses = 95 | rootRelativeFiles . mapMaybe (firstMatchingStatus statuses) 96 | $ statusPorcelain 97 | pure filesMatchingStatuses 98 | 99 | matchStatus :: Git.StatusCode -> Git.StatusLine -> Maybe String 100 | matchStatus code line 101 | | line.statusCode == code = Just line.statusArgs 102 | | otherwise = Nothing 103 | 104 | isDirectory :: FilePath -> IO Bool 105 | isDirectory x = PosixFiles.isDirectory <$> PosixFiles.getFileStatus x 106 | -------------------------------------------------------------------------------- /src/Main.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE NoImplicitPrelude, OverloadedRecordDot, FlexibleContexts #-} 2 | 3 | module Main (main) where 4 | 5 | import Conflict (Conflict(..)) 6 | import qualified Conflict 7 | import qualified Control.Exception as E 8 | import Control.Monad (when, unless) 9 | import Data.Algorithm.Diff (Diff, PolyDiff(..)) 10 | import Data.Either (rights) 11 | import Data.Foldable (traverse_) 12 | import Data.List (isPrefixOf) 13 | import Environment (checkConflictStyle, openEditor, shouldUseColorByTerminal) 14 | import qualified Git 15 | import qualified Opts 16 | import Opts (Options(..)) 17 | import PPDiff (ppDiff, ColorEnable(..)) 18 | import Resolution (Result(..), NewContent(..)) 19 | import qualified Resolution 20 | import qualified ResolutionOpts 21 | import SideDiff (SideDiff(..), getConflictDiffs, getConflictDiff2s) 22 | import StrUtils ((), ensureNewline) 23 | import System.Directory (renameFile, removeFile, getPermissions, setPermissions) 24 | import System.Exit (ExitCode(..), exitWith) 25 | import System.FilePath ((<.>)) 26 | import System.Process (callProcess, readProcess) 27 | 28 | import Prelude.Compat 29 | 30 | -- '>' -> ">>>>>>>" 31 | markerPrefix :: Char -> String 32 | markerPrefix = replicate 7 33 | 34 | markerLine :: Char -> String -> String 35 | markerLine c str = markerPrefix c ++ " " ++ str ++ "\n" 36 | 37 | trimDiff :: Int -> [Diff a] -> [Diff a] 38 | trimDiff contextLen = 39 | reverse . f . reverse . f 40 | where 41 | f l = drop (length (takeWhile both l) - contextLen) l 42 | both Both{} = True 43 | both _ = False 44 | 45 | dumpDiffs :: ColorEnable -> Options -> FilePath -> Int -> (Int, Conflict) -> IO () 46 | dumpDiffs colorEnable opts filePath count (idx, conflict) = 47 | do 48 | putStrLn $ unwords ["### Conflict", show idx, "of", show count] 49 | when opts.shouldDumpDiffs $ traverse_ dumpDiff $ getConflictDiffs conflict 50 | when opts.shouldDumpDiff2 $ dumpDiff2 $ getConflictDiff2s conflict 51 | where 52 | dumpDiff d = 53 | do 54 | putStrLn $ concat 55 | [filePath, ":", show d.marker.lineNo, ":Diff", show d.side, ": ", d.marker.content] 56 | putStr $ unlines $ map (ppDiff colorEnable) (trimDiff opts.envOptions.diffsContext d.diff) 57 | dumpDiff2 (markerA, markerB, d) = 58 | do 59 | putStrLn $ concat [filePath, ":", show markerA.lineNo, " <->", markerA.content] 60 | putStrLn $ concat [filePath, ":", show markerB.lineNo, ": ", markerB.content] 61 | putStr $ unlines $ map (ppDiff colorEnable) d 62 | 63 | dumpAndOpenEditor :: ColorEnable -> Options -> FilePath -> [Conflict] -> IO () 64 | dumpAndOpenEditor colorEnable opts path conflicts = 65 | do 66 | when (opts.shouldDumpDiffs || opts.shouldDumpDiff2) $ 67 | traverse_ (dumpDiffs colorEnable opts path (length conflicts)) (zip [1 ..] conflicts) 68 | case conflicts of 69 | [] -> pure () 70 | c:_ -> openEditor opts path ((Conflict.lineNo . Conflict.sideA . markers) c) 71 | 72 | overwrite :: FilePath -> String -> IO () 73 | overwrite fileName content = 74 | do 75 | oldPermissions <- getPermissions fileName 76 | renameFile fileName bkup 77 | writeFile fileName content 78 | setPermissions fileName oldPermissions 79 | removeFile bkup 80 | where 81 | bkup = fileName <.> "bk" 82 | 83 | handleFileResult :: ColorEnable -> Options -> FilePath -> NewContent -> IO () 84 | handleFileResult colorEnable opts fileName res 85 | | successes == 0 && allGood = 86 | do 87 | putStrLn $ fileName ++ ": No conflicts, git-adding" 88 | Git.add fileName 89 | | successes == 0 && reductions == 0 = 90 | do 91 | putStrLn $ concat 92 | [ fileName 93 | , if ResolutionOpts.isResolving opts.envOptions.resolution 94 | then ": Failed to resolve any of the " else ": " 95 | , show failures 96 | , " conflicts" 97 | ] 98 | doDump 99 | | successes == 0 = 100 | do 101 | putStrLn $ concat 102 | [fileName, ": Reduced ", show reductions, " conflicts"] 103 | overwrite fileName res.newContent 104 | doDump 105 | | otherwise = 106 | do 107 | putStrLn $ concat 108 | [ fileName, ": Successfully resolved ", show successes 109 | , " conflicts (failed to resolve ", show (reductions + failures), " conflicts)" 110 | , if allGood then ", git adding" else "" 111 | ] 112 | overwrite fileName res.newContent 113 | if allGood 114 | then Git.add fileName 115 | else doDump 116 | where 117 | allGood = Resolution.fullySuccessful res.result 118 | doDump = 119 | dumpAndOpenEditor colorEnable opts fileName 120 | (rights (Conflict.parse res.newContent)) 121 | Result 122 | { resolvedSuccessfully = successes 123 | , reducedConflicts = reductions 124 | , failedToResolve = failures 125 | } = res.result 126 | 127 | resolve :: ColorEnable -> Options -> FilePath -> IO Result 128 | resolve colorEnable opts fileName = 129 | do 130 | resolutions <- 131 | Resolution.resolveContent opts.envOptions.resolution 132 | . Conflict.parse 133 | <$> readFile fileName 134 | resolutions.result <$ handleFileResult colorEnable opts fileName resolutions 135 | 136 | withAllStageFiles :: 137 | FilePath -> (FilePath -> Maybe FilePath -> Maybe FilePath -> IO b) -> IO b 138 | withAllStageFiles path action = 139 | do 140 | [baseTmpRaw, localTmpRaw, remoteTmpRaw] <- 141 | take 3 . words 142 | <$> readProcess "git" ["checkout-index", "--stage=all", "--", path] "" 143 | cdup <- Git.getCdUp 144 | let maybePath "." = Nothing 145 | maybePath p = Just (cdup p) 146 | let mLocalTmp = maybePath localTmpRaw 147 | mRemoteTmp = maybePath remoteTmpRaw 148 | baseTmp = cdup baseTmpRaw 149 | action baseTmp mLocalTmp mRemoteTmp 150 | `E.finally` do 151 | removeFile baseTmp 152 | traverse_ removeFile mLocalTmp 153 | traverse_ removeFile mRemoteTmp 154 | 155 | deleteModifyConflictAddMarkers :: FilePath -> IO () 156 | deleteModifyConflictAddMarkers path = 157 | withAllStageFiles path $ \baseTmp mLocalTmp mRemoteTmp -> 158 | do 159 | baseContent <- readFile baseTmp 160 | localContent <- foldMap readFile mLocalTmp 161 | remoteContent <- foldMap readFile mRemoteTmp 162 | overwrite path $ 163 | concat 164 | [ markerLine '<' "LOCAL" 165 | , ensureNewline localContent 166 | , markerLine '|' "BASE" 167 | , ensureNewline baseContent 168 | , markerLine '=' "" 169 | , ensureNewline remoteContent 170 | , markerLine '>' "REMOTE" 171 | ] 172 | 173 | deleteModifyConflictHandle :: FilePath -> IO () 174 | deleteModifyConflictHandle path = 175 | do 176 | marked <- 177 | any (markerPrefix '<' `isPrefixOf`) . lines <$> readFile path 178 | unless marked $ 179 | do 180 | putStrLn $ show path ++ " has a delete/modify conflict. Adding conflict markers" 181 | deleteModifyConflictAddMarkers path 182 | 183 | removeFileIfEmpty :: FilePath -> IO () 184 | removeFileIfEmpty path = 185 | do 186 | isEmpty <- null <$> readFile path 187 | when isEmpty $ 188 | do 189 | removeFile path 190 | callProcess "git" ["add", "-u", "--", path] 191 | 192 | statusCodes :: Char -> Char -> [Git.StatusCode] 193 | statusCodes x y 194 | | x == y = [(x, y)] 195 | | otherwise = [(x, y), (y, x)] 196 | 197 | mediateAll :: ColorEnable -> Options -> IO Result 198 | mediateAll colorEnable opts = 199 | do 200 | filesMatchingPrefixes <- Git.makeFilesMatchingPrefixes 201 | 202 | -- from git-diff manpage: 203 | -- Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), 204 | -- have their type (i.e. regular file, symlink, submodule, ...) changed (T), 205 | -- are Unmerged (U), are Unknown (X), or have had their pairing Broken (B) 206 | 207 | deleteModifyConflicts <- filesMatchingPrefixes (statusCodes 'D' 'U') 208 | 209 | traverse_ deleteModifyConflictHandle deleteModifyConflicts 210 | 211 | res <- 212 | filesMatchingPrefixes 213 | ([('U', 'U'), ('A', 'A'), ('D', 'A'), ('D', 'U')] >>= uncurry statusCodes) 214 | >>= foldMap (resolve colorEnable opts) 215 | 216 | -- Heuristically delete files that were remove/modify conflict 217 | -- and ended up with empty content 218 | traverse_ removeFileIfEmpty deleteModifyConflicts 219 | pure res 220 | 221 | exitCodeOf :: Result -> ExitCode 222 | exitCodeOf res 223 | | Resolution.fullySuccessful res = ExitSuccess 224 | | otherwise = ExitFailure 111 225 | 226 | exitProcess :: Result -> IO () 227 | exitProcess = exitWith . exitCodeOf 228 | 229 | main :: IO () 230 | main = 231 | do 232 | opts <- Opts.getOpts 233 | colorEnable <- maybe shouldUseColorByTerminal pure opts.shouldUseColor 234 | checkConflictStyle opts 235 | case opts.mergeSpecificFile of 236 | Nothing -> mediateAll colorEnable opts 237 | Just path -> resolve colorEnable opts path 238 | >>= exitProcess 239 | -------------------------------------------------------------------------------- /src/OptUtils.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedRecordDot, LambdaCase, FlexibleContexts #-} 2 | 3 | module OptUtils 4 | ( Parser, parseEnvOptions, envSwitch, envOptional, envOption 5 | ) where 6 | 7 | import Control.Applicative ((<|>)) 8 | import Control.Monad ((>=>), guard, unless) 9 | import Control.Monad.Reader 10 | import Control.Monad.State 11 | import Data.Foldable (traverse_) 12 | import Data.Functor.Compose (Compose(..)) 13 | import qualified Data.Map as M 14 | import Data.Maybe (catMaybes) 15 | import qualified Data.Set as S 16 | import qualified Options.Applicative as O 17 | import System.Environment (lookupEnv) 18 | import Text.Read.Compat (readMaybe) 19 | 20 | type Parser = Compose (ReaderT EnvVarName (State EnvContent)) O.Parser 21 | 22 | type EnvVarName = String 23 | 24 | data EnvContent = EnvContent 25 | { flags :: S.Set String 26 | , options :: M.Map String String 27 | , errors :: [String] 28 | } 29 | 30 | instance Semigroup EnvContent where 31 | EnvContent f0 o0 e0 <> EnvContent f1 o1 e1 = 32 | EnvContent (f0 <> f1) (o0 <> o1) 33 | ( e0 <> e1 34 | <> (("Duplicate flag: " <>) <$> S.toList (S.intersection f0 f1)) 35 | <> (("Duplicate option: " <>) <$> M.keys (M.intersection o0 o1)) 36 | ) 37 | 38 | instance Monoid EnvContent where 39 | mempty = EnvContent mempty mempty mempty 40 | 41 | parseEnvOptions :: String -> Parser a -> IO (O.Parser a) 42 | parseEnvOptions name (Compose parser) = 43 | do 44 | envOpts <- foldMap (parseEnv . words) <$> lookupEnv name 45 | let (result, remainder) = runState (runReaderT parser name) envOpts 46 | let errFmt = formatRemainder remainder 47 | result <$ 48 | unless (null errFmt) 49 | (putStrLn (unlines 50 | (("Warning: unhandled options in " <> name <> ":") : ((" * " <>) <$> errFmt)))) 51 | 52 | formatRemainder :: EnvContent -> [String] 53 | formatRemainder (EnvContent f o e) = 54 | (("Unrecognized flag --" <>) <$> S.toList f) 55 | <> M.foldMapWithKey (\k v -> ["Unrecognized option: --" <> k <> " " <> v]) o 56 | <> e 57 | 58 | parseEnv :: [String] -> EnvContent 59 | parseEnv [] = mempty 60 | parseEnv (('-':'-':flag@(_:_)):rest) = parseEnvFlag flag rest 61 | parseEnv (['-',flag]:rest) = parseEnvFlag [flag] rest 62 | parseEnv (other:rest) = mempty{errors = ["Unknown argument: " <> other]} <> parseEnv rest 63 | 64 | parseEnvFlag :: String -> [String] -> EnvContent 65 | parseEnvFlag flag rest = 66 | case rest of 67 | [] -> flagRes 68 | ('-':_):_ -> flagRes <> parseEnv rest 69 | val:rest' -> mempty{options = M.singleton flag val} <> parseEnv rest' 70 | where 71 | flagRes = mempty{flags = S.singleton flag} 72 | 73 | -- | A boolean flag which may be initialized by an environment variable. 74 | -- 75 | -- If the flag is present in the environment, 76 | -- the corresponding --no- or -- flag will be available to override it. 77 | envSwitch :: String -> Bool -> String -> Parser Bool 78 | envSwitch name def desc = 79 | Compose $ 80 | do 81 | otherInEnv <- gets (S.member otherMode . flags) 82 | modify (\x -> x{flags = S.delete otherMode x.flags}) 83 | let flag 84 | | otherInEnv = defaultMode 85 | | otherwise = otherMode 86 | let curDef = def /= otherInEnv 87 | let actionHelp 88 | | curDef = "Disable" 89 | | otherwise = "Enable" 90 | extraHelp <- (guard otherInEnv >>) <$> overrideHelp otherMode 91 | let help = actionHelp <> " " <> desc <> extraHelp 92 | pure ((/= curDef) <$> O.switch (O.long flag <> O.help help)) 93 | where 94 | noFlag = "no-" <> name 95 | (defaultMode, otherMode) 96 | | def = (name, noFlag) 97 | | otherwise = (noFlag, name) 98 | 99 | overrideHelp :: MonadReader EnvVarName m => String -> m String 100 | overrideHelp val = asks (\name -> " (override \"--" <> val <> "\" from " <> name <> ")") 101 | 102 | -- | An optional value which may be initialized by an environment variable. 103 | -- 104 | -- If the flag is present in the environment, 105 | -- a corresponding --no- flag will be available to disable it. 106 | envOptional :: (Read a, Show a) => String -> String -> String -> (a -> String) -> Parser (Maybe a) 107 | envOptional name valDesc help disableHelp = 108 | Compose $ 109 | readOption name >>= 110 | \case 111 | Just val -> 112 | do 113 | oh <- overrideHelp (name <> " " <> show val) 114 | ov <- envOptionFromEnv val 115 | opt <- getCompose (envOption name Nothing (commonMods <> ov)) 116 | pure $ 117 | O.optional opt 118 | <|> f <$> O.switch (O.long ("no-" <> name) <> O.help (disableHelp val <> oh)) 119 | where 120 | f True = Nothing 121 | f False = Just val 122 | Nothing -> pure (O.optional (O.option O.auto (O.long name <> commonMods))) 123 | where 124 | commonMods = O.metavar valDesc <> O.help help 125 | 126 | readOption :: (Read a, MonadState EnvContent m) => String -> m (Maybe a) 127 | readOption name = 128 | do 129 | result <- gets (M.lookup name . options >=> readMaybe) 130 | result <$ traverse_ (const (modify (\x -> x{options = M.delete name x.options}))) result 131 | 132 | -- | An option with a default value which may be initialized by an environment variable. 133 | -- 134 | -- (the default value should be specified in the provided @O.Mod@ argument) 135 | envOption :: (Read a, Show a) => String -> Maybe Char -> O.Mod O.OptionFields a -> Parser a 136 | envOption name shortName mods = 137 | Compose $ 138 | traverse readOption ([name] <> maybe [] (pure . pure) shortName) 139 | >>= 140 | \case 141 | [] -> pure (O.option O.auto baseMods) 142 | [val] -> O.option O.auto . (baseMods <>) <$> envOptionFromEnv val 143 | _ -> 144 | O.option O.auto baseMods <$ 145 | modify (\x -> x{errors = x.errors <> ["Both --" <> name <> " and -" <> maybe [] pure shortName <> " specified"]}) 146 | . catMaybes 147 | where 148 | baseMods = O.long name <> foldMap O.short shortName <> mods 149 | 150 | envOptionFromEnv :: (MonadReader EnvVarName m, Show a) => a -> m (O.Mod O.OptionFields a) 151 | envOptionFromEnv val = 152 | asks (\envVar -> O.value val <> O.showDefaultWith (\x -> show x <> ", from " <> envVar)) 153 | -------------------------------------------------------------------------------- /src/Opts.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE LambdaCase #-} 2 | -- | Option parser 3 | 4 | module Opts 5 | ( Options(..), EnvOptions(..) 6 | , getOpts 7 | ) where 8 | 9 | import Control.Applicative (Alternative(..)) 10 | import qualified Options.Applicative as O 11 | import qualified OptUtils 12 | import PPDiff (ColorEnable(..)) 13 | import qualified ResolutionOpts as ResOpts 14 | import System.Exit (exitSuccess) 15 | import Version (versionString) 16 | 17 | data Options = Options 18 | { shouldUseEditor :: Bool 19 | , shouldDumpDiffs :: Bool 20 | , shouldDumpDiff2 :: Bool 21 | , shouldUseColor :: Maybe ColorEnable 22 | , shouldSetConflictStyle :: Bool 23 | , mergeSpecificFile :: Maybe FilePath 24 | , envOptions :: EnvOptions 25 | } 26 | 27 | -- Options which can be defaulted from the GIT_MEDIATE_OPTIONS environment variable 28 | data EnvOptions = EnvOptions 29 | { diffsContext :: Int 30 | , resolution :: ResOpts.ResolutionOptions 31 | } 32 | 33 | optionsParser :: O.Parser EnvOptions -> O.Parser Options 34 | optionsParser envOpts = 35 | Options 36 | <$> O.switch 37 | ( O.long "editor" <> O.short 'e' 38 | <> O.help "Execute $EDITOR for each conflicted file that remains conflicted" 39 | ) 40 | <*> O.switch 41 | ( O.long "diff" <> O.short 'd' 42 | <> O.help "Dump the left/right diffs from base in each conflict remaining" 43 | ) 44 | <*> O.switch 45 | ( O.long "diff2" <> O.short '2' 46 | <> O.help "Dump the diff between left and right in each conflict remaining" 47 | ) 48 | <*> colorParser 49 | <*> O.switch 50 | ( O.long "style" <> O.short 's' 51 | <> O.help "Configure git's global merge.conflictstyle to diff3 if needed" 52 | ) 53 | <*> O.optional 54 | ( O.strOption 55 | ( O.long "merge-file" <> O.short 'f' <> O.help "Merge a specific file") 56 | ) 57 | <*> envOpts 58 | where 59 | colorParser = 60 | O.flag' (Just EnableColor) 61 | (O.long "color" <> O.short 'c' <> O.help "Enable color") 62 | <|> O.flag' (Just DisableColor) 63 | (O.long "no-color" <> O.short 'C' <> O.help "Disable color") 64 | <|> pure Nothing 65 | 66 | envOptsParser :: OptUtils.Parser EnvOptions 67 | envOptsParser = 68 | EnvOptions 69 | <$> OptUtils.envOption "context" (Just 'U') 70 | ( O.metavar "LINECOUNT" <> O.showDefault <> O.value 3 71 | <> O.help "Number of context lines around dumped diffs" 72 | ) 73 | <*> ResOpts.parser 74 | 75 | data CmdArgs = CmdVersion | CmdOptions Options 76 | 77 | parser :: O.Parser EnvOptions -> O.Parser CmdArgs 78 | parser envOpts = 79 | O.flag' CmdVersion (O.long "version" <> O.help "Print the version and quit") 80 | <|> CmdOptions <$> optionsParser envOpts 81 | 82 | opts :: O.Parser EnvOptions -> O.ParserInfo CmdArgs 83 | opts envOpts = 84 | O.info (O.helper <*> parser envOpts) $ 85 | O.fullDesc 86 | <> O.progDesc 87 | "Resolve any git conflicts that have become trivial by editing operations.\n\ 88 | \Go to https://github.com/Peaker/git-mediate for example use." 89 | <> O.header "git-mediate - Become a conflicts hero" 90 | 91 | getOpts :: IO Options 92 | getOpts = 93 | OptUtils.parseEnvOptions "GIT_MEDIATE_OPTIONS" envOptsParser 94 | >>= O.execParser . opts 95 | >>= \case 96 | CmdVersion -> 97 | do 98 | putStrLn $ "git-mediate version " ++ versionString 99 | exitSuccess 100 | CmdOptions o -> pure o 101 | -------------------------------------------------------------------------------- /src/PPDiff.hs: -------------------------------------------------------------------------------- 1 | module PPDiff 2 | ( ColorEnable (..) 3 | , ppDiff 4 | ) where 5 | 6 | import Data.Algorithm.Diff (Diff, PolyDiff(..)) 7 | import System.Console.ANSI 8 | 9 | data ColorEnable = EnableColor | DisableColor 10 | 11 | wrap :: ColorEnable -> Color -> String -> String 12 | wrap DisableColor _ str = str 13 | wrap EnableColor color str = setSGRCode [SetColor Foreground Vivid color] ++ str ++ setSGRCode [Reset] 14 | 15 | ppDiff :: ColorEnable -> Diff String -> String 16 | ppDiff c (First x) = wrap c Red $ '-':x 17 | ppDiff c (Second x) = wrap c Green $ '+':x 18 | ppDiff _ (Both x _) = ' ':x 19 | -------------------------------------------------------------------------------- /src/Resolution.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE NoImplicitPrelude, BangPatterns, DerivingVia, DeriveGeneric, OverloadedRecordDot #-} 2 | 3 | module Resolution 4 | ( Result(..) 5 | , NewContent(..) 6 | , resolveContent 7 | , fullySuccessful 8 | ) where 9 | 10 | import Conflict (Conflict(..), Sides(..)) 11 | import qualified Conflict 12 | import Control.Monad (guard) 13 | import Data.Foldable (Foldable(..)) 14 | import Data.List (isPrefixOf) 15 | import Data.List.Split (splitWhen) 16 | import Generic.Data (Generic, Generically(..)) 17 | import ResolutionOpts 18 | 19 | import Prelude.Compat 20 | 21 | data Resolution 22 | = NoResolution Conflict 23 | | Resolution String 24 | | PartialResolution String 25 | 26 | resolveGen :: Eq a => Sides a -> Maybe a 27 | resolveGen (Sides a base b) 28 | | a == base = Just b 29 | | b == base = Just a 30 | | a == b = Just a 31 | | otherwise = Nothing 32 | 33 | resolveGenLines :: Eq a => ResolutionOptions -> Sides [a] -> Maybe [a] 34 | resolveGenLines opts sides@(Sides a base b) = 35 | case guard opts.trivial >> resolveGen sides of 36 | Just x -> Just x 37 | _ | opts.addedLines -> 38 | case addedBothSides a b <> addedBothSides b a of 39 | [x] -> Just x 40 | _ -> Nothing 41 | _ -> Nothing 42 | where 43 | n = length base 44 | addedBothSides x y = [x <> drop n y | drop (length x - n) x == base && take n y == base] 45 | 46 | resolveReduced :: ResolutionOptions -> Sides [String] -> Maybe [String] 47 | resolveReduced opts sides 48 | | opts.indentation = 49 | map . (<>) <$> resolveGen prefixes <*> resolveGenLines opts unprefixed 50 | | otherwise = resolveGenLines opts sides 51 | where 52 | prefixes = takeWhile (== ' ') . commonPrefix <$> sides 53 | unprefixed = map . drop . length <$> prefixes <*> sides 54 | 55 | commonPrefix :: Eq a => [[a]] -> [a] 56 | commonPrefix [] = [] 57 | commonPrefix [x] = x 58 | commonPrefix (x:xs) = map fst . takeWhile (uncurry (==)) . zip x $ commonPrefix xs 59 | 60 | resolveConflict :: ResolutionOptions -> Conflict -> Resolution 61 | resolveConflict opts c 62 | | matchTop == 0 && matchBottom == 0 || not opts.reduce = 63 | maybe (NoResolution c) (Resolution . unlines) (resolveReduced opts c.bodies) 64 | | otherwise = 65 | case resolveGenLines opts reduced.bodies of 66 | Just x -> Resolution $ formatRes x 67 | Nothing -> PartialResolution $ formatRes $ Conflict.prettyLines reduced 68 | where 69 | formatRes mid = unlines $ take matchTop c.bodies.sideA <> mid <> takeEnd matchBottom c.bodies.sideA 70 | match base a b 71 | | null base = lengthOfCommonPrefix a b 72 | | otherwise = minimum $ map (lengthOfCommonPrefix base) [a, b] 73 | matchTop = match c.bodies.sideBase c.bodies.sideA c.bodies.sideB 74 | revBottom = reverse . drop matchTop 75 | matchBottom = match (revBottom c.bodies.sideBase) (revBottom c.bodies.sideA) (revBottom c.bodies.sideB) 76 | dropEnd count xs = take (length xs - count) xs 77 | takeEnd count xs = drop (length xs - count) xs 78 | unmatched xs = drop matchTop $ dropEnd matchBottom xs 79 | reduced = Conflict.setEachBody unmatched c 80 | 81 | lengthOfCommonPrefix :: Eq a => [a] -> [a] -> Int 82 | lengthOfCommonPrefix x y = length $ takeWhile id $ zipWith (==) x y 83 | 84 | data Result = Result 85 | { resolvedSuccessfully :: !Int 86 | , reducedConflicts :: !Int 87 | , failedToResolve :: !Int 88 | } 89 | 90 | fullySuccessful :: Result -> Bool 91 | fullySuccessful (Result _ reduced failed) = reduced == 0 && failed == 0 92 | 93 | instance Semigroup Result where 94 | Result x0 y0 z0 <> Result x1 y1 z1 = Result (x0+x1) (y0+y1) (z0+z1) 95 | 96 | instance Monoid Result where mempty = Result 0 0 0 97 | 98 | data NewContent = NewContent 99 | { result :: !Result 100 | , newContent :: !String 101 | } 102 | deriving Generic 103 | deriving (Semigroup, Monoid) via Generically NewContent 104 | 105 | untabifyStr :: Int -> String -> String 106 | untabifyStr size = 107 | go 0 108 | where 109 | cyclicInc col 110 | | col >= size - 1 = 0 111 | | otherwise = col + 1 112 | go !col ('\t':rest) = replicate (size - col) ' ' ++ go 0 rest 113 | go !col (x:rest) = x : go (cyclicInc col) rest 114 | go _ [] = [] 115 | 116 | untabifyConflict :: Int -> Conflict -> Conflict 117 | untabifyConflict = Conflict.setStrings . untabifyStr 118 | 119 | data LineEnding = LF | CRLF | Mixed 120 | deriving (Eq, Ord) 121 | 122 | lineEnding :: String -> LineEnding 123 | lineEnding x@(_:_) | last x == '\r' = CRLF 124 | lineEnding _ = LF 125 | 126 | inferLineEndings :: [String] -> LineEnding 127 | inferLineEndings [] = Mixed 128 | inferLineEndings xs = 129 | foldl1 f (map lineEnding xs) 130 | where 131 | f Mixed _ = Mixed 132 | f x c 133 | | x == c = x 134 | | otherwise = Mixed 135 | 136 | allSame :: Eq a => [a] -> Bool 137 | allSame (x:y:rest) = x == y && allSame (y:rest) 138 | allSame _ = True 139 | 140 | lineBreakFix :: Conflict -> Conflict 141 | lineBreakFix c 142 | | any null c.bodies 143 | || allSame (toList endings) = c 144 | | otherwise = 145 | case resolveGen endings of 146 | Just LF -> Conflict.setStrings removeCr c 147 | Just CRLF -> Conflict.setStrings makeCr c 148 | _ -> c 149 | where 150 | endings = fmap inferLineEndings c.bodies 151 | removeCr x@(_:_) | last x == '\r' = init x 152 | removeCr x = x 153 | makeCr x@(_:_) | last x == '\r' = x 154 | makeCr x = x <> "\r" 155 | 156 | formatResolution :: Resolution -> NewContent 157 | formatResolution (NoResolution c) = NewContent (Result 0 0 1) (Conflict.pretty c) 158 | formatResolution (Resolution trivialLines) = NewContent (Result 1 0 0) trivialLines 159 | formatResolution (PartialResolution newLines) = NewContent (Result 0 1 0) newLines 160 | 161 | resolveContent :: ResolutionOptions -> [Either String Conflict] -> NewContent 162 | resolveContent opts = 163 | foldMap go 164 | where 165 | go (Left line) = NewContent mempty (unlines [line]) 166 | go (Right conflict) = 167 | r 168 | { result = 169 | case parts of 170 | [_] -> r.result 171 | _ | r.result.failedToResolve + r.result.reducedConflicts > 0 -> 172 | mempty {reducedConflicts = 1} -- The split is a reduction 173 | | otherwise -> mempty {resolvedSuccessfully = 1} 174 | } 175 | where 176 | parts 177 | | opts.splitMarkers = splitConflict conflict 178 | | otherwise = [conflict] 179 | r = foldMap resolve parts 180 | resolve conflict = 181 | formatResolution $ resolveConflict opts $ 182 | (if opts.lineEndings then lineBreakFix else id) $ 183 | maybe id untabifyConflict opts.untabify conflict 184 | 185 | splitConflict :: Conflict -> [Conflict] 186 | splitConflict c = 187 | maybe [c] ((\s -> c{bodies=s}) <$>) $ 188 | matchSplits $ splitWhen (isPrefixOf "~~~~~~~") <$> c.bodies 189 | 190 | matchSplits :: Sides [a] -> Maybe [Sides a] 191 | matchSplits (Sides (a:as) (b:bs) (c:cs)) = 192 | (Sides a b c :) <$> matchSplits (Sides as bs cs) 193 | matchSplits (Sides [] [] []) = Just [] 194 | matchSplits _ = Nothing 195 | -------------------------------------------------------------------------------- /src/ResolutionOpts.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE OverloadedRecordDot #-} 2 | 3 | module ResolutionOpts 4 | ( ResolutionOptions(..), parser, isResolving 5 | ) where 6 | 7 | import Data.Maybe (isJust) 8 | import qualified OptUtils 9 | 10 | data ResolutionOptions = ResolutionOpts 11 | { trivial :: Bool 12 | , reduce :: Bool 13 | , untabify :: Maybe Int 14 | , lineEndings :: Bool 15 | , addedLines :: Bool 16 | , splitMarkers :: Bool 17 | , indentation :: Bool 18 | } 19 | 20 | parser :: OptUtils.Parser ResolutionOptions 21 | parser = 22 | ResolutionOpts 23 | <$> OptUtils.envSwitch "trivial" True "trivial conflicts resolution" 24 | <*> OptUtils.envSwitch "reduce" True "conflict reduction" 25 | <*> OptUtils.envOptional "untabify" "TABSIZE" 26 | "Convert tabs to the spaces at the tab stops for the given tab size" 27 | (\x -> "Disable converting tabs to " <> show x <> " spaces at the tab stops") 28 | <*> OptUtils.envSwitch "line-endings" True "line-ending characters conflict resolution" 29 | <*> OptUtils.envSwitch "lines-added-around" False 30 | "resolve conflicts where one change prepended lines to the base and the other appended" 31 | <*> OptUtils.envSwitch "split-markers" True "split conflicts at tilde-split-markers" 32 | <*> OptUtils.envSwitch "indentation" False "indentation conflict resolution" 33 | 34 | isResolving :: ResolutionOptions -> Bool 35 | isResolving o = o.trivial || o.reduce || isJust o.untabify || o.lineEndings || o.addedLines 36 | -------------------------------------------------------------------------------- /src/Setup.hs: -------------------------------------------------------------------------------- 1 | import Distribution.Simple 2 | 3 | main = defaultMain 4 | -------------------------------------------------------------------------------- /src/SideDiff.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE NoImplicitPrelude, OverloadedRecordDot #-} 2 | 3 | module SideDiff 4 | ( SideDiff(..), Side(..) 5 | , getConflictDiffs, getConflictDiff2s 6 | ) where 7 | 8 | import Conflict (Conflict(..), Sides(..), SrcContent(..)) 9 | import Data.Algorithm.Diff (Diff, getDiff) 10 | 11 | import Prelude.Compat 12 | 13 | data Side = A | B 14 | deriving (Eq, Ord, Show) 15 | 16 | data SideDiff = SideDiff 17 | { side :: Side 18 | , marker :: SrcContent 19 | , diff :: [Diff String] 20 | } 21 | 22 | getConflictDiffs :: Conflict -> [SideDiff] 23 | getConflictDiffs c = 24 | [ SideDiff A c.markers.sideA (getDiff c.bodies.sideBase c.bodies.sideA) 25 | | not (null c.bodies.sideA) ] ++ 26 | [ SideDiff B (SrcContent c.markers.sideB.lineNo c.markerEnd.content) (getDiff c.bodies.sideBase c.bodies.sideB) 27 | | not (null c.bodies.sideB) ] 28 | 29 | getConflictDiff2s :: Conflict -> (SrcContent, SrcContent, [Diff String]) 30 | getConflictDiff2s c = 31 | (c.markers.sideA, c.markers.sideB, getDiff c.bodies.sideA c.bodies.sideB) 32 | -------------------------------------------------------------------------------- /src/StrUtils.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE NoImplicitPrelude #-} 2 | 3 | module StrUtils 4 | ( (), stripNewline, ensureNewline 5 | ) where 6 | 7 | import Data.List (isSuffixOf) 8 | import qualified System.FilePath as FilePath 9 | 10 | import Prelude.Compat 11 | 12 | stripNewline :: String -> String 13 | stripNewline x 14 | | "\n" `isSuffixOf` x = init x 15 | | otherwise = x 16 | 17 | ensureNewline :: String -> String 18 | ensureNewline "" = "" 19 | ensureNewline str = str ++ suffix 20 | where 21 | suffix 22 | | "\n" `isSuffixOf` str = "" 23 | | otherwise = "\n" 24 | 25 | () :: FilePath -> FilePath -> FilePath 26 | "." p = p 27 | d p = d FilePath. p 28 | -------------------------------------------------------------------------------- /src/Version.hs: -------------------------------------------------------------------------------- 1 | -- | Expose cabal package version as a string 2 | module Version (versionString) where 3 | 4 | import Paths_git_mediate (version) 5 | import Data.Version (showVersion) 6 | 7 | versionString :: String 8 | versionString = showVersion version 9 | -------------------------------------------------------------------------------- /stack.yaml: -------------------------------------------------------------------------------- 1 | flags: {} 2 | packages: 3 | - '.' 4 | resolver: lts-22.42 5 | -------------------------------------------------------------------------------- /test/config/test: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -eux 4 | 5 | DIR="$( dirname "$0" )" 6 | cd "${DIR}" 7 | 8 | export HOME="$(pwd)" 9 | 10 | pwd 11 | 12 | cleanup () { 13 | rm -rf .git .gitconfig 14 | } 15 | trap cleanup EXIT 16 | cleanup 17 | 18 | git init 19 | 20 | git config --global merge.conflictstyle diff3 21 | git config --global --unset merge.conflictstyle 22 | (git-mediate && exit 11) || 23 | echo 'Conflict style unset errorized correctly' 24 | 25 | git config --global merge.conflictstyle diff2 26 | (git-mediate && exit 12) || 27 | echo 'Conflict style diff2 errorized correctly' 28 | 29 | git config --global merge.conflictstyle diff3 30 | git-mediate 31 | 32 | echo 'diff3 accepted correctly' 33 | 34 | git config merge.conflictstyle diff2 35 | (git-mediate && exit 12) || 36 | echo 'Per-project conflict style diff2 errorized correctly' 37 | 38 | (git-mediate -s && exit 12) || 39 | echo 'Per-project conflict style diff2 failure to override errorized correctly' 40 | git config --unset merge.conflictstyle 41 | git config --global merge.conflictstyle diff2 42 | git-mediate -s 43 | style=$(git config merge.conflictstyle) 44 | if [ "${style}" = "diff3" ]; then 45 | echo 'Conflict style set correctly' 46 | else 47 | echo 'The -s option did not set conflict style' 48 | exit 1 49 | fi 50 | 51 | echo Success 52 | -------------------------------------------------------------------------------- /test/run_tests: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -eux 4 | 5 | DIR="$( dirname "$0" )" 6 | SRC="$( dirname "${DIR}" )" 7 | STACK_PATH="$( stack path --local-install-root )/bin" 8 | CABAL_PATH="${SRC}/dist/build/git-mediate" 9 | 10 | export PATH="${STACK_PATH}:${CABAL_PATH}:$PATH" 11 | 12 | echo 'Spaces test' 13 | "${DIR}"/spaces/test 14 | 15 | echo 'Untabify test' 16 | "${DIR}"/untabify/test 17 | 18 | echo 'Config test' 19 | "${DIR}"/config/test 20 | 21 | 22 | echo 'Tests successful' 23 | -------------------------------------------------------------------------------- /test/spaces/test: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -eux 4 | 5 | DIR="$( dirname "$0" )" 6 | cd "${DIR}" 7 | 8 | export HOME="$(pwd)" 9 | 10 | pwd 11 | 12 | cleanup () { 13 | rm -rf .git .gitconfig 'a b' 14 | } 15 | trap cleanup EXIT 16 | cleanup 17 | 18 | git init >/dev/null 19 | git config user.email test@test.com 20 | git config user.name Test 21 | echo hi > 'a b' 22 | git add -- 'a b' 23 | git commit -m'a b file added' >/dev/null 24 | echo changeA >> 'a b' 25 | git stash >/dev/null 26 | echo changeB >> 'a b' 27 | git add 'a b' 28 | git config --global merge.conflictstyle diff3 29 | (git stash pop >/dev/null && exit 1) || 30 | echo 'Conflict set up successfully' 31 | # Set up of conflict over 32 | 33 | git-mediate >/dev/null && 34 | (echo 'should fail to resolve conflicts' ; exit 1) 35 | 36 | echo Success 37 | -------------------------------------------------------------------------------- /test/untabify/test: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -eux 4 | 5 | DIR="$( dirname "$0" )" 6 | cd "${DIR}" 7 | 8 | export HOME="$(pwd)" 9 | 10 | pwd 11 | 12 | cleanup () { 13 | rm -rf .git .gitconfig file 14 | } 15 | trap cleanup EXIT 16 | cleanup 17 | 18 | git init >/dev/null 19 | git config user.email test@test.com 20 | git config user.name Test 21 | printf 'Hello\tBooya\n' > file 22 | git add -- file 23 | git commit -m'tabs' >/dev/null 24 | echo 'Extra line' >> file 25 | git stash >/dev/null 26 | echo 'Hello Booya' > file 27 | git add file 28 | git config --global merge.conflictstyle diff3 29 | (git stash pop >/dev/null && exit 1) || 30 | echo 'Conflict set up successfully' 31 | # Set up of conflict over 32 | 33 | git-mediate --untabify=4 34 | 35 | echo Success 36 | --------------------------------------------------------------------------------