summary history branches tags files
commit:70645c14473d325772dc3bc1ff7e43f6d9910cfe
author:avh4
committer:avh4
date:Sun Jan 22 16:15:52 2023 -0800
parents:b4645f780dd867207fd8177dc4ec3f9e3f3cef74
Separate collectGcroot and printGcroot
diff --git a/sizer.hs b/sizer.hs
line changes: +26/-7
index f6c9d7f..356c397
--- a/sizer.hs
+++ b/sizer.hs
@@ -1,7 +1,7 @@
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE RecordWildCards #-}
 
-import Control.Exception (IOException, try)
+import Control.Exception (Exception, IOException, try, throwIO)
 import Data.Aeson qualified as Aeson
 import Data.Aeson (ToJSON(..), FromJSON(..), Value(..), (.:), (.=), object)
 import Data.Aeson.Types (prependFailure, typeMismatch)
@@ -39,12 +39,17 @@ isBrokenLink path = do
     else
       return False
 
-collectAndPrintGcroot :: FilePath -> IO ()
-collectAndPrintGcroot gcroot = do
+data Gcroot = Gcroot
+  { gcrootPath :: FilePath
+  , gcrootDependencies :: [PathInfo]
+  }
+
+collectGcroot :: FilePath -> IO (Maybe Gcroot)
+collectGcroot gcroot = do
   isBroken <- isBrokenLink gcroot
   if isBroken
     then
-      return ()
+      return Nothing
     else do
       (json, _) <- readProcess_ $ proc "nix" [ "--extra-experimental-features", "nix-command"
                                             , "path-info"
@@ -54,12 +59,26 @@ collectAndPrintGcroot gcroot = do
                                             , gcroot
                                             ]
       let pathInfos_ = Aeson.eitherDecode json :: Either String [PathInfo]
-      putStr (gcroot <> ": ")
       case pathInfos_ of
         Left err ->
-          putStrLn ("ERROR: " <> err)
+          throwIO $ PathInfoException err
         Right pathInfos ->
-          putStrLn $ formatFileSize $ totalSize pathInfos
+          return $ Just $ Gcroot gcroot pathInfos
+
+data PathInfoException =
+  PathInfoException String
+  deriving (Show)
+
+instance Exception PathInfoException
+
+printGcroot :: Gcroot -> IO ()
+printGcroot gcroot = do
+  putStr (gcrootPath gcroot <> ": ")
+  putStrLn $ formatFileSize $ totalSize (gcrootDependencies gcroot)
+
+collectAndPrintGcroot :: FilePath -> IO ()
+collectAndPrintGcroot gcroot =
+  maybe (return ()) printGcroot =<< collectGcroot gcroot
 
 totalSize :: (Foldable f, Functor f) => f PathInfo -> Int
 totalSize = sum . fmap pathInfoNarSize