    -- Copyright (C) 2002-2005,2007 David Roundy
    --
    -- 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, 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; see the file COPYING.  If not, write to
    -- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    -- Boston, MA 02110-1301, USA.

    {-# OPTIONS_GHC -cpp #-}
    {-# LANGUAGE CPP #-}

    #include "gadts.h"

    module Darcs.Repository.ApplyPatches ( apply_patches, apply_patches_with_feedback ) where

    import Darcs.Patch ( Patchy, apply )
    import Darcs.Hopefully ( PatchInfoAnd, hopefully, info )
    import Darcs.Patch.Info ( human_friendly )
    import Darcs.Witnesses.Ordered ( FL(..), lengthFL, mapFL )
    import Darcs.Flags ( DarcsFlag )
    import Darcs.Utils ( putDocLnError )
    import Progress ( beginTedious, endTedious, tediousSize, finishedOneIO )
    import Printer ( text )

    apply_patches_with_feedback :: Patchy p => [DarcsFlag] -> String -> FL (PatchInfoAnd p) C(x y) -> IO ()
    apply_patches_with_feedback _ _ NilFL = return ()
    apply_patches_with_feedback opts k patches =
        do beginTedious k
           tediousSize k (lengthFL patches)
           sequence_ $ mapFL apply_cautiously patches
           endTedious k
        where apply_cautiously :: Patchy p => PatchInfoAnd p C(a b) -> IO ()
              apply_cautiously hp =
                 do finishedOneIO k (show $ human_friendly $ info hp)
                    apply opts (hopefully hp) `catch` \e ->
                      do putDocLnError $ text "Unapplicable patch:"
                         putDocLnError $ human_friendly (info hp)
                         ioError e

    apply_patches :: Patchy p => [DarcsFlag] -> FL (PatchInfoAnd p) C(x y) -> IO ()
    apply_patches opts ps = apply_patches_with_feedback opts "Applying patch" ps