Federated forge server
Clone
HTTPS:
git clone https://vervis.peers.community/repos/rjQ3E
SSH:
git clone USERNAME@vervis.peers.community:rjQ3E
Branches
Tags
Git.hs
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | {- This file is part of Vervis.
-
- Written in 2016, 2018, 2019, 2022, 2024
- by fr33domlover <fr33domlover@riseup.net>.
-
- ♡ Copying is an act of love. Please copy, reuse and share.
-
- The author(s) have dedicated all copyright and related and neighboring
- rights to this software to the public domain worldwide. This software is
- distributed without any warranty.
-
- You should have received a copy of the CC0 Public Domain Dedication along
- with this software. If not, see
- <http://creativecommons.org/publicdomain/zero/1.0/>.
-}
module Development.Git
( GitT
, withGitRepo
, withGitRepoE
, git
, git_
, gitE
, gitE_
, writeHookFile
, createRepo
, isGitRepo
, TreeEntryType (..)
, TreeEntry (..)
, gitListDir
, PathType (..)
, gitGetPathType
, gitGetFileContentByPath
, gitGetFileContentByHash
, gitListBranches
, gitListBranches'
, gitListTags
, gitListTags'
, gitGetObjectHash
, gitResolveHead
, gitGetObjectHashes
, RevType (..)
, gitGetRevType
, gitGetCommitInfos
, gitGetCommitInfo
, gitDiff
, gitGetCommitParents
, gitPeelTag
, gitFetch
)
where
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Control.Monad.Trans.Reader
import Data.Either
import Data.Maybe
import Data.Map (Map)
import Data.Set (Set)
import Data.Text (Text)
import Data.Time.Format
import Data.Traversable
import System.Directory.Tree
import System.FilePath
import System.Posix.Files
import System.Process.Typed
--import Text.Diff.Parse
--import Text.Diff.Parse.Types
import Text.Email.Validate
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Lazy as BL
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.IO as TIO
import Data.ObjId
import qualified Data.VersionControl as VC
hookContent :: FilePath -> Text -> Text -> Text
hookContent hook authority repo =
T.concat
[ "#!/bin/sh\nexec ", T.pack hook
, " ", authority, " ", repo
]
writeHookFile :: FilePath -> FilePath -> Text -> Text -> IO ()
writeHookFile path cmd authority repo = do
let file = path </> "hooks" </> "post-receive"
TIO.writeFile file $ hookContent cmd authority repo
setFileMode file ownerModes
initialRepoTree :: FilePath -> Text -> Text -> DirTree Text
initialRepoTree hook authority repo =
Dir (T.unpack repo)
[ Dir "branches" []
, File "config"
"[core]\n\
\ repositoryformatversion = 0\n\
\ filemode = true\n\
\ bare = true"
, File "description"
"Unnamed repository; edit this file to name the repository."
, File "HEAD" "ref: refs/heads/main"
, Dir "hooks"
[ File "post-receive" $ hookContent hook authority repo
]
, Dir "info"
[ File "exclude" ""
]
, Dir "objects"
[ Dir "info" []
, Dir "pack" []
]
, Dir "refs"
[ Dir "heads" []
, Dir "tags" []
]
]
-- | initialize a new bare repository at a specific location.
--
-- Currently in the @hit@ package, i.e. version 0.6.3, the initRepo function
-- creates a directory which the git executable doesn't recognize as a git
-- repository. The version here creates a properly initialized repo.
createRepo
:: FilePath
-- ^ Parent directory which already exists
-> Text
-- ^ Repo hashid, i.e. new directory to create under the parent
-> FilePath
-- ^ Path of Vervis hook program
-> Text
-- ^ Instance HTTP authority
-> IO ()
createRepo path repo cmd authority = do
let tree = path :/ initialRepoTree cmd authority repo
result <- writeDirectoryWith TIO.writeFile tree
let errs = failures $ dirTree result
when (not . null $ errs) $
throwIO $ userError $ show errs
setFileMode
(path </> T.unpack repo </> "hooks" </> "post-receive")
ownerModes
isGitRepo :: FilePath -> IO Bool
isGitRepo path = do
r <- runExceptT $ withGitRepoE path $ gitE "rev-parse" ["--show-prefix"]
return $
case r of
Left _ -> False
Right t -> T.null $ T.strip t
type GitT m a = ReaderT FilePath m a
withGitRepo :: MonadIO m => FilePath -> GitT m a -> m a
withGitRepo path action = runReaderT action path
type GitE m a = ExceptT Text (ReaderT FilePath m) a
withGitRepoE :: MonadIO m => FilePath -> GitE m a -> ExceptT Text m a
withGitRepoE path action = ExceptT $ withGitRepo path $ runExceptT action
git :: MonadIO m => String -> [String] -> GitT m Text
git cmd args = do
repo <- ask
lb <- readProcessStdout_ $ setStdin nullStream $ proc "git" $ ["-C", repo, cmd] ++ args
liftIO $ either throwIO return $ TE.decodeUtf8' $ BL.toStrict lb
git_ :: MonadIO m => String -> [String] -> GitT m ()
git_ cmd args = do
repo <- ask
runProcess_ $ setStdin nullStream $ proc "git" $ ["-C", repo, cmd] ++ args
gitE :: MonadIO m => String -> [String] -> GitE m Text
gitE cmd args = do
repo <- lift ask
(code, lb) <- readProcessStdout $ setStdin nullStream $ proc "git" $ ["-C", repo, cmd] ++ args
case code of
ExitSuccess -> pure ()
ExitFailure c -> throwE $ "gitE " <> T.pack cmd <> " exited with code " <> T.pack (show c)
either (throwE . T.pack . displayException) return $ TE.decodeUtf8' $ BL.toStrict lb
gitE_ :: MonadIO m => String -> [String] -> GitE m ()
gitE_ cmd args = do
repo <- lift ask
code <- runProcess $ setStdin nullStream $ proc "git" $ ["-C", repo, cmd] ++ args
case code of
ExitSuccess -> pure ()
ExitFailure c -> throwE $ "gitE_ " <> T.pack cmd <> " exited with code " <> T.pack (show c)
data TreeEntryType = TETFile Text | TETDir
data TreeEntry = TreeEntry
{ _teMode :: Text
, _teType :: TreeEntryType
, _teHash :: ObjId
, _teName :: Text
}
parseTree :: Text -> IO [TreeEntry]
parseTree = traverse (parseEntry . T.words) . T.lines
where
grabName = T.pack . takeFileName . T.unpack
parseEntry [mode, "blob", hash, size, path] = do
oid <- parseObjId hash
pure $ TreeEntry mode (TETFile size) oid (grabName path)
parseEntry [mode, "tree", hash, "-", path] = do
oid <- parseObjId hash
pure $ TreeEntry mode TETDir oid (grabName path)
parseEntry _ = error "Unexpected tree entry line"
gitListDir :: MonadIO m => Text -> Maybe FilePath -> GitT m [TreeEntry]
gitListDir rev maybePath = do
let path = fromMaybe "." maybePath
t <- git "ls-tree" [T.unpack rev, "--long", addTrailingPathSeparator path]
liftIO $ parseTree t
data PathType = PTBlob | PTTree deriving Show
parsePathType :: Text -> IO PathType
parsePathType t =
case T.strip t of
"blob" -> pure PTBlob
"tree" -> pure PTTree
_ -> error "Path type is neither blob nor tree"
gitGetPathType :: Text -> FilePath -> GitT IO PathType
gitGetPathType rev path = do
t <- git "cat-file" ["-t", T.unpack rev ++ ":" ++ path]
liftIO $ parsePathType t
parseBranches :: Text -> IO [Text]
parseBranches t = traverse grab $ map T.words $ T.lines t
where
grab [b] = pure b
grab ["*", b] = pure b
grab _ = error "Unexpected branch line"
gitGetFileContentByPath :: Text -> FilePath -> GitT IO Text
gitGetFileContentByPath rev path =
git "cat-file" ["blob", T.unpack rev ++ ":" ++ path]
gitGetFileContentByHash :: MonadIO m => ObjId -> GitT m Text
gitGetFileContentByHash oid =
git "cat-file" ["blob", T.unpack $ renderObjId oid]
gitListBranches :: MonadIO m => GitT m (Set Text)
gitListBranches = do
t <- git "branch" ["--list"]
bs <- liftIO $ parseBranches t
return $ S.fromList bs
gitListBranches' :: MonadIO m => GitT m (Map Text ObjId)
gitListBranches' = do
t <- git "branch" ["--list"]
bs <- liftIO $ parseBranches t
hs <- gitGetObjectHashes $ map ("refs/heads/" <>) bs
return $ M.fromList $ zip bs hs
parseTags :: Text -> IO [Text]
parseTags t = traverse grab $ map T.words $ T.lines t
where
grab [tag] = pure tag
grab _ = error "Unexpected tag line"
gitListTags :: MonadIO m => GitT m (Set Text)
gitListTags = do
t <- git "tag" ["--list"]
ts <- liftIO $ parseTags t
return $ S.fromList ts
gitListTags' :: MonadIO m => GitT m (Map Text ObjId)
gitListTags' = do
t <- git "tag" ["--list"]
ts <- liftIO $ parseTags t
hs <- gitGetObjectHashes $ map ("refs/tags/" <>) ts
return $ M.fromList $ zip ts hs
gitGetObjectHash :: MonadIO m => Text -> GitT m ObjId
gitGetObjectHash object = do
hash <- T.strip <$> git "rev-parse" [T.unpack object]
liftIO $ parseObjId hash
gitResolveHead :: MonadIO m => GitT m (Maybe ObjId)
gitResolveHead = do
mh <-
either (const Nothing) Just <$>
runExceptT (T.strip <$> gitE "rev-parse" ["HEAD"])
liftIO $ for mh parseObjId
gitGetObjectHashes :: MonadIO m => [Text] -> GitT m [ObjId]
gitGetObjectHashes [] = pure []
gitGetObjectHashes objects = do
hashes <- T.lines <$> git "rev-parse" (map T.unpack objects)
liftIO $ traverse parseObjId hashes
data RevType = RTCommit | RTTag deriving Show
parseRevType :: Text -> IO RevType
parseRevType t =
case T.strip t of
"commit" -> pure RTCommit
"tag" -> pure RTTag
_ -> error "Rev type is neither commit nor tag"
gitGetRevType :: MonadIO m => Text -> GitT m RevType
gitGetRevType rev = do
t <- git "cat-file" ["-t", T.unpack rev]
liftIO $ parseRevType t
parseCommits :: Text -> Maybe [VC.Commit]
parseCommits input = do
input' <- T.stripPrefix "commit " input
let sections = T.splitOn "\ncommit " input'
traverse (parseSection . T.lines) sections
where
parseSection (hash : a : ad : c : cd : "" : title : " " : rest) = do
a' <- T.strip <$> T.stripPrefix "Author:" a
author <- parsePerson a'
ad' <- T.strip <$> T.stripPrefix "AuthorDate:" ad
date <- parseDate ad'
committed <- do
c' <- T.strip <$> T.stripPrefix "Commit:" c
cd' <- T.strip <$> T.stripPrefix "CommitDate:" cd
if c' == a' && cd' == ad'
then pure Nothing
else Just $ (,) <$> parsePerson c' <*> parseDate cd'
title' <- T.stripPrefix " " title
desc <- T.unlines <$> traverse (T.stripPrefix " ") rest
return $ VC.Commit (author, date) committed hash title' desc
where
parseDate t =
parseTimeM False defaultTimeLocale rfc822DateFormat $ T.unpack t
parsePerson t = do
let (name, e) = T.break (== '<') t
(c, e') <- T.uncons e
(e'', c') <- T.unsnoc e'
guard $ c == '<'
guard $ c' == '>'
email <- emailAddress $ TE.encodeUtf8 e''
return $ VC.Author name email
parseSection _ = Nothing
gitGetCommitInfos
:: MonadIO m
=> Text -> [ObjId] -> Maybe Int -> Maybe Int -> GitT m [VC.Commit]
gitGetCommitInfos refspec existingBranchHashes maybeLimit maybeOffset = do
let limit =
case maybeLimit of
Nothing -> []
Just n -> ["--max-count=" ++ show n]
offset =
case maybeOffset of
Nothing -> []
Just n -> ["--skip=" ++ show n]
t <- git "rev-list" $ offset ++ limit ++ ["--format=fuller", T.unpack refspec] ++ map (('^' :) . T.unpack . renderObjId) existingBranchHashes
case parseCommits t of
Just cs -> pure cs
Nothing -> error "parseCommits failed"
gitGetCommitInfo :: MonadIO m => ObjId -> GitT m (VC.Commit)
gitGetCommitInfo oid = do
cs <- gitGetCommitInfos (renderObjId oid) [] Nothing Nothing
case cs of
[c] -> pure c
_ -> error "gitGetCommitInfo: Expected a single commit"
--gitDiff :: MonadIO m => Text -> GitT m [FileDelta]
gitDiff :: MonadIO m => ObjId -> GitT m Text
gitDiff commitOid =
let commitHash = renderObjId commitOid
in git "diff"
["--no-color", T.unpack $ commitHash <> "~", T.unpack commitHash]
{-
case parseDiff t of
Left e -> error $ "gitDiff: " ++ e
Right deltas -> pure deltas
-}
gitGetCommitParents :: MonadIO m => ObjId -> GitT m [ObjId]
gitGetCommitParents oid = do
hashes <- T.lines <$> git "rev-parse" [T.unpack $ renderObjId oid <> "^@"]
liftIO $ traverse parseObjId hashes
-- | Given a tag's hash, if it's an annotated tag, return the commit hash it
-- points to
gitPeelTag :: MonadIO m => ObjId -> GitT m (Maybe ObjId)
gitPeelTag tagOid = do
let tagHash = renderObjId tagOid
typ <- gitGetRevType tagHash
commitHash <- T.strip <$> git "rev-parse" [T.unpack $ tagHash <> "^{commit}"]
case (typ, commitHash == tagHash) of
(RTCommit, True) -> pure Nothing
(RTTag, False) -> liftIO $ Just <$> parseObjId commitHash
_ -> error "gitPeelTag unexpected situation"
gitFetch :: MonadIO m => Text -> Text -> Text -> GitT m ()
gitFetch myBranch u theirBranch = git_ "fetch" [T.unpack u, T.unpack $ theirBranch <> ":" <> myBranch]
|