Brent's personal tool

root / 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
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
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell    #-}
{-# OPTIONS_GHC -fno-cse #-}
module Main where

import           Control.Applicative          ((<$>), (<*))
import           Control.Lens
import           Control.Monad                (forM, forM_, mzero, when,
                                               zipWithM_)
import           Control.Monad.IO.Class       (MonadIO (..))
import           Control.Monad.Trans.Maybe    (MaybeT (..))
import           Data.Char                    (isDigit, isSpace, toLower)
import           Data.List                    (find, intercalate, isPrefixOf,
                                               isSuffixOf, sort)
import           Data.Maybe                   (listToMaybe, mapMaybe)
import           Data.Version                 (Version (..), parseVersion,
                                               showVersion)
import           Safe                         (readMay)
import           System.Console.CmdArgs       (Data, Typeable, argPos, args,
                                               cmdArgs, def, help, modes, typ,
                                               (&=))
import           System.Environment           (getEnvironment)
import           System.Exit                  (ExitCode (..))
import           System.FilePath              (takeFileName, (</>))
import           System.FilePath.Glob         (namesMatching)
import           System.IO                    (BufferMode (..), hFlush,
                                               hSetBinaryMode, hSetBuffering,
                                               stdout)
import qualified System.IO.Strict             as Strict
import           System.Process               (runInteractiveProcess,
                                               showCommandForUser, system,
                                               waitForProcess)
import           Text.ParserCombinators.ReadP (eof, readP_to_S, skipSpaces)
import           Text.Printf                  (printf)

data Brent = Install
             { pkg      :: String
             , instArgs :: [String]
             }
           | Switch
             { prog       :: String
             , versionNum :: Maybe String
             , stow       :: Maybe FilePath
             }
           | BFR
             { branch  :: Maybe String
             , commits :: [String]
             }
  deriving (Data, Typeable, Show)

installMode :: Brent
installMode = Install { pkg = def &= argPos 0 &= typ "PACKAGE"

                      , instArgs = def &= args &= typ "FLAGS"
                      }

switchMode :: Brent
switchMode = Switch { prog       = "ghc" &= typ "PROGRAM"
                    , versionNum = def &= typ "VERSION"
                    , stow       = def
                                   &= typ "DIR"
                                   &= help "Location of stowed packages"
                    }

bfrMode :: Brent
bfrMode = BFR
  { branch  = def &= typ "BRANCH" &= help "Branch from which to make the release."
  , commits = def &= args
  }

makeLensesFor [("versionBranch", "versionBranch_")] ''Version

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  a <- cmdArgs (modes [installMode, switchMode, bfrMode])
  case a of
    Install p args    -> tryInstall p args
    Switch p ver sDir -> do
      env <- getEnvironment
      let stowEnv = lookup "STOW" env
          sDir'   = case (stowEnv, sDir) of
                    (_, Just d) -> d
                    (Just d, _) -> d
                    _           -> "/scratch/local/stow"
      switch p ver sDir'
    BFR br cs -> bugFixRelease br cs

------------------------------------------------------------
--  Utilities
------------------------------------------------------------

(==>) :: a -> b -> (a,b)
(==>) = (,)

choices :: MonadIO m => [(String, m a)] -> m a
choices cs = do
  inp <- liftIO $ do
    printChoices (map fst cs)
    putStr "> "
    getLine
  case readMay inp of
    Just n  -> snd (cs !! n)
    Nothing -> choices cs

printChoices :: [String] -> IO ()
printChoices = mapM_ printChoice . zip [0::Int ..]
  where printChoice (i, s) = putStrLn (printf "%2d" i ++ ") " ++ s)

------------------------------------------------------------
--  Install
------------------------------------------------------------

tryInstall :: String -> [String] -> IO ()
tryInstall p args = do
  let args' = unwords args
  exit <- system $ "cabal install --dry-run " ++ p ++ " " ++ args' ++ " | highlight-versions"
  case exit of
    ExitSuccess -> do
      choices [ "Proceed with installation" ==> doInstall p args
              , "Another dry run"           ==> tryInstall p args
              , "Quit"                      ==> return ()
              ]
    _           -> do
      choices [ "Try dry run again" ==> tryInstall p args
              , "Quit"              ==> return ()
              ]

doInstall :: String -> [String] -> IO ()
doInstall p args = do
  let args' = unwords args
  exit <- system $ "cabal install " ++ p ++ " " ++ args'
  case exit of
    ExitSuccess -> return ()
    _           -> do
      choices [ "Another dry run" ==> tryInstall p args
              , "Try install again" ==> doInstall p args
              , "Quit" ==> return ()
              ]

------------------------------------------------------------
--  Stow switch
------------------------------------------------------------

switch :: String -> Maybe String -> FilePath -> IO ()
switch p (Just ver) sDir = doSwitch p ver sDir
switch p Nothing    sDir = do
  fs <- namesMatching $ sDir </> (p ++ "-*")
  let vers = sort . map (drop (length p + 1) . takeFileName) $ fs
  choices $ ("Quit", return ()) : map (\v -> (v, doSwitch p v sDir)) vers

doSwitch :: String -> String -> FilePath -> IO ()
doSwitch p ver sDir = do
  _ <- system $ "cd " ++ sDir ++ " && stow -D \"" ++ p ++ "-`" ++ p ++ " --numeric-version`\" && stow \"" ++ p ++ "-" ++ ver ++ "\""
  return ()

------------------------------------------------------------
--  Bug fix release
------------------------------------------------------------

execMaybeT :: MaybeT IO a -> IO ()
execMaybeT = (>> return ()) . runMaybeT

bugFixRelease :: Maybe String -> [String] -> IO ()
bugFixRelease Nothing _    = execMaybeT $ do
  (out,_) <- cmdQ "git" [] ["branch"]
  let branches = map (drop 2) . lines $ out
      branchChoices = map (\b -> b ==> (liftIO $ bugFixRelease (Just b) [])) branches
  liftIO $ putStrLn "Please choose a release branch:"
  choices $ [ "Quit" ==> return () ] ++ branchChoices

bugFixRelease (Just br) cs' = execMaybeT $ do

  -- Set up/pull
  git ["checkout", br]
  git ["pull"]
  git ["checkout", "master"]
  git ["pull"]

  -- Choose commits from master to cherry-pick
  cs <- case (br, cs') of
    ("master", _) -> return cs'
    (_, (_:_)) -> return cs'
    (_, []   ) -> do
      (out,_) <- cmdQ "git" [] ["--no-pager", "log", "--pretty=oneline", "--abbrev-commit"]
      let commits = lines out
      liftIO $ zipWithM_ (\i c -> putStrLn (show i ++ ") " ++ c)) [0..] (take 10 commits)
      liftIO $ putStr "Please choose commits to cherry-pick: " >> hFlush stdout
      let toCommit s
            | length s == 1 = (commits !!) <$> readMay s
            | otherwise     = find (s `isPrefixOf`) commits
      chosenCommits <- mapMaybe toCommit . words <$> liftIO getLine
      liftIO $ putStrLn "Cherry-picking commits:"
      liftIO $ mapM_ (putStrLn . ("  "++)) chosenCommits
      return $ map (head . words) chosenCommits

  -- Cherry-pick
  git ["checkout", br]
  forM_ cs $ \c -> git ["cherry-pick", "-x", c]

  -- Test build
  confirmOrSkip "Test build" $ do

    sandbox ["init"]
    cabal ["install", "--enable-tests", "--only-dependencies", "--dry-run"]
    confirm "Continue"

    cabal ["install", "--enable-tests", "--only-dependencies", "-j8"]
    cabal ["configure", "--enable-tests"]
    cabal ["build"]
    cabal ["test"]

  cabalFile <- findCabalFile

  -- Increment version
  ver <- confirmOrElse "Increment version" (readVersion cabalFile) $ do

    ver' <- incrementVersion cabalFile
    git ["add", cabalFile]
    git ["commit", "-m", "Bump version to " ++ ver']

    -- Edit release notes
    confirmOrSkip "Edit release notes" $ do

      git ["checkout", "master"]
      changesFile <- findChangesFile
      addRelease ver' cs changesFile
      emacs [changesFile]
      git ["add", changesFile]
      git ["commit", "-m", "Release notes for " ++ ver']
      (out, _) <- git ["--no-pager", "log", "-n1", "--pretty=oneline"]
      let changesCommit = takeWhile (not . isSpace) out

      -- Pull release notes update into branch
      when (br /= "master") $ confirmOrSkip "Cherry-pick release notes into release branch" $ do
        git ["checkout", br]
        git ["cherry-pick", "-x", changesCommit]

    -- Tag
    confirmOrSkip "Tag" $ do
      git ["tag", "-m", ver' ++ " release", "v" ++ ver']

    return ver'

  -- Push commits
  confirmOrSkip "Push" $ do

    git $ ["push", "origin", "master"] ++ [ br | br /= "master" ]
    git ["push", "--tags"]

  -- Upload package
  confirmOrSkip "Upload" $ do

    pkg <- getPackageName cabalFile
    cabal ["sdist"]
    cabal ["upload", "dist/" ++ pkg ++ "-" ++ ver ++ ".tar.gz"]

  -- clean up
  git ["checkout", "master"]

findCabalFile :: MaybeT IO FilePath
findCabalFile = do
  fs <- liftIO $ namesMatching "*.cabal"
  case fs of
    []    -> mzero
    (f:_) -> return f

readVersion :: FilePath -> MaybeT IO String
readVersion cabalFile = do
  c <- liftIO $ Strict.readFile cabalFile
  let (before, vLine:after) = break (("version:" `isPrefixOf`) . map toLower)
                            . lines $ c
      (verField, vStr) = break isDigit vLine
  return vStr

incrementVersion :: FilePath -> MaybeT IO String
incrementVersion cabalFile = do
  c <- liftIO $ Strict.readFile cabalFile
  let (before, vLine:after) = break (("version:" `isPrefixOf`) . map toLower)
                            . lines $ c
      (verField, vStr) = break isDigit vLine
  v <- case readP_to_S (parseVersion <* skipSpaces <* eof) vStr of
         []        -> mzero
         ((x,_):_) -> return x
  let vStr' = showVersion . incVersion $ v
  liftIO . writeFile cabalFile . unlines $ before ++ ((verField ++ vStr') : after)
  return vStr'

incVersion :: Version -> Version
incVersion = versionBranch_ %~ ((element 3 %~ (+1)) . extend)
  where
    extend = take 4 . (++repeat 0)

findChangesFile :: MaybeT IO FilePath
findChangesFile = do
  fs <- liftIO $ namesMatching "CHANGES*"
  case listToMaybe (filter (not . ("~" `isSuffixOf`)) fs) of
    Nothing -> mzero
    Just c  -> return c

-- XXX improve
addRelease :: String -> [String] -> FilePath -> MaybeT IO ()
addRelease ver cs changesFile = do
  (date,_) <- cmdQ "date" [] ["+%-d %B %Y"]
  changes  <- liftIO $ Strict.readFile changesFile
  let title  = ver ++ " (" ++ trim date ++ ")"
      header = unlines [title, replicate (length title) '-', ""]

  rawNotes <- forM cs $ \c -> git ["show", "-s", c]
  let notes = unlines . map fst $ rawNotes
  liftIO $ writeFile changesFile (header ++ notes ++ changes)

getPackageName :: FilePath -> MaybeT IO String
getPackageName cabalFile = do
  c <- liftIO $ Strict.readFile cabalFile
  let pLine = head . filter (("name:" `isPrefixOf`) . map toLower) . lines $ c
      name  = trim . drop 5 $ pLine
  return name

rm       = cmd "rm" []
git      = cmd "git" []
sandbox  = cmd "cabal" ["sandbox"]
emacs    = cmd "emacs" []
cabal    = cmd "cabal" []

cmd :: String -> [String] -> [String] -> MaybeT IO (String, String)
cmd = cmdG True

cmdQ :: String -> [String] -> [String] -> MaybeT IO (String, String)
cmdQ = cmdG False

cmdG :: Bool -> String -> [String] -> [String] -> MaybeT IO (String, String)
cmdG v c args1 args2 = do
  liftIO . putStrLn . ("==== " ++) $ intercalate " " (c : args1 ++ args2)
  (inp,out,err,pid) <- liftIO $ runInteractiveProcess c (args1 ++ args2) Nothing Nothing
  liftIO $ hSetBinaryMode out False >> hSetBinaryMode err False
  outStr <- liftIO $ Strict.hGetContents out
  errStr <- liftIO $ Strict.hGetContents err
  when v $ liftIO $ putStr outStr
  e <- liftIO $ waitForProcess pid
  case e of
    ExitSuccess   -> return (outStr,errStr)
    ExitFailure _ -> do
      liftIO $ print e >> putStr errStr
      mzero

confirm :: String -> MaybeT IO ()
confirm go =
  choices
  [ go     ==> return ()
  , "Quit" ==> mzero
  ]

confirmOrSkip :: String -> MaybeT IO a -> MaybeT IO ()
confirmOrSkip go next =
  choices
  [ go     ==> (next >> return ())
  , "Skip" ==> return ()
  , "Quit" ==> mzero
  ]

confirmOrElse :: String -> MaybeT IO a -> MaybeT IO a -> MaybeT IO a
confirmOrElse go els next =
  choices
  [ go     ==> next
  , "Skip" ==> els
  , "Quit" ==> mzero
  ]

trim  = swop . swop
swop  = reverse . dropWhile isSpace