git-annex/Command/Unused.hs

255 lines
7.7 KiB
Haskell
Raw Normal View History

{- git-annex command
-
- Copyright 2010-2012 Joey Hess <joey@kitenet.net>
-
- Licensed under the GNU GPL version 3 or higher.
-}
{-# LANGUAGE BangPatterns #-}
module Command.Unused where
import qualified Data.Set as S
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Encoding as L
import Data.BloomFilter
import Data.BloomFilter.Easy
import Data.BloomFilter.Hash
2011-10-05 20:02:51 +00:00
import Common.Annex
import Command
2011-10-04 04:40:47 +00:00
import Annex.Content
import Utility.FileMode
2011-10-16 04:31:25 +00:00
import Utility.TempFile
2011-10-15 20:21:08 +00:00
import Logs.Location
2010-11-15 22:04:19 +00:00
import qualified Annex
import qualified Git
2011-12-14 19:56:11 +00:00
import qualified Git.Command
2011-12-12 22:23:24 +00:00
import qualified Git.Ref
import qualified Git.LsFiles as LsFiles
import qualified Git.LsTree as LsTree
import qualified Backend
2011-04-03 00:59:41 +00:00
import qualified Remote
2011-10-04 04:40:47 +00:00
import qualified Annex.Branch
2012-01-06 14:14:37 +00:00
import qualified Option
2011-10-04 04:40:47 +00:00
import Annex.CatFile
def :: [Command]
def = [withOptions [fromOption] $ command "unused" paramNothing seek
"look for unused file content"]
fromOption :: Option
2012-01-06 14:14:37 +00:00
fromOption = Option.field ['f'] "from" paramRemote "remote to check for unused content"
seek :: [CommandSeek]
2012-02-16 04:41:30 +00:00
seek = [withNothing start]
{- Finds unused content in the annex. -}
start :: CommandStart
start = do
2012-01-06 14:14:37 +00:00
from <- Annex.getField $ Option.name fromOption
let (name, action) = case from of
Nothing -> (".", checkUnused)
Just "." -> (".", checkUnused)
Just "here" -> (".", checkUnused)
Just n -> (n, checkRemoteUnused n)
showStart "unused" name
next action
genBloomFilter :: [Key] -> Annex (Bloom String)
genBloomFilter ks = do
-- A bloom filter capable of holding one million keys with a
-- false positive rate of 0.1% uses 16 mb of memory.
-- TODO: make this configurable, for the really large repos,
-- or really low false positive rates.
let (numbits, numhashes) = suggestSizing 1000000 0.0001
return $ fromListB (cheapHashes numhashes) numbits $ map show ks
bloomFilter :: Bloom String -> [Key] -> [Key]
bloomFilter b l = filter (\k -> show k `notElemB` b) l
checkUnused :: CommandPerform
2012-03-12 01:08:48 +00:00
checkUnused = chain 0
[ check "" unusedMsg $ findunused =<< Annex.getState Annex.fast
, check "bad" staleBadMsg $ staleKeysPrune gitAnnexBadDir
, check "tmp" staleTmpMsg $ staleKeysPrune gitAnnexTmpDir
]
where
findunused True = do
showNote "fast mode enabled; only finding stale files"
return []
findunused False = do
showAction "checking for unused data"
b <- genBloomFilter =<< withKeysReferenced [] (:)
bloomFilter b <$> getKeysPresent
-- TODO: check branches
2012-03-12 01:08:48 +00:00
chain _ [] = next $ return True
chain v (a:as) = do
v' <- a v
chain v' as
checkRemoteUnused :: String -> CommandPerform
2012-03-12 01:08:48 +00:00
checkRemoteUnused name = go =<< fromJust <$> Remote.byName (Just name)
where
go r = do
showAction "checking for unused data"
_ <- check "" (remoteUnusedMsg r) (remoteunused r) 0
next $ return True
remoteunused r =
excludeReferenced =<< loggedKeysFor (Remote.uuid r)
check :: FilePath -> ([(Int, Key)] -> String) -> Annex [Key] -> Int -> Annex Int
check file msg a c = do
l <- a
let unusedlist = number c l
unless (null l) $ showLongNote $ msg unusedlist
writeUnusedFile file unusedlist
return $ c + length l
2011-05-15 06:49:43 +00:00
2012-03-12 01:08:48 +00:00
number :: Int -> [a] -> [(Int, a)]
number _ [] = []
number n (x:xs) = (n+1, x) : number (n+1) xs
2011-04-03 00:59:41 +00:00
writeUnusedFile :: FilePath -> [(Int, Key)] -> Annex ()
writeUnusedFile prefix l = do
logfile <- fromRepo $ gitAnnexUnusedLog prefix
liftIO $ viaTmp writeFile logfile $
2011-04-03 00:59:41 +00:00
unlines $ map (\(n, k) -> show n ++ " " ++ show k) l
table :: [(Int, Key)] -> [String]
2011-07-15 16:47:14 +00:00
table l = " NUMBER KEY" : map cols l
where
cols (n,k) = " " ++ pad 6 (show n) ++ " " ++ show k
2010-11-15 22:04:19 +00:00
pad n s = s ++ replicate (n - length s) ' '
2011-04-03 00:59:41 +00:00
staleTmpMsg :: [(Int, Key)] -> String
staleTmpMsg t = unlines $
["Some partially transferred data exists in temporary files:"]
++ table t ++ [dropMsg Nothing]
staleBadMsg :: [(Int, Key)] -> String
staleBadMsg t = unlines $
["Some corrupted files have been preserved by fsck, just in case:"]
++ table t ++ [dropMsg Nothing]
2011-04-03 00:59:41 +00:00
unusedMsg :: [(Int, Key)] -> String
unusedMsg u = unusedMsg' u
["Some annexed data is no longer used by any files:"]
[dropMsg Nothing]
2011-04-03 00:59:41 +00:00
unusedMsg' :: [(Int, Key)] -> [String] -> [String] -> String
unusedMsg' u header trailer = unlines $
header ++
table u ++
["(To see where data was previously used, try: git log --stat -S'KEY')"] ++
trailer
2011-12-31 08:11:39 +00:00
remoteUnusedMsg :: Remote -> [(Int, Key)] -> String
remoteUnusedMsg r u = unusedMsg' u
["Some annexed data on " ++ name ++ " is not used by any files:"]
[dropMsg $ Just r]
where
name = Remote.name r
2011-12-31 08:11:39 +00:00
dropMsg :: Maybe Remote -> String
2011-04-03 00:59:41 +00:00
dropMsg Nothing = dropMsg' ""
dropMsg (Just r) = dropMsg' $ " --from " ++ Remote.name r
dropMsg' :: String -> String
dropMsg' s = "\nTo remove unwanted data: git-annex dropunused" ++ s ++ " NUMBER\n"
2011-04-03 00:59:41 +00:00
{- Finds keys in the list that are not referenced in the git repository. -}
excludeReferenced :: [Key] -> Annex [Key]
2011-09-28 21:38:41 +00:00
excludeReferenced [] = return [] -- optimisation
excludeReferenced l = do
let s = S.fromList l
!s' <- withKeysReferenced s S.delete
go s' =<< refs <$> (inRepo $ Git.Command.pipeRead [Param "show-ref"])
where
-- Skip the git-annex branches, and get all other unique refs.
refs = map (Git.Ref . snd) .
nubBy uniqref .
filter ourbranches .
support all filename encodings with ghc 7.4 Under ghc 7.4, this seems to be able to handle all filename encodings again. Including filename encodings that do not match the LANG setting. I think this will not work with earlier versions of ghc, it uses some ghc internals. Turns out that ghc 7.4 has a special filesystem encoding that it uses when reading/writing filenames (as FilePaths). This encoding is documented to allow "arbitrary undecodable bytes to be round-tripped through it". So, to get FilePaths from eg, git ls-files, set the Handle that is reading from git to use this encoding. Then things basically just work. However, I have not found a way to make Text read using this encoding. Text really does assume unicode. So I had to switch back to using String when reading/writing data to git. Which is a pity, because it's some percent slower, but at least it works. Note that stdout and stderr also have to be set to this encoding, or printing out filenames that contain undecodable bytes causes a crash. IMHO this is a misfeature in ghc, that the user can pass you a filename, which you can readFile, etc, but that default, putStr of filename may cause a crash! Git.CheckAttr gave me special trouble, because the filenames I got back from git, after feeding them in, had further encoding breakage. Rather than try to deal with that, I just zip up the input filenames with the attributes. Which must be returned in the same order queried for this to work. Also of note is an apparent GHC bug I worked around in Git.CheckAttr. It used to forkProcess and feed git from the child process. Unfortunatly, after this forkProcess, accessing the `files` variable from the parent returns []. Not the value that was passed into the function. This screams of a bad bug, that's clobbering a variable, but for now I just avoid forkProcess there to work around it. That forkProcess was itself only added because of a ghc bug, #624389. I've confirmed that the test case for that bug doesn't reproduce it with ghc 7.4. So that's ok, except for the new ghc bug I have not isolated and reported. Why does this simple bit of code magnet the ghc bugs? :) Also, the symlink touching code is currently broken, when used on utf-8 filenames in a non-utf-8 locale, or probably on any filename containing undecodable bytes, and I temporarily commented it out.
2012-02-03 19:12:41 +00:00
map (separate (== ' ')) . lines
uniqref (a, _) (b, _) = a == b
2011-12-09 05:57:13 +00:00
ourbranchend = '/' : show Annex.Branch.name
ourbranches (_, b) = not $ ourbranchend `isSuffixOf` b
go s [] = return $ S.toList s
go s (r:rs)
2011-09-29 00:12:11 +00:00
| s == S.empty = return [] -- optimisation
| otherwise = do
s' <- withKeysReferencedInGit r s S.delete
go s' rs
2011-04-03 00:59:41 +00:00
{- Finds items in the first, smaller list, that are not
- present in the second, larger list.
-
- Constructing a single set, of the list that tends to be
- smaller, appears more efficient in both memory and CPU
- than constructing and taking the S.difference of two sets. -}
exclude :: Ord a => [a] -> [a] -> [a]
exclude [] _ = [] -- optimisation
exclude smaller larger = S.toList $ remove larger $ S.fromList smaller
where
remove a b = foldl (flip S.delete) b a
{- Given an initial value, mutates it using an action for each
- key referenced by symlinks in the git repo. -}
withKeysReferenced :: v -> (Key -> v -> v) -> Annex v
withKeysReferenced initial a = go initial =<< files
where
files = do
top <- fromRepo Git.workTree
inRepo $ LsFiles.inRepo [top]
go v [] = return v
go v (f:fs) = do
x <- Backend.lookupFile f
case x of
Nothing -> go v fs
Just (k, _) -> do
let !v' = a k v
go v' fs
withKeysReferencedInGit :: Git.Ref -> v -> (Key -> v -> v) -> Annex v
withKeysReferencedInGit ref initial a = do
2011-12-12 22:23:24 +00:00
showAction $ "checking " ++ Git.Ref.describe ref
go initial =<< inRepo (LsTree.lsTree ref)
where
go v [] = return v
go v (l:ls)
2011-09-29 00:12:11 +00:00
| isSymLink (LsTree.mode l) = do
content <- L.decodeUtf8 <$> catFile ref (LsTree.file l)
case fileKey (takeFileName $ L.unpack content) of
Nothing -> go v ls
Just k -> do
let !v' = a k v
go v' ls
| otherwise = go v ls
{- Looks in the specified directory for bad/tmp keys, and returns a list
- of those that might still have value, or might be stale and removable.
-
- Also, stale keys that can be proven to have no value are deleted.
-}
staleKeysPrune :: (Git.Repo -> FilePath) -> Annex [Key]
staleKeysPrune dirspec = do
contents <- staleKeys dirspec
2011-09-23 22:13:24 +00:00
dups <- filterM inAnnex contents
let stale = contents `exclude` dups
dir <- fromRepo dirspec
liftIO $ forM_ dups $ \t -> removeFile $ dir </> keyFile t
return stale
staleKeys :: (Git.Repo -> FilePath) -> Annex [Key]
staleKeys dirspec = do
dir <- fromRepo dirspec
exists <- liftIO $ doesDirectoryExist dir
if not exists
then return []
else do
contents <- liftIO $ getDirectoryContents dir
files <- liftIO $ filterM doesFileExist $
map (dir </>) contents
2011-07-15 16:47:14 +00:00
return $ mapMaybe (fileKey . takeFileName) files