git-annex/Git/Ref.hs

221 lines
6.5 KiB
Haskell
Raw Normal View History

2011-12-12 22:23:24 +00:00
{- git ref stuff
-
2020-07-10 17:28:16 +00:00
- Copyright 2011-2020 Joey Hess <id@joeyh.name>
2011-12-12 22:23:24 +00:00
-
- Licensed under the GNU AGPL version 3 or higher.
2011-12-12 22:23:24 +00:00
-}
{-# LANGUAGE OverloadedStrings #-}
2011-12-12 22:23:24 +00:00
module Git.Ref where
import Common
import Git
2011-12-14 19:56:11 +00:00
import Git.Command
import Git.Sha
import Git.Types
2020-07-10 17:28:16 +00:00
import Git.FilePath
2011-12-12 22:23:24 +00:00
import Data.Char (chr, ord)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
headRef :: Ref
headRef = Ref "HEAD"
headFile :: Repo -> FilePath
headFile r = fromRawFilePath (localGitDir r) </> "HEAD"
setHeadRef :: Ref -> Repo -> IO ()
setHeadRef ref r = S.writeFile (headFile r) ("ref: " <> fromRef' ref)
{- Converts a fully qualified git ref into a user-visible string. -}
2011-12-12 22:23:24 +00:00
describe :: Ref -> String
describe = fromRef . base
2016-09-21 18:57:44 +00:00
{- Often git refs are fully qualified
- (eg refs/heads/master or refs/remotes/origin/master).
- Converts such a fully qualified ref into a base ref
- (eg: master or origin/master). -}
base :: Ref -> Ref
base = removeBase "refs/heads/" . removeBase "refs/remotes/"
{- Removes a directory such as "refs/heads/master" from a
- fully qualified ref. Any ref not starting with it is left as-is. -}
removeBase :: String -> Ref -> Ref
removeBase dir r
| prefix `isPrefixOf` rs = Ref $ encodeBS $ drop (length prefix) rs
| otherwise = r
2012-12-13 04:24:19 +00:00
where
rs = fromRef r
prefix = case end dir of
['/'] -> dir
_ -> dir ++ "/"
2011-12-12 22:23:24 +00:00
{- Given a directory such as "refs/remotes/origin", and a ref such as
- refs/heads/master, yields a version of that ref under the directory,
- such as refs/remotes/origin/master. -}
underBase :: String -> Ref -> Ref
underBase dir r = Ref $ encodeBS dir <> "/" <> fromRef' (base r)
{- Convert a branch such as "master" into a fully qualified ref. -}
branchRef :: Branch -> Ref
branchRef = underBase "refs/heads"
{- A Ref that can be used to refer to a file in the repository, as staged
- in the index.
-
- If the input file is located outside the repository, returns Nothing.
-}
fileRef :: RawFilePath -> Repo -> IO (Maybe Ref)
fileRef f repo = do
-- The filename could be absolute, or contain eg "../repo/file",
-- neither of which work in a ref, so convert it to a minimal
-- relative path.
f' <- relPathCwdToFile f
return $ if repoPath repo `dirContains` f'
-- Prefixing the file with ./ makes this work even when in a
-- subdirectory of a repo. Eg, ./foo in directory bar refers
-- to bar/foo, not to foo in the top of the repository.
then Just $ Ref $ ":./" <> toInternalGitPath f'
else Nothing
2020-07-10 17:28:16 +00:00
{- A Ref that can be used to refer to a file in a particular branch. -}
branchFileRef :: Branch -> RawFilePath -> Ref
branchFileRef branch f = Ref $ fromRef' branch <> ":" <> toInternalGitPath f
{- Converts a Ref to refer to the content of the Ref on a given date. -}
dateRef :: Ref -> RefDate -> Ref
dateRef r (RefDate d) = Ref $ fromRef' r <> "@" <> encodeBS d
{- A Ref that can be used to refer to a file in the repository as it
- appears in a given Ref.
-
- If the file path is located outside the repository, returns Nothing.
-}
fileFromRef :: Ref -> RawFilePath -> Repo -> IO (Maybe Ref)
fileFromRef r f repo = fileRef f repo >>= return . \case
Just (Ref fr) -> Just (Ref (fromRef' r <> fr))
Nothing -> Nothing
{- Checks if a ref exists. Note that it must be fully qualified,
- eg refs/heads/master rather than master. -}
2011-12-12 22:23:24 +00:00
exists :: Ref -> Repo -> IO Bool
exists ref = runBool
[ Param "show-ref"
, Param "--verify"
, Param "-q"
, Param $ fromRef ref
]
2011-12-12 22:23:24 +00:00
{- The file used to record a ref. (Git also stores some refs in a
- packed-refs file.) -}
file :: Ref -> Repo -> FilePath
file ref repo = fromRawFilePath (localGitDir repo) </> fromRef ref
{- Checks if HEAD exists. It generally will, except for in a repository
- that was just created. -}
headExists :: Repo -> IO Bool
headExists repo = do
ls <- S.split nl <$> pipeReadStrict [Param "show-ref", Param "--head"] repo
return $ any (" HEAD" `S.isSuffixOf`) ls
where
nl = fromIntegral (ord '\n')
2011-12-12 22:23:24 +00:00
{- Get the sha of a fully qualified git ref, if it exists. -}
sha :: Branch -> Repo -> IO (Maybe Sha)
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
sha branch repo = process <$> showref repo
2012-12-13 04:24:19 +00:00
where
showref = pipeReadStrict
[ Param "show-ref"
, Param "--hash" -- get the hash
, Param $ fromRef branch
]
process s
| S.null s = Nothing
| otherwise = Just $ Ref $ firstLine' s
2011-12-12 22:23:24 +00:00
headSha :: Repo -> IO (Maybe Sha)
headSha = sha headRef
{- List of (shas, branches) matching a given ref or refs. -}
matching :: [Ref] -> Repo -> IO [(Sha, Branch)]
matching = matching' []
2013-05-22 00:04:38 +00:00
{- Includes HEAD in the output, if asked for it. -}
matchingWithHEAD :: [Ref] -> Repo -> IO [(Sha, Branch)]
matchingWithHEAD = matching' [Param "--head"]
2013-05-22 00:04:38 +00:00
matching' :: [CommandParam] -> [Ref] -> Repo -> IO [(Sha, Branch)]
matching' ps rs repo = map gen . S8.lines <$>
pipeReadStrict (Param "show-ref" : ps ++ rps) repo
2012-12-13 04:24:19 +00:00
where
gen l = let (r, b) = separate' (== fromIntegral (ord ' ')) l
2012-12-13 04:24:19 +00:00
in (Ref r, Ref b)
rps = map (Param . fromRef) rs
2011-12-30 22:36:40 +00:00
{- List of (shas, branches) matching a given ref.
- Duplicate shas are filtered out. -}
matchingUniq :: [Ref] -> Repo -> IO [(Sha, Branch)]
matchingUniq refs repo = nubBy uniqref <$> matching refs repo
2012-12-13 04:24:19 +00:00
where
uniqref (a, _) (b, _) = a == b
{- List of all refs. -}
list :: Repo -> IO [(Sha, Ref)]
list = matching' [] []
{- Deletes a ref. This can delete refs that are not branches,
- which git branch --delete refuses to delete. -}
delete :: Sha -> Ref -> Repo -> IO ()
delete oldvalue ref = run
[ Param "update-ref"
, Param "-d"
, Param $ fromRef ref
, Param $ fromRef oldvalue
]
{- Gets the sha of the tree a ref uses.
-
- The ref may be something like a branch name, and it could contain
- ":subdir" if a subtree is wanted. -}
tree :: Ref -> Repo -> IO (Maybe Sha)
tree (Ref ref) = extractSha <$$> pipeReadStrict
[ Param "rev-parse"
, Param "--verify"
, Param "--quiet"
, Param (decodeBS ref')
]
where
ref' = if ":" `S.isInfixOf` ref
then ref
-- de-reference commit objects to the tree
else ref <> ":"
{- Checks if a String is a legal git ref name.
-
- The rules for this are complex; see git-check-ref-format(1) -}
legal :: Bool -> String -> Bool
legal allowonelevel s = all (== False) illegal
2012-12-13 04:24:19 +00:00
where
illegal =
[ any ("." `isPrefixOf`) pathbits
, any (".lock" `isSuffixOf`) pathbits
, not allowonelevel && length pathbits < 2
, contains ".."
, any (\c -> contains [c]) illegalchars
, begins "/"
, ends "/"
, contains "//"
, ends "."
, contains "@{"
, null s
]
contains v = v `isInfixOf` s
ends v = v `isSuffixOf` s
begins v = v `isPrefixOf` s
pathbits = splitc '/' s
2012-12-13 04:24:19 +00:00
illegalchars = " ~^:?*[\\" ++ controlchars
controlchars = chr 0o177 : [chr 0 .. chr (0o40-1)]