% Copyright (C) 2002-2004 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. \subsection{darcs send} \begin{code} {-# OPTIONS_GHC -cpp #-} module Darcs.Commands.Send ( send ) where import System.Exit ( exitWith, ExitCode( ExitSuccess ) ) import System.IO.Error ( ioeGetErrorString ) import System.IO ( hClose ) import Control.Monad ( when, unless, liftM, guard, mplus ) import Data.Maybe (isJust, isNothing ) import Darcs.Commands ( DarcsCommand(..) ) import Darcs.Arguments ( DarcsFlag( EditDescription, LogFile, RmLogFile, Target, OutputAutoName, Output, Context, DryRun, Verbose, Quiet ), fix_filepath, definePatches, get_cc, get_author, working_repo_dir, edit_description, logfile, rmlogfile, sign, get_subject, no_deps, match_several, set_default, output_auto_name, output, cc, subject, target, author, sendmail_cmd, remote_repo, ssh_cm, all_interactive, get_sendmail_cmd, print_dry_run_message_and_exit, summary, from_opt, dry_run, send_to_context, ) import Darcs.Hopefully ( PatchInfoAnd, hopefully, info ) import Darcs.Repository ( PatchSet, Repository, amInRepository, identifyRepositoryFor, withRepoReadLock, ($-), read_repo, slurp_recorded, prefsUrl ) import Darcs.Patch ( RepoPatch, description, apply_to_slurpy, invert ) import Darcs.Patch.Ordered ( FL(..), RL(..), (:>)(..), (:\/:)(..), unsafeUnRL, mapRL_RL, mapFL, mapRL, reverseRL, mapFL_FL, lengthFL, nullFL ) import Darcs.Patch.Bundle ( make_bundle, scan_context ) import Darcs.Patch.Info ( just_name ) import Darcs.Repository.Prefs ( defaultrepo, set_defaultrepo, get_preflist ) import Darcs.External ( signString, sendEmailDoc, fetchFilePS, Cachable(..), generateEmail ) import FastPackedString ( unpackPS, mmapFilePS ) import Darcs.Lock ( withOpenTemp, writeDocBinFile, readDocBinFile, world_readable_temp, removeFileMayNotExist ) import Darcs.SelectChanges ( with_selected_changes ) import Darcs.Patch.Depends ( get_common_and_uncommon ) import Darcs.Utils ( askUser, catchall, edit_file, formatPath ) import Darcs.Progress ( debugMessage ) import Darcs.Email ( make_email ) import Printer ( Doc, vsep, vcat, text, ($$), putDocLn, putDoc ) import FileName ( patch_filename ) import Darcs.RepoPath ( toPath ) import Darcs.Sealed ( Sealed(..) ) import qualified HTTP #include "impossible.h" \end{code} \begin{code} send_description :: String send_description = "Send by email a bundle of one or more patches." \end{code} \options{send} \haskell{send_help} \begin{code} send_help :: String send_help = "Send is used to prepare a bundle of patches that can be applied to a target\n"++ "repository. Send accepts the URL of the repository as an argument. When\n"++ "called without an argument, send will use the most recent repository that\n"++ "was either pushed to, pulled from or sent to. By default, the patch bundle\n"++ "is sent by email, although you may save it to a file.\n" \end{code} Do not confuse the \verb!--author! options with the return address that \verb!darcs send! will set for your patch bundle. For example, if you have two email addresses A and B: \begin{description} \item If you use \verb!--author A! but your machine is configured to send mail from address B by default, then the return address on your message will be B. \item If you use \verb!--from A! and your mail client supports setting the From: address arbitrarily (some non-Unix-like mail clients, especially, may not support this), then the return address will be A; if it does not support this, then the return address will be B. \item If you supply neither \verb!--from! nor \verb!--author!, then the return address will be B. \end{description} In addition, unless you specify the sendmail command with \verb!--sendmail-command!, darcs sends email using the default email command on your computer. This default command is determined by the \verb!configure! script. Thus, on some non-Unix-like OSes, \verb!--from! is likely to not work at all. \begin{code} send :: DarcsCommand send = DarcsCommand {command_name = "send", command_help = send_help, command_description = send_description, command_extra_args = 1, command_extra_arg_help = ["[REPOSITORY]"], command_command = send_cmd, command_prereq = amInRepository, command_get_arg_possibilities = get_preflist "repos", command_argdefaults = defaultrepo, command_advanced_options = [logfile, rmlogfile, remote_repo, send_to_context, ssh_cm], command_basic_options = [match_several, no_deps, all_interactive, from_opt, author, target,cc,subject, output,output_auto_name,sign] ++dry_run++[summary, edit_description, set_default, working_repo_dir, sendmail_cmd]} \end{code} \begin{code} send_cmd :: [DarcsFlag] -> [String] -> IO () send_cmd input_opts [""] = send_cmd input_opts [] send_cmd input_opts [unfixedrepodir] = withRepoReadLock input_opts $- \repository -> do context_ps <- the_context input_opts case context_ps of Just them -> send_to_them repository input_opts [] "CONTEXT" them Nothing -> do let repodir = toPath $ fix_filepath input_opts unfixedrepodir -- Test to make sure we aren't trying to push to the current repo when (repodir == "") $ fail ("Can't send to current repository! Did you mean send -"++"-context?") repo <- identifyRepositoryFor repository repodir Sealed them <- read_repo repo old_default <- defaultrepo input_opts "" [] set_defaultrepo repodir input_opts when (old_default == [repodir] && not (Quiet `elem` input_opts)) $ putStrLn $ "Creating patch to "++formatPath repodir++"..." wtds <- decide_on_behavior input_opts repo send_to_them repository input_opts wtds repodir them where the_context [] = return Nothing the_context (Context foo:_) = (Just . scan_context )`liftM` mmapFilePS foo the_context (_:fs) = the_context fs send_cmd _ _ = impossible send_to_them :: RepoPatch p => Repository p -> [DarcsFlag] -> [WhatToDo] -> String -> PatchSet p -> IO () send_to_them repo opts wtds their_name them = do let am_verbose = Verbose `elem` opts am_quiet = Quiet `elem` opts putVerbose s = when am_verbose $ putDocLn s putInfo s = when (not am_quiet) $ putStrLn s patch_desc p = just_name $ info p make_fname tbs = patch_filename $ patch_desc $ headFL tbs headFL (x:>:_) = x headFL _ = impossible Sealed us <- read_repo repo case get_common_and_uncommon (us, them) of (common, us' :\/: _) -> do putVerbose $ text "We have the following patches to send:" $$ (vcat $ mapRL description $ head $ unsafeUnRL us') case us' of NilRL:<:NilRL -> do putInfo "No recorded local changes to send!" exitWith ExitSuccess _ -> return () s <- slurp_recorded repo let our_ps = reverseRL $ head $ unsafeUnRL us' with_selected_changes "send" opts s our_ps $ \ (to_be_sent :> _) -> do print_dry_run_message_and_exit "send" opts to_be_sent when (nullFL to_be_sent) $ do putInfo "You don't want to send any patches, and that's fine with me!" exitWith ExitSuccess definePatches to_be_sent bundle <- signString opts $ make_bundle opts (fromJust $ apply_to_slurpy (invert $ mapRL_RL hopefully $ head $ unsafeUnRL us') s) common (mapFL_FL hopefully to_be_sent) let outname = get_output opts `mplus` (do guard (OutputAutoName `elem` opts); return $ make_fname to_be_sent) case outname of Just fname -> do (d,f) <- get_description opts to_be_sent if fname == "-" then putDoc (d $$ bundle) else writeDocBinFile fname (d $$ bundle) cleanup f putStrLn $ "Wrote patch to " ++ fname ++ "." Nothing -> let auto_subject (p:>:NilFL) = "darcs patch: " ++ trim (patch_desc p) 57 auto_subject (p:>:ps) = "darcs patch: " ++ trim (patch_desc p) 43 ++ " (and " ++ show (lengthFL ps) ++ " more)" auto_subject _ = error "Tried to get a name from empty patch list." trim st n = if length st <= n then st else take (n-3) st ++ "..." in do thetargets <- get_targets wtds from <- get_author opts let thesubject = case get_subject opts of Nothing -> auto_subject to_be_sent Just subj -> subj (mailcontents, mailfile) <- get_description opts to_be_sent let body = make_email their_name (Just mailcontents) bundle (Just $ make_fname to_be_sent) contentAndBundle = Just (mailcontents, bundle) (sendEmailDoc from (lt [t | SendMail t <- thetargets]) (thesubject) (get_cc opts) (get_sendmail_cmd opts) contentAndBundle body) `catch` \e -> let msg = "Email body left in " in do when (isJust mailfile) $ putStrLn $ msg ++ (fromJust mailfile) ++ "." fail $ ioeGetErrorString e cleanup mailfile nbody <- withOpenTemp $ \ (fh,fn) -> do generateEmail fh from (lt [t | SendMail t <- thetargets]) thesubject (get_cc opts) body hClose fh mmapFilePS fn putInfo $ "Successfully sent patch bundle to: "++lt [ t | SendMail t <- thetargets ]++"." forM_ [ p | Post p <- thetargets] $ \url -> do putInfo $ "posting patch to " ++ url HTTP.postUrl url (unpackPS nbody) "message/rfc822" where cleanup (Just mailfile) = when (isNothing (get_fileopt opts) || (RmLogFile `elem` opts)) $ removeFileMayNotExist mailfile cleanup Nothing = return () lt [t] = t lt [t,""] = t lt (t:ts) = t++" , "++lt ts lt [] = "" \end{code} \begin{options} --output, --to, --cc \end{options} The \verb!--output!, \verb!--output-auto-name!, and \verb!--to! flags determine what darcs does with the patch bundle after creating it. If you provide an \verb!--output! argument, the patch bundle is saved to that file. If you specify \verb!--output-auto-name!, the patch bundle is saved to a file with an automatically generated name. If you give one or more \verb!--to! arguments, the bundle of patches is sent to those locations. The locations may either be email addresses or urls that the patch should be submitted to via HTTP. If you don't provide any of these options, darcs will look at the contents of the \verb!_darcs/prefs/email! file in the target repository (if it exists), and send the patch by email to that address. In this case, you may use the \verb!--cc! option to specify additional recipients without overriding the default repository email address. If there is no email address associated with the repository, darcs will prompt you for an email address. \begin{options} --subject \end{options} Use the \verb!--subject! flag to set the subject of the e-mail to be sent. If you don't provide a subject on the command line, darcs will make one up based on names of the patches in the patch bundle. \begin{code} forM_ :: (Monad m) => [a] -> (a -> m b) -> m () forM_ = (flip mapM_) data WhatToDo = Post String -- ^ POST the patch via HTTP | SendMail String -- ^ send patch via email decide_on_behavior :: RepoPatch p => [DarcsFlag] -> Repository p -> IO [WhatToDo] decide_on_behavior opts the_remote_repo = case the_targets of [] -> if (isJust $ get_output opts) || (OutputAutoName `elem` opts) then return [] else do wtds <- check_post unless (null wtds) $ announce_recipients wtds return wtds ts -> do announce_recipients ts return ts where the_targets = collect_targets opts check_post | HTTP.exists = ((readPost . unpackPS) `liftM` fetchFilePS (prefsUrl the_remote_repo++"/post") (MaxAge 600)) `catchall` who_to_email | otherwise = who_to_email who_to_email = do email <- (unpackPS `liftM` fetchFilePS (prefsUrl the_remote_repo++"/email") (MaxAge 600)) `catchall` return "" if '@' `elem` email then return . map SendMail $ lines email else return [] readPost p = map pp (lines p) where pp ('m':'a':'i':'l':'t':'o':':':s) = SendMail s pp s = Post s putInfoLn s = unless (Quiet `elem` opts) $ putStrLn s announce_recipients emails = let pn (SendMail s) = s pn (Post p) = p in if DryRun `elem` opts then putInfoLn $ "Patch bundle would be sent to: "++unwords (map pn emails) else when (null the_targets) $ putInfoLn $ "Patch bundle will be sent to: "++unwords (map pn emails) \end{code} \begin{code} get_output :: [DarcsFlag] -> Maybe String get_output (Output a:_) = return a get_output (_:flags) = get_output flags get_output [] = Nothing \end{code} \begin{code} get_targets :: [WhatToDo] -> IO [WhatToDo] get_targets [] = do liftM ((:[]) . SendMail) $ askUser "What is the target email address? " get_targets wtds = return wtds collect_targets :: [DarcsFlag] -> [WhatToDo] collect_targets flags = [ f t | Target t <- flags ] where f url@('h':'t':'t':'p':':':_) = Post url f em = SendMail em \end{code} \begin{options} --matches, --patches, --tags, --no-deps \end{options} The \verb!--patches!, \verb!--matches!, \verb!--tags!, and \verb!--no-deps! options can be used to select which patches to send, as described in subsection~\ref{selecting}. \begin{options} --edit-description \end{options} If you want to include a description or explanation along with the bundle of patches, you need to specify the \verb!--edit-description! flag, which will cause darcs to open up an editor with which you can compose a message to go along with your patches. \begin{options} --sendmail-command \end{options} If you want to use a command different from the default one for sending email, you need to specify a command line with the \verb!--sendmail-command! option. The command line can contain some format specifiers which are replaced by the actual values. Accepted format specifiers are \verb!%s! for subject, \verb!%t! for to, \verb!%c! for cc, \verb!%b! for the body of the mail, \verb!%f! for from, \verb!%a! for the patch bundle and the same specifiers in uppercase for the URL-encoded values. Additionally you can add \verb!% [DarcsFlag] -> FL (PatchInfoAnd p) -> IO (Doc, Maybe String) get_description opts patches = case get_filename of Just f -> do file <- f when (EditDescription `elem` opts) $ do when (isNothing $ get_fileopt opts) $ writeDocBinFile file patchdesc debugMessage $ "About to edit file " ++ file edit_file file return () doc <- readDocBinFile file return (doc, Just file) Nothing -> return (patchdesc, Nothing) where patchdesc = vsep $ mapFL description patches get_filename = case get_fileopt opts of Just f -> Just $ return f Nothing -> if EditDescription `elem` opts then Just tempfile else Nothing tempfile = world_readable_temp "darcs-temp-mail" get_fileopt :: [DarcsFlag] -> Maybe String get_fileopt (LogFile f:_) = Just f get_fileopt (_:flags) = get_fileopt flags get_fileopt [] = Nothing \end{code}