improve type signatures with a Ref newtype

In git, a Ref can be a Sha, or a Branch, or a Tag. I added type aliases for
those. Note that this does not prevent mixing up of eg, refs and branches
at the type level. Since git really doesn't care, except rare cases like
git update-ref, or git tag -d, that seems ok for now.

There's also a tree-ish, but let's just use Ref for it. A given Sha or Ref
may or may not be a tree-ish, depending on the object type, so there seems
no point in trying to represent it at the type level.
This commit is contained in:
Joey Hess 2011-11-16 02:23:34 -04:00
parent 272a67921c
commit 9290095fc2
10 changed files with 86 additions and 71 deletions

View file

@ -31,19 +31,17 @@ import qualified Git.UnionMerge
import qualified Annex import qualified Annex
import Annex.CatFile import Annex.CatFile
type GitRef = String
{- Name of the branch that is used to store git-annex's information. -} {- Name of the branch that is used to store git-annex's information. -}
name :: GitRef name :: Git.Ref
name = "git-annex" name = Git.Ref "git-annex"
{- Fully qualified name of the branch. -} {- Fully qualified name of the branch. -}
fullname :: GitRef fullname :: Git.Ref
fullname = "refs/heads/" ++ name fullname = Git.Ref $ "refs/heads/" ++ show name
{- Branch's name in origin. -} {- Branch's name in origin. -}
originname :: GitRef originname :: Git.Ref
originname = "origin/" ++ name originname = Git.Ref $ "origin/" ++ show name
{- A separate index file for the branch. -} {- A separate index file for the branch. -}
index :: Git.Repo -> FilePath index :: Git.Repo -> FilePath
@ -104,7 +102,8 @@ create :: Annex ()
create = unlessM hasBranch $ do create = unlessM hasBranch $ do
e <- hasOrigin e <- hasOrigin
if e if e
then inRepo $ Git.run "branch" [Param name, Param originname] then inRepo $ Git.run "branch"
[Param $ show name, Param $ show originname]
else withIndex' True $ else withIndex' True $
inRepo $ Git.commit "branch created" fullname [] inRepo $ Git.commit "branch created" fullname []
@ -140,8 +139,8 @@ update = onceonly $ do
let merge_desc = if null branches let merge_desc = if null branches
then "update" then "update"
else "merging " ++ else "merging " ++
(unwords $ map Git.refDescribe branches) ++ (unwords $ map (show . Git.refDescribe) branches) ++
" into " ++ name " into " ++ show name
unless (null branches) $ do unless (null branches) $ do
showSideAction merge_desc showSideAction merge_desc
{- Note: This merges the branches into the index. {- Note: This merges the branches into the index.
@ -164,12 +163,12 @@ update = onceonly $ do
{- Checks if the second branch has any commits not present on the first {- Checks if the second branch has any commits not present on the first
- branch. -} - branch. -}
changedBranch :: String -> String -> Annex Bool changedBranch :: Git.Branch -> Git.Branch -> Annex Bool
changedBranch origbranch newbranch = not . L.null <$> diffs changedBranch origbranch newbranch = not . L.null <$> diffs
where where
diffs = inRepo $ Git.pipeRead diffs = inRepo $ Git.pipeRead
[ Param "log" [ Param "log"
, Param (origbranch ++ ".." ++ newbranch) , Param (show origbranch ++ ".." ++ show newbranch)
, Params "--oneline -n1" , Params "--oneline -n1"
] ]
@ -181,7 +180,7 @@ changedBranch origbranch newbranch = not . L.null <$> diffs
- every commit present in all the other refs, as well as in the - every commit present in all the other refs, as well as in the
- git-annex branch. - git-annex branch.
-} -}
tryFastForwardTo :: [String] -> Annex Bool tryFastForwardTo :: [Git.Ref] -> Annex Bool
tryFastForwardTo [] = return True tryFastForwardTo [] = return True
tryFastForwardTo (first:rest) = do tryFastForwardTo (first:rest) = do
-- First, check that the git-annex branch does not contain any -- First, check that the git-annex branch does not contain any
@ -194,7 +193,7 @@ tryFastForwardTo (first:rest) = do
where where
no_ff = return False no_ff = return False
do_ff branch = do do_ff branch = do
inRepo $ Git.run "update-ref" [Param fullname, Param branch] inRepo $ Git.run "update-ref" [Param $ show fullname, Param $ show branch]
return True return True
findbest c [] = return $ Just c findbest c [] = return $ Just c
findbest c (r:rs) findbest c (r:rs)
@ -220,9 +219,9 @@ disableUpdate = Annex.changeState setupdated
old = Annex.branchstate s old = Annex.branchstate s
{- Checks if a git ref exists. -} {- Checks if a git ref exists. -}
refExists :: GitRef -> Annex Bool refExists :: Git.Ref -> Annex Bool
refExists ref = inRepo $ Git.runBool "show-ref" refExists ref = inRepo $ Git.runBool "show-ref"
[Param "--verify", Param "-q", Param ref] [Param "--verify", Param "-q", Param $ show ref]
{- Does the main git-annex branch exist? -} {- Does the main git-annex branch exist? -}
hasBranch :: Annex Bool hasBranch :: Annex Bool
@ -238,12 +237,12 @@ hasSomeBranch = not . null <$> siblingBranches
{- List of git-annex (refs, branches), including the main one and any {- List of git-annex (refs, branches), including the main one and any
- from remotes. Duplicate refs are filtered out. -} - from remotes. Duplicate refs are filtered out. -}
siblingBranches :: Annex [(String, String)] siblingBranches :: Annex [(Git.Ref, Git.Branch)]
siblingBranches = do siblingBranches = do
r <- inRepo $ Git.pipeRead [Param "show-ref", Param name] r <- inRepo $ Git.pipeRead [Param "show-ref", Param $ show name]
return $ nubBy uref $ map (pair . words . L.unpack) (L.lines r) return $ nubBy uref $ map (gen . words . L.unpack) (L.lines r)
where where
pair l = (head l, last l) gen l = (Git.Ref $ head l, Git.Ref $ last l)
uref (a, _) (b, _) = a == b uref (a, _) (b, _) = a == b
{- Applies a function to modifiy the content of a file. {- Applies a function to modifiy the content of a file.
@ -291,7 +290,7 @@ get' staleok file = fromcache =<< getCache file
files :: Annex [FilePath] files :: Annex [FilePath]
files = withIndexUpdate $ do files = withIndexUpdate $ do
bfiles <- inRepo $ Git.pipeNullSplit bfiles <- inRepo $ Git.pipeNullSplit
[Params "ls-tree --name-only -r -z", Param fullname] [Params "ls-tree --name-only -r -z", Param $ show fullname]
jfiles <- getJournalledFiles jfiles <- getJournalledFiles
return $ jfiles ++ bfiles return $ jfiles ++ bfiles
@ -346,10 +345,10 @@ stageJournalFiles = do
hClose toh hClose toh
exitSuccess exitSuccess
hClose toh hClose toh
s <- hGetContents fromh shas <- map Git.Ref . lines <$> hGetContents fromh
-- update the index, also in just one command -- update the index, also in just one command
Git.UnionMerge.update_index g $ Git.UnionMerge.update_index g $
index_lines (lines s) $ map fileJournal fs index_lines shas (map fileJournal fs)
hClose fromh hClose fromh
forceSuccess pid forceSuccess pid
mapM_ removeFile paths mapM_ removeFile paths

View file

@ -13,10 +13,11 @@ module Annex.CatFile (
import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.ByteString.Lazy.Char8 as L
import Common.Annex import Common.Annex
import qualified Git
import qualified Git.CatFile import qualified Git.CatFile
import qualified Annex import qualified Annex
catFile :: String -> FilePath -> Annex L.ByteString catFile :: Git.Branch -> FilePath -> Annex L.ByteString
catFile branch file = do catFile branch file = do
h <- catFileHandle h <- catFileHandle
liftIO $ Git.CatFile.catFile h branch file liftIO $ Git.CatFile.catFile h branch file

View file

@ -26,9 +26,9 @@ check :: Annex ()
check = do check = do
b <- current_branch b <- current_branch
when (b == Annex.Branch.name) $ error $ when (b == Annex.Branch.name) $ error $
"cannot uninit when the " ++ b ++ " branch is checked out" "cannot uninit when the " ++ show b ++ " branch is checked out"
where where
current_branch = head . lines . B.unpack <$> revhead current_branch = Git.Ref . head . lines . B.unpack <$> revhead
revhead = inRepo $ Git.pipeRead revhead = inRepo $ Git.pipeRead
[Params "rev-parse --abbrev-ref HEAD"] [Params "rev-parse --abbrev-ref HEAD"]
@ -57,5 +57,5 @@ cleanup = do
liftIO $ removeDirectoryRecursive annexdir liftIO $ removeDirectoryRecursive annexdir
-- avoid normal shutdown -- avoid normal shutdown
saveState saveState
inRepo $ Git.run "branch" [Param "-D", Param Annex.Branch.name] inRepo $ Git.run "branch" [Param "-D", Param $ show Annex.Branch.name]
liftIO exitSuccess liftIO exitSuccess

View file

@ -152,12 +152,13 @@ excludeReferenced l = do
(S.fromList l) (S.fromList l)
where where
-- Skip the git-annex branches, and get all other unique refs. -- Skip the git-annex branches, and get all other unique refs.
refs = map last . refs = map Git.Ref .
last .
nubBy cmpheads . nubBy cmpheads .
filter ourbranches . filter ourbranches .
map words . lines . L.unpack map words . lines . L.unpack
cmpheads a b = head a == head b cmpheads a b = head a == head b
ourbranchend = '/' : Annex.Branch.name ourbranchend = '/' : show (Annex.Branch.name)
ourbranches ws = not $ ourbranchend `isSuffixOf` last ws ourbranches ws = not $ ourbranchend `isSuffixOf` last ws
removewith [] s = return $ S.toList s removewith [] s = return $ S.toList s
removewith (a:as) s removewith (a:as) s
@ -188,7 +189,7 @@ getKeysReferenced = do
return $ map fst $ catMaybes keypairs return $ map fst $ catMaybes keypairs
{- List of keys referenced by symlinks in a git ref. -} {- List of keys referenced by symlinks in a git ref. -}
getKeysReferencedInGit :: String -> Annex [Key] getKeysReferencedInGit :: Git.Ref -> Annex [Key]
getKeysReferencedInGit ref = do getKeysReferencedInGit ref = do
showAction $ "checking " ++ Git.refDescribe ref showAction $ "checking " ++ Git.refDescribe ref
findkeys [] =<< inRepo (LsTree.lsTree ref) findkeys [] =<< inRepo (LsTree.lsTree ref)

36
Git.hs
View file

@ -10,6 +10,10 @@
module Git ( module Git (
Repo, Repo,
Ref(..),
Branch,
Sha,
Tag,
repoFromCwd, repoFromCwd,
repoFromAbsPath, repoFromAbsPath,
repoFromUnknown, repoFromUnknown,
@ -94,6 +98,18 @@ data Repo = Repo {
remoteName :: Maybe String remoteName :: Maybe String
} deriving (Show, Eq) } deriving (Show, Eq)
{- A git ref. Can be a sha1, or a branch or tag name. -}
newtype Ref = Ref String
deriving (Eq)
instance Show Ref where
show (Ref v) = v
{- Aliases for Ref. -}
type Branch = Ref
type Sha = Ref
type Tag = Ref
newFrom :: RepoLocation -> Repo newFrom :: RepoLocation -> Repo
newFrom l = newFrom l =
Repo { Repo {
@ -162,9 +178,9 @@ repoDescribe Repo { location = Url url } = show url
repoDescribe Repo { location = Dir dir } = dir repoDescribe Repo { location = Dir dir } = dir
repoDescribe Repo { location = Unknown } = "UNKNOWN" repoDescribe Repo { location = Unknown } = "UNKNOWN"
{- Converts a fully qualified git ref into a user-visible version -} {- Converts a fully qualified git ref into a user-visible version. -}
refDescribe :: String -> String refDescribe :: Ref -> String
refDescribe = remove "refs/heads/" . remove "refs/remotes/" refDescribe = remove "refs/heads/" . remove "refs/remotes/" . show
where where
remove prefix s remove prefix s
| prefix `isPrefixOf` s = drop (length prefix) s | prefix `isPrefixOf` s = drop (length prefix) s
@ -432,7 +448,7 @@ useIndex index = do
{- Runs an action that causes a git subcommand to emit a sha, and strips {- Runs an action that causes a git subcommand to emit a sha, and strips
any trailing newline, returning the sha. -} any trailing newline, returning the sha. -}
getSha :: String -> IO String -> IO String getSha :: String -> IO String -> IO Sha
getSha subcommand a = do getSha subcommand a = do
t <- a t <- a
let t' = if last t == '\n' let t' = if last t == '\n'
@ -440,27 +456,27 @@ getSha subcommand a = do
else t else t
when (length t' /= shaSize) $ when (length t' /= shaSize) $
error $ "failed to read sha from git " ++ subcommand ++ " (" ++ t' ++ ")" error $ "failed to read sha from git " ++ subcommand ++ " (" ++ t' ++ ")"
return t' return $ Ref t'
{- Size of a git sha. -} {- Size of a git sha. -}
shaSize :: Int shaSize :: Int
shaSize = 40 shaSize = 40
{- Commits the index into the specified branch, {- Commits the index into the specified branch (or other ref),
- with the specified parent refs. -} - with the specified parent refs. -}
commit :: String -> String -> [String] -> Repo -> IO () commit :: String -> Ref -> [Ref] -> Repo -> IO ()
commit message newref parentrefs repo = do commit message newref parentrefs repo = do
tree <- getSha "write-tree" $ asString $ tree <- getSha "write-tree" $ asString $
pipeRead [Param "write-tree"] repo pipeRead [Param "write-tree"] repo
sha <- getSha "commit-tree" $ asString $ sha <- getSha "commit-tree" $ asString $
ignorehandle $ pipeWriteRead ignorehandle $ pipeWriteRead
(map Param $ ["commit-tree", tree] ++ ps) (map Param $ ["commit-tree", show tree] ++ ps)
(L.pack message) repo (L.pack message) repo
run "update-ref" [Param newref, Param sha] repo run "update-ref" [Param $ show newref, Param $ show sha] repo
where where
ignorehandle a = snd <$> a ignorehandle a = snd <$> a
asString a = L.unpack <$> a asString a = L.unpack <$> a
ps = concatMap (\r -> ["-p", r]) parentrefs ps = concatMap (\r -> ["-p", show r]) parentrefs
{- Runs git config and populates a repo with its config. -} {- Runs git config and populates a repo with its config. -}
configRead :: Repo -> IO Repo configRead :: Repo -> IO Repo

View file

@ -37,14 +37,14 @@ catFileStop (pid, from, to) = do
forceSuccess pid forceSuccess pid
{- Reads a file from a specified branch. -} {- Reads a file from a specified branch. -}
catFile :: CatFileHandle -> String -> FilePath -> IO L.ByteString catFile :: CatFileHandle -> Branch -> FilePath -> IO L.ByteString
catFile h branch file = catObject h (branch ++ ":" ++ file) catFile h branch file = catObject h $ Ref $ show branch ++ ":" ++ file
{- Uses a running git cat-file read the content of an object. {- Uses a running git cat-file read the content of an object.
- Objects that do not exist will have "" returned. -} - Objects that do not exist will have "" returned. -}
catObject :: CatFileHandle -> String -> IO L.ByteString catObject :: CatFileHandle -> Ref -> IO L.ByteString
catObject (_, from, to) object = do catObject (_, from, to) object = do
hPutStrLn to object hPutStrLn to $ show object
hFlush to hFlush to
header <- hGetLine from header <- hGetLine from
case words header of case words header of
@ -53,7 +53,7 @@ catObject (_, from, to) object = do
validobjtype objtype -> handle size validobjtype objtype -> handle size
| otherwise -> empty | otherwise -> empty
_ _
| header == object ++ " missing" -> empty | header == show object ++ " missing" -> empty
| otherwise -> error $ "unknown response from git cat-file " ++ header | otherwise -> error $ "unknown response from git cat-file " ++ header
where where
handle size = case reads size of handle size = case reads size of

View file

@ -19,8 +19,6 @@ import qualified Data.ByteString.Lazy.Char8 as L
import Git import Git
import Utility.SafeCommand import Utility.SafeCommand
type Treeish = String
data TreeItem = TreeItem data TreeItem = TreeItem
{ mode :: FileMode { mode :: FileMode
, typeobj :: String , typeobj :: String
@ -28,10 +26,10 @@ data TreeItem = TreeItem
, file :: FilePath , file :: FilePath
} deriving Show } deriving Show
{- Lists the contents of a Treeish -} {- Lists the contents of a Ref -}
lsTree :: Treeish -> Repo -> IO [TreeItem] lsTree :: Ref -> Repo -> IO [TreeItem]
lsTree t repo = map parseLsTree <$> lsTree t repo = map parseLsTree <$>
pipeNullSplitB [Params "ls-tree --full-tree -z -r --", File t] repo pipeNullSplitB [Params "ls-tree --full-tree -z -r --", File $ show t] repo
{- Parses a line of ls-tree output. {- Parses a line of ls-tree output.
- (The --long format is not currently supported.) -} - (The --long format is not currently supported.) -}

View file

@ -22,12 +22,14 @@ import Common
import Git import Git
import Git.CatFile import Git.CatFile
type Streamer = (String -> IO ()) -> IO ()
{- Performs a union merge between two branches, staging it in the index. {- Performs a union merge between two branches, staging it in the index.
- Any previously staged changes in the index will be lost. - Any previously staged changes in the index will be lost.
- -
- Should be run with a temporary index file configured by Git.useIndex. - Should be run with a temporary index file configured by Git.useIndex.
-} -}
merge :: String -> String -> Repo -> IO () merge :: Ref -> Ref -> Repo -> IO ()
merge x y repo = do merge x y repo = do
h <- catFileStart repo h <- catFileStart repo
stream_update_index repo stream_update_index repo
@ -38,7 +40,7 @@ merge x y repo = do
{- Merges a list of branches into the index. Previously staged changed in {- Merges a list of branches into the index. Previously staged changed in
- the index are preserved (and participate in the merge). -} - the index are preserved (and participate in the merge). -}
merge_index :: CatFileHandle -> Repo -> [String] -> IO () merge_index :: CatFileHandle -> Repo -> [Ref] -> IO ()
merge_index h repo bs = merge_index h repo bs =
stream_update_index repo $ map (\b -> merge_tree_index b h repo) bs stream_update_index repo $ map (\b -> merge_tree_index b h repo) bs
@ -48,8 +50,6 @@ merge_index h repo bs =
update_index :: Repo -> [String] -> IO () update_index :: Repo -> [String] -> IO ()
update_index repo ls = stream_update_index repo [\s -> mapM_ s ls] update_index repo ls = stream_update_index repo [\s -> mapM_ s ls]
type Streamer = (String -> IO ()) -> IO ()
{- Streams content into update-index. -} {- Streams content into update-index. -}
stream_update_index :: Repo -> [Streamer] -> IO () stream_update_index :: Repo -> [Streamer] -> IO ()
stream_update_index repo as = do stream_update_index repo as = do
@ -66,22 +66,22 @@ stream_update_index repo as = do
{- Generates a line suitable to be fed into update-index, to add {- Generates a line suitable to be fed into update-index, to add
- a given file with a given sha. -} - a given file with a given sha. -}
update_index_line :: String -> FilePath -> String update_index_line :: Sha -> FilePath -> String
update_index_line sha file = "100644 blob " ++ sha ++ "\t" ++ file update_index_line sha file = "100644 blob " ++ show sha ++ "\t" ++ file
{- Gets the contents of a tree. -} {- Gets the current tree for a ref. -}
ls_tree :: String -> Repo -> Streamer ls_tree :: Ref -> Repo -> Streamer
ls_tree x repo streamer = mapM_ streamer =<< pipeNullSplit params repo ls_tree (Ref x) repo streamer = mapM_ streamer =<< pipeNullSplit params repo
where where
params = map Param ["ls-tree", "-z", "-r", "--full-tree", x] params = map Param ["ls-tree", "-z", "-r", "--full-tree", x]
{- For merging two trees. -} {- For merging two trees. -}
merge_trees :: String -> String -> CatFileHandle -> Repo -> Streamer merge_trees :: Ref -> Ref -> CatFileHandle -> Repo -> Streamer
merge_trees x y h = calc_merge h $ "diff-tree":diff_opts ++ [x, y] merge_trees (Ref x) (Ref y) h = calc_merge h $ "diff-tree":diff_opts ++ [x, y]
{- For merging a single tree into the index. -} {- For merging a single tree into the index. -}
merge_tree_index :: String -> CatFileHandle -> Repo -> Streamer merge_tree_index :: Ref -> CatFileHandle -> Repo -> Streamer
merge_tree_index x h = calc_merge h $ "diff-index":diff_opts ++ ["--cached", x] merge_tree_index (Ref x) h = calc_merge h $ "diff-index":diff_opts ++ ["--cached", x]
diff_opts :: [String] diff_opts :: [String]
diff_opts = ["--raw", "-z", "-r", "--no-renames", "-l0"] diff_opts = ["--raw", "-z", "-r", "--no-renames", "-l0"]
@ -101,7 +101,7 @@ calc_merge ch differ repo streamer = gendiff >>= go
- a line suitable for update_index that union merges the two sides of the - a line suitable for update_index that union merges the two sides of the
- diff. -} - diff. -}
mergeFile :: String -> FilePath -> CatFileHandle -> Repo -> IO (Maybe String) mergeFile :: String -> FilePath -> CatFileHandle -> Repo -> IO (Maybe String)
mergeFile info file h repo = case filter (/= nullsha) [asha, bsha] of mergeFile info file h repo = case filter (/= nullsha) [Ref asha, Ref bsha] of
[] -> return Nothing [] -> return Nothing
(sha:[]) -> return $ Just $ update_index_line sha file (sha:[]) -> return $ Just $ update_index_line sha file
shas -> do shas -> do
@ -110,11 +110,11 @@ mergeFile info file h repo = case filter (/= nullsha) [asha, bsha] of
return $ Just $ update_index_line sha file return $ Just $ update_index_line sha file
where where
[_colonamode, _bmode, asha, bsha, _status] = words info [_colonamode, _bmode, asha, bsha, _status] = words info
nullsha = replicate shaSize '0' nullsha = Ref $ replicate shaSize '0'
unionmerge = L.unlines . nub . L.lines unionmerge = L.unlines . nub . L.lines
{- Injects some content into git, returning its hash. -} {- Injects some content into git, returning its Sha. -}
hashObject :: L.ByteString -> Repo -> IO String hashObject :: L.ByteString -> Repo -> IO Sha
hashObject content repo = getSha subcmd $ do hashObject content repo = getSha subcmd $ do
(h, s) <- pipeWriteRead (map Param params) content repo (h, s) <- pipeWriteRead (map Param params) content repo
L.length s `seq` do L.length s `seq` do

View file

@ -86,7 +86,7 @@ logFiles dir = return . filter (".log" `isSuffixOf`)
push :: Annex () push :: Annex ()
push = do push = do
origin_master <- Annex.Branch.refExists "origin/master" origin_master <- Annex.Branch.refExists $ Git.Ref "origin/master"
origin_gitannex <- Annex.Branch.hasOrigin origin_gitannex <- Annex.Branch.hasOrigin
case (origin_master, origin_gitannex) of case (origin_master, origin_gitannex) of
(_, True) -> do (_, True) -> do
@ -103,7 +103,7 @@ push = do
Annex.Branch.update -- just in case Annex.Branch.update -- just in case
showAction "pushing new git-annex branch to origin" showAction "pushing new git-annex branch to origin"
showOutput showOutput
inRepo $ Git.run "push" [Param "origin", Param Annex.Branch.name] inRepo $ Git.run "push" [Param "origin", Param $ show Annex.Branch.name]
_ -> do _ -> do
-- no origin exists, so just let the user -- no origin exists, so just let the user
-- know about the new branch -- know about the new branch

View file

@ -37,7 +37,7 @@ parseArgs = do
main :: IO () main :: IO ()
main = do main = do
[aref, bref, newref] <- parseArgs [aref, bref, newref] <- map Git.Ref <$> parseArgs
g <- Git.configRead =<< Git.repoFromCwd g <- Git.configRead =<< Git.repoFromCwd
_ <- Git.useIndex (tmpIndex g) _ <- Git.useIndex (tmpIndex g)
setup g setup g