git-mediate-1.0.9/0000755000000000000000000000000007346545000012103 5ustar0000000000000000git-mediate-1.0.9/ChangeLog.md0000644000000000000000000000437707346545000014267 0ustar0000000000000000## 1.0.9 / To be released * Do not warn when git is set to use `zdiff3` conflict style * Resolve line ending conventions changes (i.e changes from Unix/Windows line endings) * Preserve file modes when resolving conflicts (i.e executable scripts remain executable) * Handle changes in `git status` formatting for files in spaces in their names * `--context` option for `-d` mode to control size of context shown around diff * Fixed parsing of conflicts with nested recursive conflicts * `--editor` goes to the location of the first conflict in the file ## 1.0.8.1 / 2020.10.13 * First release on Debian (entered Debian unstable at 2023.07.20) * Build maintenance (anti-bitrot) ## 1.0.6 / 2020.01.07 * `--merge-file` option to merge specific file, even if file is not marked as conflicted * Reduce add/add conflicts with matching prefix/suffix lines * Add support for `--untabify` ## 1.0.5 / 2018.07.24 * Windows compatibility fixes ## 1.0.1 / 2018.07.24 * Conflict headers for `-d` option (i.e "### Conflict 3 of 7") * Improved error message when not running inside a git repository ## 1.0 / 2016.12.20 * Renamed to `git-mediate` * First release on Hackage * Add `--version` flag ## 0.3.2.4 / 2016.12.20 * Reduce conflicts when first or last lines match in all parts ## 0.3.2.1 / 2015.12.25 * `--diff2` option to dump diffs in `diff2` format * Fix bug in modify/delete conflicts when not running from the repo's root ## 0.3.1.2 / 2015.09.20 * Better error reporting for conflict parsing errors ## 0.3.1.1 / 2015.09.01 * Support modify/delete conflicts ## 0.3.0.3 / 2015.08.16 * `-d` option also prints the diffs markers * Support add/add conflicts * Fixed bug with submodule conflicts ## 0.3.0.1 / 2015.06.06 * Detect git using `diff2` conflict style and add `-s` option to switch to `diff3` style * Fixed bug with filenames containing spaces ## 0.2.0.2 / 2015.02.03 * Support for terminals without color ## 0.2.0.1 / 2015.01.12 * Don't keep `.bk` backups files for content before resolution ## 0.2 / 2014.12.18 * `-d` option for displaying the remaining conflicts ## 0.1.0.1 / 2014.12.10 * Conflict also resolves if both sides match (regardless of base also matching) ## Development started / 2014.12.1 * Tool developed started originally as "resolve-trivial-conflicts" git-mediate-1.0.9/LICENSE0000644000000000000000000004325407346545000013120 0ustar0000000000000000 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. git-mediate-1.0.9/README.md0000644000000000000000000000665207346545000013373 0ustar0000000000000000# Introduction Handling conflicts is difficult! One useful way to handle them, is to use git's diff3 conflict style: ```shell git config --global merge.conflictstyle diff3 ``` And then when you get a conflict, it looks like: Unconflicted stuff <<<<<<< HEAD Version A changes ||||||| Base version ======= Version B Version B changes >>>>>>> More unconflicted stuff here Then you are supposed to manually merge the useful changes in the top and bottom parts, relative to the base version. A useful way to do this is to figure out which of the changes (Version A or Version B) is a simpler change. Perhaps one of the versions just added a small comment above the code section: Unconflicted stuff <<<<<<< HEAD Added a comment here BASE ||||||| BASE ======= Version B BASE and complex changes here >>>>>>> More unconflicted stuff here One easy thing to do, mechanically, is to apply the simple change to the other 2 versions. Thus, it becomes: Unconflicted stuff <<<<<<< HEAD Added a comment here BASE ||||||| Added a comment here BASE ======= Version B Added a comment here BASE and complex changes here >>>>>>> More unconflicted stuff here Now, you can run this little utility: git-mediate, which will see the conflict has become trivial (only one side changed anything) and select that side appropriately. When all conflicts have been resolved in a file, "git add" will be used on it automatically. ## Simpler case You might just resolve the conflicts manually and remove the merge markers from all of the conflicts. In such a case, just run git-mediate, and it will "git add" the file for you. # Installation ## Recommended: Using haskell-stack 1. Install [haskell stack](https://docs.haskellstack.org/en/stable/) 2. Run: `stack install git-mediate` ## Alternative install: from sources Clone it: git clone https://github.com/Peaker/git-mediate cd git-mediate Option #1: Build & install using stack: `stack install` (make sure you installed [haskell stack](https://docs.haskellstack.org/en/stable/)) Option #2: Build & install using cabal: `cabal install` (make sure `~/.cabal/bin` is in your `$PATH`) # Use Call the git-mediate from a git repository with conflicts. # Additional features ## Open editor You can use the `-e` flag to invoke your `$EDITOR` on every conflicted file that could not be automatically resolved. ## Show conflict diffs Sometimes, the conflict is just a giant block of incomprehensible text next to another giant block of incomprehensible text. 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. # License Copyright (C) 2014-2023 Eyal Lotem 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; version 2 of the License only. 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, see . git-mediate-1.0.9/git-mediate.cabal0000644000000000000000000000702607346545000015265 0ustar0000000000000000-- Initial git-mediate.cabal generated by cabal init. For -- further documentation, see https://cabal.readthedocs.io/ name: git-mediate version: 1.0.9 synopsis: Tool to help resolving git conflicts description: Git conflict resolution has never been easier . When encountering a conflict, you can sometimes imagine: if only I could have applied one of these patches BEFORE the other rather than concurrently, I wouldn't be in this mess! . Well, with git-mediate, you can! . In any conflicted state - git-mediate shows you the 2 diffs involved. By applying these diffs to the base version and the other version, you emulate the situation where the patch had already existed when the other had been applied. . Reapply git-mediate, it will validate that you've indeed applied it correctly, and bam: conflict disappeared! . Git-mediate also lets you handle modify/delete conflicts (there's no sane way in git to show what the modification actually was) . Git-mediate also streamlines jumping to the conflicts with your editor, either with the `-e` option to invoke your editor, or via the standard line number format, which is parsed by all major editors, to allow use of "jump to next error" keys. . Git-mediate especially shines with automatic source transformation tools such as renamers. . In a conflicted state, re-apply a rename that caused the conflict, run git-mediate without opening any files, and the conflicts are gone! homepage: https://github.com/Peaker/git-mediate license: GPL-2 license-file: LICENSE author: Eyal Lotem maintainer: eyal.lotem@gmail.com -- copyright: category: Development build-type: Simple extra-source-files: stack.yaml ChangeLog.md README.md cabal-version: >=1.10 source-repository head type: git location: https://github.com/Peaker/git-mediate executable git-mediate main-is: Main.hs other-modules: Conflict , Environment , Opts , PPDiff , Resolution , SideDiff , StrUtils , Version , Paths_git_mediate ghc-options: -O2 -Wall -- other-extensions: build-depends: base >=4.8 && <5 , base-compat >= 0.8.2 , mtl >=2.1 , directory >=1.2 , process >=1.2 , filepath >=1.3 , unix-compat >=0.4.2.0 , Diff >=0.4 , ansi-terminal >=0.6.2 , optparse-applicative >=0.11 , generic-data >=0.8.2 hs-source-dirs: src default-language: Haskell2010 git-mediate-1.0.9/src/0000755000000000000000000000000007346545000012672 5ustar0000000000000000git-mediate-1.0.9/src/Conflict.hs0000644000000000000000000000765507346545000015004 0ustar0000000000000000{-# LANGUAGE FlexibleContexts, NoImplicitPrelude, DeriveTraversable, NamedFieldPuns, DerivingVia, DeriveGeneric, OverloadedRecordDot #-} module Conflict ( Conflict(..), Sides(..), SrcContent(..) , setEachBody, setStrings , pretty, prettyLines , parse ) where import Control.Monad.State (MonadState, state, evalStateT) import Control.Monad.Writer (runWriter, tell) import Data.Maybe (fromMaybe) import Generic.Data (Generically1(..)) import GHC.Generics (Generic1) import Prelude.Compat data Sides a = Sides { sideA :: a , sideBase :: a , sideB :: a } deriving (Functor, Foldable, Traversable, Show, Eq, Ord, Generic1) deriving Applicative via Generically1 Sides data SrcContent = SrcContent { lineNo :: Int , content :: String } deriving Show data Conflict = Conflict { markers :: Sides SrcContent -- The markers at the beginning of sections , markerEnd :: SrcContent -- The ">>>>>>>...." marker at the end of the conflict , bodies :: Sides [String] } deriving Show setBodies :: (Sides [String] -> Sides [String]) -> Conflict -> Conflict setBodies f c = c{bodies = f c.bodies} setEachBody :: ([String] -> [String]) -> Conflict -> Conflict setEachBody = setBodies . fmap setStrings :: (String -> String) -> Conflict -> Conflict setStrings = setEachBody . map prettyLines :: Conflict -> [String] prettyLines c = concat ((:) <$> ((.content) <$> c.markers) <*> c.bodies) <> [c.markerEnd.content] pretty :: Conflict -> String pretty = unlines . prettyLines breakUpToMarker :: MonadState [SrcContent] m => Char -> Maybe Int -> m [SrcContent] breakUpToMarker c mCount = state (break cond) where count = fromMaybe 7 mCount prefix = replicate count c cond l = pre == prefix && rightCount where (pre, post) = splitAt count l.content rightCount = case (mCount, post) of (Just{}, x:_) -> c /= x _ -> True readHead :: MonadState [a] m => m (Maybe a) readHead = state f where f [] = (Nothing, []) f (l:ls) = (Just l, ls) tryReadUpToMarker :: MonadState [SrcContent] m => Char -> Maybe Int -> m ([SrcContent], Maybe SrcContent) tryReadUpToMarker c mCount = (,) <$> breakUpToMarker c mCount <*> readHead readUpToMarker :: MonadState [SrcContent] m => Char -> Maybe Int -> m ([SrcContent], SrcContent) readUpToMarker c mCount = do res <- tryReadUpToMarker c mCount case res of (ls, Just h) -> pure (ls, h) (ls, Nothing) -> error $ concat [ "Parse error: failed reading up to marker: " , show c, ", got:" , concatMap (\l -> "\n" ++ show l.lineNo ++ "\t" ++ l.content) $ take 5 ls ] parseConflict :: MonadState [SrcContent] m => SrcContent -> m Conflict parseConflict markerA = do (linesA , markerBase) <- readUpToMarker '|' markerCount (linesBase, markerB) <- readUpToMarker '=' markerCount (linesB , markerEnd) <- readUpToMarker '>' markerCount pure Conflict { markers = Sides markerA markerBase markerB , markerEnd , bodies = fmap (.content) <$> Sides linesA linesBase linesB } where markerCount = Just (length (takeWhile (== '<') markerA.content)) parseFromNumberedLines :: [SrcContent] -> [Either String Conflict] parseFromNumberedLines = snd . runWriter . evalStateT loop where loop = do (ls, mMarkerA) <- tryReadUpToMarker '<' Nothing tell $ map (Left . (.content)) ls case mMarkerA of Nothing -> pure () Just markerA -> do tell . pure . Right =<< parseConflict markerA loop parse :: String -> [Either String Conflict] parse = parseFromNumberedLines . zipWith SrcContent [1..] . lines git-mediate-1.0.9/src/Environment.hs0000644000000000000000000000500707346545000015534 0ustar0000000000000000{-# LANGUAGE NoImplicitPrelude, OverloadedRecordDot #-} module Environment ( checkConflictStyle, shouldUseColorByTerminal, openEditor ) where import qualified Control.Exception as E import Control.Monad (when, unless) import Data.Functor ((<&>)) import Opts (Options(..)) import PPDiff (ColorEnable(..)) import StrUtils (stripNewline) import System.Console.ANSI (hSupportsANSI) import System.IO (stdout) import System.Environment (getEnv) import System.Exit (ExitCode(..)) import System.Process (callProcess, readProcessWithExitCode) import Prelude.Compat shouldUseColorByTerminal :: IO ColorEnable shouldUseColorByTerminal = hSupportsANSI stdout <&> \istty -> if istty then EnableColor else DisableColor getConflictStyle :: IO String getConflictStyle = do (exitCode, output, _) <- readProcessWithExitCode "git" ["config", "merge.conflictstyle"] stdin case exitCode of ExitSuccess -> pure $ stripNewline output ExitFailure 1 -> pure "unset" ExitFailure _ -> E.throwIO exitCode where stdin = "" setConflictStyle :: IO () setConflictStyle = callProcess "git" ["config", "--global", "merge.conflictstyle", "diff3"] checkConflictStyle :: Options -> IO () checkConflictStyle opts = do conflictStyle <- getConflictStyle unless (conflictStyle `elem` ["diff3", "zdiff3"]) $ do unless opts.shouldSetConflictStyle $ fail $ concat [ "merge.conflictstyle must be diff3 but is " , show conflictStyle , ". Use -s to automatically set it globally" ] setConflictStyle newConflictStyle <- getConflictStyle when (newConflictStyle /= "diff3") $ fail $ concat [ "Attempt to set conflict style failed. Perhaps you have" , " an incorrect merge.conflictstyle configuration " , "specified in your per-project .git/config?" ] openEditor :: Options -> FilePath -> Int -> IO () openEditor opts path lineNo | opts.shouldUseEditor = do editor <- getEnv "EDITOR" let cmdOpts = case editor of "code" -> ["--goto", path <> ":" <> show lineNo] _ -> ["+" <> show lineNo, path] callProcess editor cmdOpts | otherwise = pure () git-mediate-1.0.9/src/Main.hs0000644000000000000000000002455207346545000014122 0ustar0000000000000000{-# LANGUAGE NoImplicitPrelude, OverloadedRecordDot, FlexibleContexts #-} module Main (main) where import Conflict (Conflict(..)) import qualified Conflict import qualified Control.Exception as E import Control.Monad (when, unless, filterM) import Data.Algorithm.Diff (Diff, PolyDiff(..)) import Data.Either (rights) import Data.Foldable (asum, traverse_) import Data.List (isPrefixOf) import Data.Maybe (mapMaybe) import Environment (checkConflictStyle, openEditor, shouldUseColorByTerminal) import qualified Opts import Opts (Options(..)) import PPDiff (ppDiff, ColorEnable(..)) import Resolution (Result(..), NewContent(..), Untabify(..)) import qualified Resolution import SideDiff (SideDiff(..), getConflictDiffs, getConflictDiff2s) import StrUtils (ensureNewline, stripNewline, unprefix) import System.Directory (renameFile, removeFile, getCurrentDirectory, getPermissions, setPermissions) import System.Exit (ExitCode(..), exitWith) import System.FilePath ((<.>), makeRelative, joinPath, splitPath) import qualified System.FilePath as FilePath import System.IO (hPutStr, stderr) import qualified System.PosixCompat.Files as PosixFiles import System.Process (callProcess, readProcess, readProcessWithExitCode) import Prelude.Compat -- '>' -> ">>>>>>>" markerPrefix :: Char -> String markerPrefix = replicate 7 markerLine :: Char -> String -> String markerLine c str = markerPrefix c ++ " " ++ str ++ "\n" gitAdd :: FilePath -> IO () gitAdd fileName = callProcess "git" ["add", "--", fileName] trimDiff :: Int -> [Diff a] -> [Diff a] trimDiff contextLen = reverse . f . reverse . f where f l = drop (length (takeWhile both l) - contextLen) l both Both{} = True both _ = False dumpDiffs :: ColorEnable -> Options -> FilePath -> Int -> (Int, Conflict) -> IO () dumpDiffs colorEnable opts filePath count (idx, conflict) = do putStrLn $ unwords ["### Conflict", show idx, "of", show count] when opts.shouldDumpDiffs $ traverse_ dumpDiff $ getConflictDiffs conflict when opts.shouldDumpDiff2 $ dumpDiff2 $ getConflictDiff2s conflict where dumpDiff d = do putStrLn $ concat [filePath, ":", show d.marker.lineNo, ":Diff", show d.side, ": ", d.marker.content] putStr $ unlines $ map (ppDiff colorEnable) (trimDiff opts.diffsContext d.diff) dumpDiff2 (markerA, markerB, d) = do putStrLn $ concat [filePath, ":", show markerA.lineNo, " <->", markerA.content] putStrLn $ concat [filePath, ":", show markerB.lineNo, ": ", markerB.content] putStr $ unlines $ map (ppDiff colorEnable) d dumpAndOpenEditor :: ColorEnable -> Options -> FilePath -> [Conflict] -> IO () dumpAndOpenEditor colorEnable opts path conflicts = do when (opts.shouldDumpDiffs || opts.shouldDumpDiff2) $ traverse_ (dumpDiffs colorEnable opts path (length conflicts)) (zip [1..] conflicts) openEditor opts path ((Conflict.lineNo . Conflict.sideA . markers . head) conflicts) overwrite :: FilePath -> String -> IO () overwrite fileName content = do oldPermissions <- getPermissions fileName renameFile fileName bkup writeFile fileName content setPermissions fileName oldPermissions removeFile bkup where bkup = fileName <.> "bk" handleFileResult :: ColorEnable -> Options -> FilePath -> NewContent -> IO () handleFileResult colorEnable opts fileName res | successes == 0 && allGood = do putStrLn $ fileName ++ ": No conflicts, git-adding" gitAdd fileName | successes == 0 && reductions == 0 = do putStrLn $ concat [ fileName, ": Failed to resolve any of the " , show failures, " conflicts" ] doDump | successes == 0 = do putStrLn $ concat [ fileName, ": Reduced ", show reductions, " conflicts"] overwrite fileName res.newContent doDump | otherwise = do putStrLn $ concat [ fileName, ": Successfully resolved ", show successes , " conflicts (failed to resolve " ++ show (reductions + failures) ++ " conflicts)" , if allGood then ", git adding" else "" ] overwrite fileName res.newContent if allGood then gitAdd fileName else doDump where allGood = Resolution.fullySuccessful res.result doDump = dumpAndOpenEditor colorEnable opts fileName (rights (Conflict.parse res.newContent)) Result { resolvedSuccessfully = successes , reducedConflicts = reductions , failedToResolve = failures } = res.result resolve :: ColorEnable -> Options -> FilePath -> IO Result resolve colorEnable opts fileName = do resolutions <- Resolution.resolveContent (Untabify opts.untabify) . Conflict.parse <$> readFile fileName resolutions.result <$ handleFileResult colorEnable opts fileName resolutions relativePath :: FilePath -> FilePath -> FilePath relativePath base path | rel /= path = rel | revRel /= base = joinPath $ replicate (length (splitPath revRel)) ".." | otherwise = path where rel = makeRelative base path revRel = makeRelative path base () :: FilePath -> FilePath -> FilePath "." p = p d p = d FilePath. p isDirectory :: FilePath -> IO Bool isDirectory x = PosixFiles.isDirectory <$> PosixFiles.getFileStatus x withAllStageFiles :: FilePath -> (FilePath -> Maybe FilePath -> Maybe FilePath -> IO b) -> IO b withAllStageFiles path action = do let stdin = "" [baseTmpRaw, localTmpRaw, remoteTmpRaw] <- take 3 . words <$> readProcess "git" ["checkout-index", "--stage=all", "--", path] stdin cdup <- takeWhile (/= '\0') . stripNewline <$> readProcess "git" ["rev-parse", "--show-cdup"] stdin let maybePath "." = Nothing maybePath p = Just (cdup p) let mLocalTmp = maybePath localTmpRaw mRemoteTmp = maybePath remoteTmpRaw baseTmp = cdup baseTmpRaw action baseTmp mLocalTmp mRemoteTmp `E.finally` do removeFile baseTmp traverse_ removeFile mLocalTmp traverse_ removeFile mRemoteTmp deleteModifyConflictAddMarkers :: FilePath -> IO () deleteModifyConflictAddMarkers path = withAllStageFiles path $ \baseTmp mLocalTmp mRemoteTmp -> do baseContent <- readFile baseTmp localContent <- foldMap readFile mLocalTmp remoteContent <- foldMap readFile mRemoteTmp overwrite path $ concat [ markerLine '<' "LOCAL" , ensureNewline localContent , markerLine '|' "BASE" , ensureNewline baseContent , markerLine '=' "" , ensureNewline remoteContent , markerLine '>' "REMOTE" ] deleteModifyConflictHandle :: FilePath -> IO () deleteModifyConflictHandle path = do marked <- any (markerPrefix '<' `isPrefixOf`) . lines <$> readFile path unless marked $ do putStrLn $ show path ++ " has a delete/modify conflict. Adding conflict markers" deleteModifyConflictAddMarkers path removeFileIfEmpty :: FilePath -> IO () removeFileIfEmpty path = do isEmpty <- null <$> readFile path when isEmpty $ do removeFile path callProcess "git" ["add", "-u", "--", path] getStatusPorcelain :: IO String getStatusPorcelain = do (statusCode, statusPorcelain, statusStderr) <- readProcessWithExitCode "git" ["status", "--porcelain"] "" when (statusCode /= ExitSuccess) $ do -- Print git's error message. Usually - -- "fatal: Not a git repository (or any of the parent directories): .git" hPutStr stderr statusStderr exitWith statusCode pure statusPorcelain getGitRootDir :: IO FilePath getGitRootDir = do cwd <- getCurrentDirectory relativePath cwd . stripNewline <$> readProcess "git" ["rev-parse", "--show-toplevel"] "" makeFilesMatchingPrefixes :: IO ([String] -> IO [FilePath]) makeFilesMatchingPrefixes = do statusPorcelain <- getStatusPorcelain rootDir <- getGitRootDir let rootRelativeFiles = filterM (fmap not . isDirectory) . map (rootDir ) let decode x = case reads x of [(r, "")] -> r _ -> x let firstMatchingPrefix :: [String] -> String -> Maybe String firstMatchingPrefix prefixes = fmap decode . asum . traverse unprefix prefixes let filesMatchingPrefixes :: [String] -> IO [FilePath] filesMatchingPrefixes prefixes = rootRelativeFiles . mapMaybe (firstMatchingPrefix prefixes) $ lines statusPorcelain pure filesMatchingPrefixes mediateAll :: ColorEnable -> Options -> IO Result mediateAll colorEnable opts = do filesMatchingPrefixes <- makeFilesMatchingPrefixes -- from git-diff manpage: -- Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), -- have their type (i.e. regular file, symlink, submodule, ...) changed (T), -- are Unmerged (U), are Unknown (X), or have had their pairing Broken (B) deleteModifyConflicts <- filesMatchingPrefixes ["DU ", "UD "] traverse_ deleteModifyConflictHandle deleteModifyConflicts res <- filesMatchingPrefixes ["UU ", "AA ", "DA ", "AD ", "DU ", "UD "] >>= foldMap (resolve colorEnable opts) -- Heuristically delete files that were remove/modify conflict -- and ended up with empty content traverse_ removeFileIfEmpty deleteModifyConflicts pure res exitCodeOf :: Result -> ExitCode exitCodeOf res | Resolution.fullySuccessful res = ExitSuccess | otherwise = ExitFailure 111 exitProcess :: Result -> IO () exitProcess = exitWith . exitCodeOf main :: IO () main = do opts <- Opts.getOpts colorEnable <- maybe shouldUseColorByTerminal pure opts.shouldUseColor checkConflictStyle opts case opts.mergeSpecificFile of Nothing -> mediateAll colorEnable opts Just path -> resolve colorEnable opts path >>= exitProcess git-mediate-1.0.9/src/Opts.hs0000644000000000000000000000601007346545000014150 0ustar0000000000000000{-# LANGUAGE LambdaCase #-} -- | Option parser module Opts ( Options(..) , getOpts ) where import Control.Applicative (Alternative(..)) import qualified Options.Applicative as O import PPDiff (ColorEnable(..)) import System.Exit (exitSuccess) import Version (versionString) data Options = Options { shouldUseEditor :: Bool , shouldDumpDiffs :: Bool , shouldDumpDiff2 :: Bool , shouldUseColor :: Maybe ColorEnable , shouldSetConflictStyle :: Bool , untabify :: Maybe Int , mergeSpecificFile :: Maybe FilePath , diffsContext :: Int } data CmdArgs = CmdVersion | CmdOptions Options parser :: O.Parser CmdArgs parser = O.flag' CmdVersion (O.long "version" <> O.help "Print the version and quit") <|> CmdOptions <$> ( Options <$> O.switch ( O.long "editor" <> O.short 'e' <> O.help "Execute $EDITOR for each conflicted file that remains conflicted" ) <*> O.switch ( O.long "diff" <> O.short 'd' <> O.help "Dump the left/right diffs from base in each conflict remaining" ) <*> O.switch ( O.long "diff2" <> O.short '2' <> O.help "Dump the diff between left and right in each conflict remaining" ) <*> ( O.flag' (Just EnableColor) (O.long "color" <> O.short 'c' <> O.help "Enable color") <|> O.flag' (Just DisableColor) (O.long "no-color" <> O.short 'C' <> O.help "Disable color") <|> pure Nothing ) <*> O.switch ( O.long "style" <> O.short 's' <> O.help "Configure git's global merge.conflictstyle to diff3 if needed" ) <*> O.optional ( O.option O.auto ( O.long "untabify" <> O.metavar "TABSIZE" <> O.help "Convert tabs to the spaces at the tab stops for the given tab size" ) ) <*> O.optional ( O.strOption ( O.long "merge-file" <> O.short 'f' <> O.help "Merge a specific file") ) <*> O.option O.auto (O.long "context" <> O.short 'U' <> O.metavar "LINECOUNT" <> O.showDefault <> O.value 3 <> O.help "Number of context lines around dumped diffs" ) ) opts :: O.ParserInfo CmdArgs opts = O.info (O.helper <*> parser) $ O.fullDesc <> O.progDesc "Resolve any git conflicts that have become trivial by editing operations.\n\ \Go to https://github.com/Peaker/git-mediate for example use." <> O.header "git-mediate - Become a conflicts hero" getOpts :: IO Options getOpts = O.execParser opts >>= \case CmdVersion -> do putStrLn $ "git-mediate version " ++ versionString exitSuccess CmdOptions o -> pure o git-mediate-1.0.9/src/PPDiff.hs0000644000000000000000000000103207346545000014332 0ustar0000000000000000module PPDiff ( ColorEnable(..) , ppDiff ) where import Data.Algorithm.Diff (Diff, PolyDiff(..)) import System.Console.ANSI data ColorEnable = EnableColor | DisableColor wrap :: ColorEnable -> Color -> String -> String wrap DisableColor _ str = str wrap EnableColor color str = setSGRCode [SetColor Foreground Vivid color] ++ str ++ setSGRCode [Reset] ppDiff :: ColorEnable -> Diff String -> String ppDiff c (First x) = wrap c Red $ '-':x ppDiff c (Second x) = wrap c Green $ '+':x ppDiff _ (Both x _) = ' ':x git-mediate-1.0.9/src/Resolution.hs0000644000000000000000000001053507346545000015375 0ustar0000000000000000{-# LANGUAGE NoImplicitPrelude, BangPatterns, DerivingVia, DeriveGeneric, OverloadedRecordDot #-} module Resolution ( Result(..) , NewContent(..) , Untabify(..) , resolveContent , fullySuccessful ) where import Conflict (Conflict(..), Sides(..)) import qualified Conflict import Data.Foldable (Foldable(..)) import Generic.Data (Generic, Generically(..)) import Prelude.Compat data Resolution = NoResolution | Resolution String | PartialResolution String resolveGen :: Eq a => Sides a -> Maybe a resolveGen (Sides a base b) | a == base = Just b | b == base = Just a | a == b = Just a | otherwise = Nothing resolveConflict :: Conflict -> Resolution resolveConflict c = case resolveGen c.bodies of Just r -> Resolution $ unlines r Nothing | matchTop > 0 || matchBottom > 0 -> PartialResolution $ unlines $ take matchTop c.bodies.sideA ++ Conflict.prettyLines (Conflict.setEachBody unmatched c) ++ takeEnd matchBottom c.bodies.sideA | otherwise -> NoResolution where match base a b | null base = lengthOfCommonPrefix a b | otherwise = minimum $ map (lengthOfCommonPrefix base) [a, b] matchTop = match c.bodies.sideBase c.bodies.sideA c.bodies.sideB revBottom = reverse . drop matchTop matchBottom = match (revBottom c.bodies.sideBase) (revBottom c.bodies.sideA) (revBottom c.bodies.sideB) dropEnd count xs = take (length xs - count) xs takeEnd count xs = drop (length xs - count) xs unmatched xs = drop matchTop $ dropEnd matchBottom xs lengthOfCommonPrefix :: Eq a => [a] -> [a] -> Int lengthOfCommonPrefix x y = length $ takeWhile id $ zipWith (==) x y data Result = Result { resolvedSuccessfully :: !Int , reducedConflicts :: !Int , failedToResolve :: !Int } fullySuccessful :: Result -> Bool fullySuccessful (Result _ reduced failed) = reduced == 0 && failed == 0 instance Semigroup Result where Result x0 y0 z0 <> Result x1 y1 z1 = Result (x0+x1) (y0+y1) (z0+z1) instance Monoid Result where mempty = Result 0 0 0 data NewContent = NewContent { result :: !Result , newContent :: !String } deriving Generic deriving (Semigroup, Monoid) via Generically NewContent newtype Untabify = Untabify { mUntabifySize :: Maybe Int } untabifyStr :: Int -> String -> String untabifyStr size = go 0 where cyclicInc col | col >= size - 1 = 0 | otherwise = col + 1 go !col ('\t':rest) = replicate (size - col) ' ' ++ go 0 rest go !col (x:rest) = x : go (cyclicInc col) rest go _ [] = [] untabify :: Int -> Conflict -> Conflict untabify = Conflict.setStrings . untabifyStr data LineEnding = LF | CRLF | Mixed deriving (Eq, Ord) lineEnding :: String -> LineEnding lineEnding x@(_:_) | last x == '\r' = CRLF lineEnding _ = LF lineEndings :: [String] -> LineEnding lineEndings [] = Mixed lineEndings xs = foldl1 f (map lineEnding xs) where f Mixed _ = Mixed f x c | x == c = x | otherwise = Mixed allSame :: Eq a => [a] -> Bool allSame (x:y:rest) = x == y && allSame (y:rest) allSame _ = True lineBreakFix :: Conflict -> Conflict lineBreakFix c | any null (toList c.bodies) || allSame (toList endings) = c | otherwise = case resolveGen endings of Just LF -> Conflict.setStrings removeCr c Just CRLF -> Conflict.setStrings makeCr c _ -> c where endings = fmap lineEndings c.bodies removeCr x@(_:_) | last x == '\r' = init x removeCr x = x makeCr x@(_:_) | last x == '\r' = x makeCr x = x <> "\r" resolveContent :: Untabify -> [Either String Conflict] -> NewContent resolveContent (Untabify mTabSize) = foldMap go where untabified = maybe id untabify mTabSize go (Left line) = NewContent mempty (unlines [line]) go (Right conflict) = case (resolveConflict . lineBreakFix . untabified) conflict of NoResolution -> NewContent (Result 0 0 1) (Conflict.pretty (untabified conflict)) Resolution trivialLines -> NewContent (Result 1 0 0) trivialLines PartialResolution newLines -> NewContent (Result 0 1 0) newLines git-mediate-1.0.9/src/SideDiff.hs0000644000000000000000000000170707346545000014710 0ustar0000000000000000{-# LANGUAGE NoImplicitPrelude, OverloadedRecordDot #-} module SideDiff ( SideDiff(..), Side(..) , getConflictDiffs, getConflictDiff2s ) where import Conflict (Conflict(..), Sides(..), SrcContent(..)) import Data.Algorithm.Diff (Diff, getDiff) import Prelude.Compat data Side = A | B deriving (Eq, Ord, Show) data SideDiff = SideDiff { side :: Side , marker :: SrcContent , diff :: [Diff String] } getConflictDiffs :: Conflict -> [SideDiff] getConflictDiffs c = [ SideDiff A c.markers.sideA (getDiff c.bodies.sideBase c.bodies.sideA) | not (null c.bodies.sideA) ] ++ [ SideDiff B (SrcContent c.markers.sideB.lineNo c.markerEnd.content) (getDiff c.bodies.sideBase c.bodies.sideB) | not (null c.bodies.sideB) ] getConflictDiff2s :: Conflict -> (SrcContent, SrcContent, [Diff String]) getConflictDiff2s c = (c.markers.sideA, c.markers.sideB, getDiff c.bodies.sideA c.bodies.sideB) git-mediate-1.0.9/src/StrUtils.hs0000644000000000000000000000120107346545000015011 0ustar0000000000000000{-# LANGUAGE NoImplicitPrelude #-} module StrUtils ( stripNewline, ensureNewline, unprefix ) where import Data.List (isPrefixOf, isSuffixOf) import Prelude.Compat stripNewline :: String -> String stripNewline x | "\n" `isSuffixOf` x = init x | otherwise = x ensureNewline :: String -> String ensureNewline "" = "" ensureNewline str = str ++ suffix where suffix | "\n" `isSuffixOf` str = "" | otherwise = "\n" unprefix :: Eq a => [a] -> [a] -> Maybe [a] unprefix prefix str | prefix `isPrefixOf` str = Just (drop (length prefix) str) | otherwise = Nothing git-mediate-1.0.9/src/Version.hs0000644000000000000000000000032607346545000014654 0ustar0000000000000000-- | Expose cabal package version as a string module Version (versionString) where import Paths_git_mediate (version) import Data.Version (showVersion) versionString :: String versionString = showVersion version git-mediate-1.0.9/stack.yaml0000644000000000000000000000005507346545000014074 0ustar0000000000000000flags: {} packages: - '.' resolver: lts-21.3