git-annex/Command/Sync.hs

451 lines
14 KiB
Haskell
Raw Normal View History

{- git-annex command
-
2011-12-30 20:24:30 +00:00
- Copyright 2011 Joachim Breitner <mail@joachim-breitner.de>
- Copyright 2011,2012 Joey Hess <joey@kitenet.net>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Command.Sync where
import Common.Annex
import Command
import qualified Remote
import qualified Annex
import qualified Annex.Branch
import qualified Annex.Queue
2012-12-12 23:20:38 +00:00
import Annex.Direct
import Annex.CatFile
fully support core.symlinks=false in all relevant symlink handling code Refactored annex link code into nice clean new library. Audited and dealt with calls to createSymbolicLink. Remaining calls are all safe, because: Annex/Link.hs: ( liftIO $ createSymbolicLink linktarget file only when core.symlinks=true Assistant/WebApp/Configurators/Local.hs: createSymbolicLink link link test if symlinks can be made Command/Fix.hs: liftIO $ createSymbolicLink link file command only works in indirect mode Command/FromKey.hs: liftIO $ createSymbolicLink link file command only works in indirect mode Command/Indirect.hs: liftIO $ createSymbolicLink l f refuses to run if core.symlinks=false Init.hs: createSymbolicLink f f2 test if symlinks can be made Remote/Directory.hs: go [file] = catchBoolIO $ createSymbolicLink file f >> return True fast key linking; catches failure to make symlink and falls back to copy Remote/Git.hs: liftIO $ catchBoolIO $ createSymbolicLink loc file >> return True ditto Upgrade/V1.hs: liftIO $ createSymbolicLink link f v1 repos could not be on a filesystem w/o symlinks Audited and dealt with calls to readSymbolicLink. Remaining calls are all safe, because: Annex/Link.hs: ( liftIO $ catchMaybeIO $ readSymbolicLink file only when core.symlinks=true Assistant/Threads/Watcher.hs: ifM ((==) (Just link) <$> liftIO (catchMaybeIO $ readSymbolicLink file)) code that fixes real symlinks when inotify sees them It's ok to not fix psdueo-symlinks. Assistant/Threads/Watcher.hs: mlink <- liftIO (catchMaybeIO $ readSymbolicLink file) ditto Command/Fix.hs: stopUnless ((/=) (Just link) <$> liftIO (catchMaybeIO $ readSymbolicLink file)) $ do command only works in indirect mode Upgrade/V1.hs: getsymlink = takeFileName <$> readSymbolicLink file v1 repos could not be on a filesystem w/o symlinks Audited and dealt with calls to isSymbolicLink. (Typically used with getSymbolicLinkStatus, but that is just used because getFileStatus is not as robust; it also works on pseudolinks.) Remaining calls are all safe, because: Assistant/Threads/SanityChecker.hs: | isSymbolicLink s -> addsymlink file ms only handles staging of symlinks that were somehow not staged (might need to be updated to support pseudolinks, but this is only a belt-and-suspenders check anyway, and I've never seen the code run) Command/Add.hs: if isSymbolicLink s || not (isRegularFile s) avoids adding symlinks to the annex, so not relevant Command/Indirect.hs: | isSymbolicLink s -> void $ flip whenAnnexed f $ only allowed on systems that support symlinks Command/Indirect.hs: whenM (liftIO $ not . isSymbolicLink <$> getSymbolicLinkStatus f) $ do ditto Seek.hs:notSymlink f = liftIO $ not . isSymbolicLink <$> getSymbolicLinkStatus f used to find unlocked files, only relevant in indirect mode Utility/FSEvents.hs: | Files.isSymbolicLink s = runhook addSymlinkHook $ Just s Utility/FSEvents.hs: | Files.isSymbolicLink s -> Utility/INotify.hs: | Files.isSymbolicLink s -> Utility/INotify.hs: checkfiletype Files.isSymbolicLink addSymlinkHook f Utility/Kqueue.hs: | Files.isSymbolicLink s = callhook addSymlinkHook (Just s) change all above are lower-level, not relevant Audited and dealt with calls to isSymLink. Remaining calls are all safe, because: Annex/Direct.hs: | isSymLink (getmode item) = This is looking at git diff-tree objects, not files on disk Command/Unused.hs: | isSymLink (LsTree.mode l) = do This is looking at git ls-tree, not file on disk Utility/FileMode.hs:isSymLink :: FileMode -> Bool Utility/FileMode.hs:isSymLink = checkMode symbolicLinkMode low-level Done!!
2013-02-17 19:05:55 +00:00
import Annex.Link
2011-12-14 19:56:11 +00:00
import qualified Git.Command
import qualified Git.LsFiles as LsFiles
import qualified Git.Merge
import qualified Git.Branch
import qualified Git.Ref
import qualified Git
import Git.Types (BlobType(..))
import qualified Types.Remote
import qualified Remote.Git
import Types.Key
import Config
import Annex.ReplaceFile
import Git.FileMode
import qualified Data.Set as S
import Data.Hash.MD5
import Control.Concurrent.MVar
def :: [Command]
def = [command "sync" (paramOptional (paramRepeating paramRemote))
[seek] SectionCommon "synchronize local repository with remotes"]
2011-12-31 06:18:16 +00:00
-- syncing involves several operations, any of which can independently fail
seek :: CommandSeek
seek rs = do
prepMerge
-- There may not be a branch checked out until after the commit,
-- or perhaps after it gets merged from the remote.
-- So only look it up once it's needed, and if once there is a
-- branch, cache it.
mvar <- liftIO newEmptyMVar
let getbranch = ifM (liftIO $ isEmptyMVar mvar)
( do
branch <- inRepo Git.Branch.current
when (isJust branch) $
liftIO $ putMVar mvar branch
return branch
, liftIO $ readMVar mvar
)
let withbranch a = a =<< getbranch
remotes <- syncRemotes rs
2012-02-16 04:41:30 +00:00
return $ concat
2011-12-30 21:54:09 +00:00
[ [ commit ]
, [ withbranch mergeLocal ]
, [ withbranch (pullRemote remote) | remote <- remotes ]
2011-12-30 21:54:09 +00:00
, [ mergeAnnex ]
, [ withbranch pushLocal ]
, [ withbranch (pushRemote remote) | remote <- remotes ]
2011-12-30 21:54:09 +00:00
]
2011-12-30 20:24:30 +00:00
{- Merging may delete the current directory, so go to the top
- of the repo. -}
prepMerge :: Annex ()
prepMerge = liftIO . setCurrentDirectory =<< fromRepo Git.repoPath
syncBranch :: Git.Ref -> Git.Ref
syncBranch = Git.Ref.under "refs/heads/synced" . fromDirectBranch
2011-12-31 08:11:39 +00:00
remoteBranch :: Remote -> Git.Ref -> Git.Ref
remoteBranch remote = Git.Ref.underBase $ "refs/remotes/" ++ Remote.name remote
2011-12-31 07:01:18 +00:00
2011-12-31 08:11:39 +00:00
syncRemotes :: [String] -> Annex [Remote]
syncRemotes rs = ifM (Annex.getState Annex.fast) ( nub <$> pickfast , wanted )
2012-11-12 05:05:04 +00:00
where
pickfast = (++) <$> listed <*> (good =<< fastest <$> available)
wanted
| null rs = good =<< concat . Remote.byCost <$> available
| otherwise = listed
listed = do
l <- catMaybes <$> mapM (Remote.byName . Just) rs
2013-09-09 13:58:17 +00:00
let s = filter (not . Remote.syncableRemote) l
2012-11-12 05:05:04 +00:00
unless (null s) $
error $ "cannot sync special remotes: " ++
unwords (map Types.Remote.name s)
return l
2013-09-09 13:58:17 +00:00
available = filter Remote.syncableRemote
. filter (remoteAnnexSync . Types.Remote.gitconfig)
<$> Remote.remoteList
2012-11-12 05:05:04 +00:00
good = filterM $ Remote.Git.repoAvail . Types.Remote.repo
fastest = fromMaybe [] . headMaybe . Remote.byCost
2011-12-10 16:21:22 +00:00
commit :: CommandStart
2013-09-25 07:09:06 +00:00
commit = next $ next $ ifM isDirect
( do
void stageDirect
runcommit []
, runcommit [Param "-a"]
)
2012-12-12 23:20:38 +00:00
where
runcommit ps = do
showStart "commit" ""
2011-12-10 16:21:22 +00:00
showOutput
2012-12-13 19:58:38 +00:00
Annex.Branch.commit "update"
2011-12-10 16:21:22 +00:00
-- Commit will fail when the tree is clean, so ignore failure.
2013-09-25 07:09:06 +00:00
let params = Param "commit" : ps ++
2012-12-12 23:20:38 +00:00
[Param "-m", Param "git-annex automatic sync"]
_ <- inRepo $ tryIO . Git.Command.runQuiet params
2011-12-10 16:21:22 +00:00
return True
mergeLocal :: Maybe Git.Ref -> CommandStart
mergeLocal Nothing = stop
mergeLocal (Just branch) = go =<< needmerge
2012-11-12 05:05:04 +00:00
where
syncbranch = syncBranch branch
needmerge = ifM isBareRepo
( return False
, do
unlessM (inRepo $ Git.Ref.exists syncbranch) $
inRepo $ updateBranch syncbranch
inRepo $ Git.Branch.changed branch syncbranch
)
2012-11-12 05:05:04 +00:00
go False = stop
go True = do
showStart "merge" $ Git.Ref.describe syncbranch
next $ next $ mergeFrom syncbranch
pushLocal :: Maybe Git.Ref -> CommandStart
pushLocal Nothing = stop
pushLocal (Just branch) = do
-- Update the sync branch to match the new state of the branch
inRepo $ updateBranch $ syncBranch branch
-- In direct mode, we're operating on some special direct mode
-- branch, rather than the intended branch, so update the indended
-- branch.
whenM isDirect $
inRepo $ updateBranch $ fromDirectBranch branch
stop
2011-12-30 22:52:24 +00:00
updateBranch :: Git.Ref -> Git.Repo -> IO ()
updateBranch syncbranch g =
2011-12-30 22:52:24 +00:00
unlessM go $ error $ "failed to update " ++ show syncbranch
2012-11-12 05:05:04 +00:00
where
go = Git.Command.runBool
[ Param "branch"
, Param "-f"
2012-11-12 05:05:04 +00:00
, Param $ show $ Git.Ref.base syncbranch
] g
2011-12-30 21:38:38 +00:00
pullRemote :: Remote -> Maybe Git.Ref -> CommandStart
pullRemote remote branch = do
showStart "pull" (Remote.name remote)
2011-12-30 21:38:38 +00:00
next $ do
showOutput
stopUnless fetch $
next $ mergeRemote remote branch
2012-11-12 05:05:04 +00:00
where
fetch = inRepo $ Git.Command.runBool
[Param "fetch", Param $ Remote.name remote]
{- The remote probably has both a master and a synced/master branch.
- Which to merge from? Well, the master has whatever latest changes
- were committed (or pushed changes, if this is a bare remote),
- while the synced/master may have changes that some
- other remote synced to this remote. So, merge them both. -}
2013-09-25 07:09:06 +00:00
mergeRemote :: Remote -> Maybe Git.Ref -> CommandCleanup
mergeRemote remote b = case b of
Nothing -> do
branch <- inRepo Git.Branch.currentUnsafe
2013-09-25 07:09:06 +00:00
and <$> mapM merge (branchlist branch)
Just _ -> and <$> (mapM merge =<< tomerge (branchlist b))
2012-11-12 05:05:04 +00:00
where
merge = mergeFrom . remoteBranch remote
tomerge branches = filterM (changed remote) branches
branchlist Nothing = []
branchlist (Just branch) = [branch, syncBranch branch]
pushRemote :: Remote -> Maybe Git.Ref -> CommandStart
pushRemote _remote Nothing = stop
pushRemote remote (Just branch) = go =<< needpush
2012-11-12 05:05:04 +00:00
where
needpush = anyM (newer remote) [syncBranch branch, Annex.Branch.name]
go False = stop
go True = do
showStart "push" (Remote.name remote)
next $ next $ do
showOutput
ok <- inRepo $ pushBranch remote branch
unless ok $ do
warning $ unwords [ "Pushing to " ++ Remote.name remote ++ " failed." ]
2013-11-01 15:04:19 +00:00
showLongNote "(non-fast-forward problems can be solved by setting receive.denyNonFastforwards to false in the remote's git config)"
return ok
{- Pushes a regular branch like master to a remote. Also pushes the git-annex
- branch.
-
- If the remote is a bare git repository, it's best to push the regular
- branch directly to it, so that cloning/pulling will get it.
- On the other hand, if it's not bare, pushing to the checked out branch
- will fail, and this is why we push to its syncBranch.
-
- Git offers no way to tell if a remote is bare or not, so both methods
- are tried.
-
- The direct push is likely to spew an ugly error message, so stderr is
- elided. Since git progress display goes to stderr too, the sync push
- is done first, and actually sends the data. Then the direct push is
- tried, with stderr discarded, to update the branch ref on the remote.
-
- The sync push forces the update of the remote synced/git-annex branch.
- This is necessary if a transition has rewritten the git-annex branch.
- Normally any changes to the git-annex branch get pulled and merged before
- this push, so this forcing is unlikely to overwrite new data pushed
- in from another repository that is also syncing.
-
- But overwriting of data on synced/git-annex can happen, in a race.
- The only difference caused by using a forced push in that case is that
- the last repository to push wins the race, rather than the first to push.
-
- The sync push will fail to overwrite if receive.denyNonFastforwards is
- set on the remote.
-}
pushBranch :: Remote -> Git.Ref -> Git.Repo -> IO Bool
pushBranch remote branch g = tryIO (directpush g) `after` syncpush g
where
syncpush = Git.Command.runBool $ pushparams
[ Git.Branch.forcePush $ refspec Annex.Branch.name
, refspec branch
]
directpush = Git.Command.runQuiet $ pushparams
[show $ Git.Ref.base $ fromDirectBranch branch]
pushparams branches =
[ Param "push"
, Param $ Remote.name remote
] ++ map Param branches
2012-11-12 05:05:04 +00:00
refspec b = concat
[ show $ Git.Ref.base b
, ":"
, show $ Git.Ref.base $ syncBranch b
]
mergeAnnex :: CommandStart
2011-12-30 21:38:38 +00:00
mergeAnnex = do
2013-09-25 07:09:06 +00:00
void Annex.Branch.forceUpdate
2011-12-30 21:38:38 +00:00
stop
2011-12-31 06:18:16 +00:00
{- Merges from a branch into the current branch. -}
mergeFrom :: Git.Ref -> Annex Bool
mergeFrom branch = do
showOutput
ifM isDirect
( maybe go godirect =<< inRepo Git.Branch.current
, go
)
where
go = runmerge $ inRepo $ Git.Merge.mergeNonInteractive branch
godirect currbranch = do
old <- inRepo $ Git.Ref.sha currbranch
d <- fromRepo gitAnnexMergeDir
r <- runmerge $ inRepo $ mergeDirect d branch
new <- inRepo $ Git.Ref.sha currbranch
case (old, new) of
(Just oldsha, Just newsha) ->
mergeDirectCleanup d oldsha newsha
_ -> noop
return r
2013-09-25 07:09:06 +00:00
runmerge a = ifM a
( return True
, resolveMerge
)
{- Resolves a conflicted merge. It's important that any conflicts be
- resolved in a way that itself avoids later merge conflicts, since
- multiple repositories may be doing this concurrently.
-
- Only annexed files are resolved; other files are left for the user to
- handle.
-
- This uses the Keys pointed to by the files to construct new
- filenames. So when both sides modified file foo,
- it will be deleted, and replaced with files foo.variant-A and
- foo.variant-B.
-
- On the other hand, when one side deleted foo, and the other modified it,
- it will be deleted, and the modified version stored as file
- foo.variant-A (or B).
-
- It's also possible that one side has foo as an annexed file, and
- the other as a directory or non-annexed file. The annexed file
- is renamed to resolve the merge, and the other object is preserved as-is.
-}
resolveMerge :: Annex Bool
resolveMerge = do
top <- fromRepo Git.repoPath
(fs, cleanup) <- inRepo (LsFiles.unmerged [top])
mergedfs <- catMaybes <$> mapM resolveMerge' fs
let merged = not (null mergedfs)
void $ liftIO cleanup
(deleted, cleanup2) <- inRepo (LsFiles.deleted [top])
2013-02-05 19:11:05 +00:00
unless (null deleted) $
Annex.Queue.addCommand "rm" [Params "--quiet -f --"] deleted
void $ liftIO cleanup2
when merged $ do
unlessM isDirect $
cleanConflictCruft mergedfs top
Annex.Queue.flush
void $ inRepo $ Git.Command.runBool
[ Param "commit"
, Param "-m"
, Param "git-annex automatic merge conflict fix"
]
showLongNote "Merge conflict was automatically resolved; you may want to examine the result."
return merged
resolveMerge' :: LsFiles.Unmerged -> Annex (Maybe FilePath)
resolveMerge' u
| issymlink LsFiles.valUs && issymlink LsFiles.valThem = do
kus <- getKey LsFiles.valUs
kthem <- getKey LsFiles.valThem
case (kus, kthem) of
-- Both sides of conflict are annexed files
(Just keyUs, Just keyThem) -> do
removeoldfile keyUs
if keyUs == keyThem
then makelink keyUs
else do
makelink keyUs
makelink keyThem
return $ Just file
-- Our side is annexed, other side is not.
(Just keyUs, Nothing) -> do
ifM isDirect
-- Move newly added non-annexed object
-- out of direct mode merge directory.
( do
removeoldfile keyUs
makelink keyUs
d <- fromRepo gitAnnexMergeDir
liftIO $ rename (d </> file) file
-- cleaup tree after git merge
, do
unstageoldfile
makelink keyUs
)
return $ Just file
-- Our side is not annexed, other side is.
(Nothing, Just keyThem) -> do
makelink keyThem
unstageoldfile
return $ Just file
-- Neither side is annexed; cannot resolve.
(Nothing, Nothing) -> return Nothing
| otherwise = return Nothing
2012-11-12 05:05:04 +00:00
where
file = LsFiles.unmergedFile u
2013-09-25 07:09:06 +00:00
issymlink select = select (LsFiles.unmergedBlobType u) `elem` [Just SymlinkBlob, Nothing]
makelink key = do
2012-11-12 05:05:04 +00:00
let dest = mergeFile file key
l <- inRepo $ gitAnnexLink dest key
replaceFile dest $ makeAnnexLink l
stageSymlink dest =<< hashSymlink l
2013-09-25 07:09:06 +00:00
whenM isDirect $
toDirect key dest
removeoldfile keyUs = do
ifM isDirect
( removeDirect keyUs file
, liftIO $ nukeFile file
)
Annex.Queue.addCommand "rm" [Params "--quiet -f --"] [file]
unstageoldfile = Annex.Queue.addCommand "rm" [Params "--quiet -f --cached --"] [file]
getKey select = case select (LsFiles.unmergedSha u) of
Nothing -> return Nothing
Just sha -> catKey sha symLinkMode
{- git-merge moves conflicting files away to files
- named something like f~HEAD or f~branch, but the
- exact name chosen can vary. Once the conflict is resolved,
- this cruft can be deleted. To avoid deleting legitimate
- files that look like this, only delete files that are
- A) not staged in git and B) look like git-annex symlinks.
-}
cleanConflictCruft :: [FilePath] -> FilePath -> Annex ()
cleanConflictCruft resolvedfs top = do
(fs, cleanup) <- inRepo $ LsFiles.notInRepo False [top]
mapM_ clean fs
void $ liftIO cleanup
where
clean f
| matchesresolved f = whenM (isJust <$> isAnnexLink f) $
liftIO $ nukeFile f
| otherwise = noop
s = S.fromList resolvedfs
matchesresolved f = S.member (base f) s
base f = reverse $ drop 1 $ dropWhile (/= '~') $ reverse f
{- The filename to use when resolving a conflicted merge of a file,
- that points to a key.
-
- Something derived from the key needs to be included in the filename,
- but rather than exposing the whole key to the user, a very weak hash
- is used. There is a very real, although still unlikely, chance of
- conflicts using this hash.
-
- In the event that there is a conflict with the filename generated
- for some other key, that conflict will itself be handled by the
- conflicted merge resolution code. That case is detected, and the full
- key is used in the filename.
-}
mergeFile :: FilePath -> Key -> FilePath
mergeFile file key
| doubleconflict = go $ key2file key
| otherwise = go $ shortHash $ key2file key
2012-11-12 05:05:04 +00:00
where
varmarker = ".variant-"
doubleconflict = varmarker `isInfixOf` file
2012-11-12 05:05:04 +00:00
go v = takeDirectory file
</> dropExtension (takeFileName file)
++ varmarker ++ v
++ takeExtension file
shortHash :: String -> String
2012-09-13 23:14:00 +00:00
shortHash = take 4 . md5s . md5FilePath
2011-12-31 07:01:18 +00:00
2011-12-31 08:11:39 +00:00
changed :: Remote -> Git.Ref -> Annex Bool
2011-12-31 07:01:18 +00:00
changed remote b = do
let r = remoteBranch remote b
ifM (inRepo $ Git.Ref.exists r)
( inRepo $ Git.Branch.changed b r
, return False
)
2011-12-31 07:01:18 +00:00
2011-12-31 08:11:39 +00:00
newer :: Remote -> Git.Ref -> Annex Bool
2011-12-31 07:01:18 +00:00
newer remote b = do
let r = remoteBranch remote b
ifM (inRepo $ Git.Ref.exists r)
( inRepo $ Git.Branch.changed r b
, return True
)