Git post-receive hook which collects new commits and tags made in the Git push, and reports them to a running instance of FunBot, so that the bot can announce the event to IRC.
Clone
HTTPS:
git clone https://vervis.peers.community/repos/brwmv
SSH:
git clone USERNAME@vervis.peers.community:brwmv
Branches
Tags
Main.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 | {- This file is part of funbot-git-hook.
-
- Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.
-
- ♡ 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/>.
-}
-- For pattern matching Data.Text values
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Exception (tryJust)
import Control.Monad (guard, forM, liftM)
import Data.Either (partitionEithers)
import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
import Data.Git
import Data.Git.Ref (fromHex)
import Data.Git.Repository (configGet)
import Data.Git.Storage.Object (Object (..))
import Data.Text.Template
import Network.URI (URI, parseURI)
import System.Directory (getCurrentDirectory)
import System.FilePath (splitExtension, takeFileName)
import System.IO.Error (isEOFError)
import Text.Printf (printf)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.UTF8 as BU
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Encoding as T
import qualified FunBot.Client as F
import qualified FunBot.ExtEvents as F hiding (ExtEvent)
-------------------------------------------------------------------------------
-- Read input lines
-------------------------------------------------------------------------------
-- | Maximal number of refs to read. The bot will announce only few of them
-- anyway, and we don't want to leave open the option of getting stuck in an
-- infinite loop. Just make sure to set this high enough to be above actual
-- normal use cases.
maxRefs :: Int
maxRefs = 3000
-- | Read from stdin one line of reflog data passed by git. Return 'Nothing' if
-- the end of the list has been reached.
readRef :: IO (Maybe (B.ByteString, B.ByteString, B.ByteString))
readRef = do
res <- tryJust (guard . isEOFError) B.getLine
case res of
Left _ -> return Nothing
Right line ->
case BC.words line of
[old, new, ref] -> return $ Just (old, new, ref)
_ -> error "An input line must contain exactly 3 spaces"
-- | Read from stdin all the reflog data passed by git.
readRefs :: IO [(B.ByteString, B.ByteString, B.ByteString)]
readRefs =
let f triples 0 = return triples
f triples left = do
mtriple <- readRef
case mtriple of
Just triple -> f (triple : triples) (left - 1)
Nothing -> return triples
in liftM reverse $ f [] maxRefs
-------------------------------------------------------------------------------
-- Read hash+branch pairs
-------------------------------------------------------------------------------
-- | Check whether a given change is an update of a ref. Creations and
-- deletions of branches aren't relevant to us.
isUpdate :: B.ByteString -> B.ByteString -> Bool
isUpdate old new = BC.any (/= '0') old || BC.any (/= '0') new
-- | A 'stripPrefix' variant for byte strings: Strip if prefix exists,
-- otherwise return the input as is.
stripPrefixB :: B.ByteString -> B.ByteString -> B.ByteString
stripPrefixB pref b =
if pref `B.isPrefixOf` b
then B.drop (B.length pref) b
else b
-- | Get details of a relevant change, or discard if not relevant.
parseChange :: B.ByteString
-> B.ByteString
-> B.ByteString
-> Maybe (B.ByteString, B.ByteString)
parseChange old new name =
if isUpdate old new
then Just (new, stripPrefixB "refs/heads/" name)
else Nothing
-- | Read input and filter relevant changes.
readChanges :: IO [(B.ByteString, B.ByteString)]
readChanges =
let f (old, new, name) = parseChange old new name
in liftM (mapMaybe f) readRefs
-------------------------------------------------------------------------------
-- Read commits and tags, filter out the rest
-------------------------------------------------------------------------------
-- | Determine repo name using the system.
getRepoName :: IO String
getRepoName = do
file <- liftM takeFileName getCurrentDirectory
return $ case splitExtension file of
(name, ".git") -> name
_ -> file
{- Get commit URL template from program arguments.
getUrlTemplate :: IO (Maybe Template)
getUrlTemplate = do
args <- getArgs
return $ case args of
[] -> Nothing
[arg] -> Just $ template $ T.pack arg
_ -> error "Too many args! Expected at most 1, the URL template."-}
-- | Get commit URL template from git config. This should probablt be in the
-- global config, not the per-repo one, since the URL template is likely
-- identical for all repos.
getUrlTemplate :: Git -> IO (Maybe Template)
getUrlTemplate git =
liftM (fmap $ template . T.pack) $
configGet git "funbot" "commit-url-template"
-- | Get repo owner string from git config. This would usually be in the
-- per-repo config. Gitolite can make it easier, defining it in @gitolite.conf@
-- at the same place @gitweb.owner@ can be defined. Note that this is data
-- /required/, therefore not finding it in the config causes an 'error'.
getRepoOwner :: Git -> IO String
getRepoOwner git =
liftM (fromMaybe $ error "funbot.owner not found in git config") $
configGet git "funbot" "owner"
-- | Apply template.
subst :: Maybe Template -> Context -> TL.Text
subst Nothing _ = TL.empty
subst (Just t) c = render t c
-- | Create a mapping from URL template variables to their values.
makeContext :: T.Text -> T.Text -> T.Text -> Context
makeContext repo branch commit var =
case var of
"repo" -> repo
"branch" -> branch
"commit" -> T.take 8 commit
_ -> T.pack "NO_SUCH_VAR"
-- | Read commit and tag data from repo, discard irrelevant input.
readEventData :: Git -> IO ([Either (F.Commit, String) F.Tag], String, String)
readEventData git = do
repo <- getRepoName
let mkCtx = makeContext $ T.pack repo
owner <- getRepoOwner git
templ <- getUrlTemplate git
cs <- readChanges
ms <- forM cs $ \ (hash, branch) -> do
mobj <- getObject git (fromHex hash) True
return $ case mobj of
Just (ObjCommit c) ->
let ctx = mkCtx (T.decodeUtf8 branch) (T.decodeUtf8 hash)
author = BU.toString $ personName $ commitAuthor c
title =
BU.toString $ BC.takeWhile (/= '\n') $ commitMessage c
url = TL.unpack $ subst templ ctx
in Just $ Left
( F.Commit
{ F.commitAuthor = author
, F.commitTitle = title
, F.commitUrl = url
}
, BU.toString branch
)
Just (ObjTag t) ->
let author = BU.toString $ personName $ tagName t
name = BU.toString $ BC.takeWhile (/= '\n') $ tagS t
in Just $ Right F.Tag
{ F.tagAuthor = author
, F.tagRef = name
, F.tagRepo = repo
, F.tagRepoOwner = owner
}
_ -> Nothing
return (catMaybes ms, repo, owner)
-------------------------------------------------------------------------------
-- Read and collect event data into push and tag events
-------------------------------------------------------------------------------
-- | Collect consecutive commits to the same branch into lists.
groupCommits :: [Either (F.Commit, String) F.Tag]
-> ([Either ([F.Commit], String) F.Tag], Int, Int)
groupCommits l =
let f (Right t) xs = Right t : xs
f (Left (c, b)) [] = [Left ([c], b)]
f (Left (c, b)) xs@(Right _ : _) = Left ([c], b) : xs
f (Left (c, b)) xs@(Left (cs, b') : r) =
if b == b'
then Left (c : cs, b) : r
else Left ([c], b) : xs
(lc, lt) = partitionEithers l
in (foldr f [] l, length lc, length lt)
-- | Given grouped event data, prepare event records.
makeEvents :: [Either ([F.Commit], String) F.Tag]
-> String
-> String
-> [F.ExtEvent]
makeEvents gs repo owner =
let mkBranch n = F.Branch
{ F.branchName = n
, F.branchRepo = repo
, F.branchRepoOwner = owner
}
mk (Left (cs, b)) = F.mkPushEvent F.Push
{ F.pushBranch = mkBranch b
, F.pushCommits = cs
}
mk (Right t) = F.mkTagEvent t
in map mk gs
-- | Read input, filter relevant events.
readEvents :: Git -> IO ([F.ExtEvent], Int, Int)
readEvents git = do
(ds, repo, owner) <- readEventData git
let (gs, nc, nt) = groupCommits ds
return (makeEvents gs repo owner, nc, nt)
-------------------------------------------------------------------------------
-- Read input, filter relevant events and send to a funbot
-------------------------------------------------------------------------------
-- | Read the funbot instance web hook URL from git config
getBotClientHookUrl :: Git -> IO URI
getBotClientHookUrl git = do
ms <- configGet git "funbot" "bot-url"
let s = fromMaybe (error "funbot.bot-url not found in git config") ms
let muri = parseURI s
uri = fromMaybe (error "funbot.bot-url is an invalid URL") muri
return uri
-- | Like 'when', but takes a 'Just' and passs the value to the action.
whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
whenJust (Just x) f = f x
whenJust Nothing _ = return ()
-- | Try to send an event to the bot, print a message if failed.
send :: F.Bot -> Int -> F.ExtEvent -> Int -> IO ()
send bot total event i = do
merr <- F.sendExtEvent bot event
whenJust merr $ \ err -> putStrLn $
printf "Failed to send %v of %v: %v" i total (show err)
main :: IO ()
main = withCurrentRepo $ \ git -> do
(events, nc, nt) <- readEvents git
url <- getBotClientHookUrl git
let bot = F.mkBot url False
putStrLn $ printf "Reporting %v commits and %v tags to funbot" nc nt
let len = length events
pairs = zip events [1..]
mapM_ (uncurry $ send bot len) pairs
|