summaryrefslogtreecommitdiff
path: root/Command/DropUnused.hs
blob: 9c9513ca9d6db9d762c51e32c284b8278b14ddb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
{- git-annex command
 -
 - Copyright 2010,2012 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

module Command.DropUnused where

import qualified Data.Map as M

import Common.Annex
import Command
import qualified Annex
import qualified Command.Drop
import qualified Remote
import qualified Git
import qualified Option
import Types.Key

type UnusedMap = M.Map Integer Key

def :: [Command]
def = [withOptions [Command.Drop.fromOption] $
	command "dropunused" (paramRepeating paramNumber)
		seek "drop unused file content"]

seek :: [CommandSeek]
seek = [withUnusedMaps]

{- Read unused logs once, and pass the maps to each start action. -}
withUnusedMaps :: CommandSeek
withUnusedMaps params = do
	unused <- readUnusedLog ""
	unusedbad <- readUnusedLog "bad"
	unusedtmp <- readUnusedLog "tmp"
	return $ map (start (unused, unusedbad, unusedtmp)) $
		concatMap unusedSpec params

unusedSpec :: String -> [Integer]
unusedSpec spec
	| "-" `isInfixOf` spec = range $ separate (== '-') spec
	| otherwise = catMaybes [readish spec]
	where
		range (a, b) = case (readish a, readish b) of
			(Just x, Just y) -> [x..y]
			_ -> []

start :: (UnusedMap, UnusedMap, UnusedMap) -> Integer -> CommandStart
start (unused, unusedbad, unusedtmp) n = search
	[ (unused, perform)
	, (unusedbad, performOther gitAnnexBadLocation)
	, (unusedtmp, performOther gitAnnexTmpLocation)
	]
	where
		search [] = stop
		search ((m, a):rest) =
			case M.lookup n m of
				Nothing -> search rest
				Just key -> do
					showStart "dropunused" (show n)
					next $ a key

perform :: Key -> CommandPerform
perform key = maybe droplocal dropremote =<< Remote.byName =<< from
	where
		dropremote r = do
			showAction $ "from " ++ Remote.name r
			ok <- Remote.removeKey r key
			next $ Command.Drop.cleanupRemote key r ok
		droplocal = Command.Drop.performLocal key (Just 0) -- force drop
		from = Annex.getField $ Option.name Command.Drop.fromOption

performOther :: (Key -> Git.Repo -> FilePath) -> Key -> CommandPerform
performOther filespec key = do
	f <- fromRepo $ filespec key
	liftIO $ whenM (doesFileExist f) $ removeFile f
	next $ return True

readUnusedLog :: FilePath -> Annex UnusedMap
readUnusedLog prefix = do
	f <- fromRepo $ gitAnnexUnusedLog prefix
	ifM (liftIO $ doesFileExist f)
		( M.fromList . catMaybes . map parse . lines
			<$> liftIO (readFile f)
		, return M.empty
		)
	where
		parse line =
			case (readish tag, readKey rest) of
				(Just num, Just key) -> Just (num, key)
				_ -> Nothing
			where
				(tag, rest) = separate (== ' ') line