Skip to content

Instantly share code, notes, and snippets.

@shuhei
Created September 17, 2016 07:48
Show Gist options
  • Save shuhei/125ee591163f13d39168cfb89c996ab0 to your computer and use it in GitHub Desktop.
Save shuhei/125ee591163f13d39168cfb89c996ab0 to your computer and use it in GitHub Desktop.
Count import statements: an exercise of http://qiita.com/hiratara/items/169b5cb83b0adbfda764
#!/usr/bin/env stack
-- stack --resolver lts-7.0 --install-ghc runghc --package turtle
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding (FilePath)
import qualified Control.Foldl as Fold
import Turtle
import Data.Maybe (fromMaybe)
main :: IO ()
main = do
(maybeDir, showModule) <- options "Count imports" parser
let dir = fromText $ fromMaybe "." maybeDir
sink = if showModule then dump else wc
sink (extractImports dir) & sh
dump :: Shell Text -> Shell ()
dump importLines =
let pat = (("import " <> option "qualified ") *> "") <> plus ( noneOf " ")
in importLines & sed (prefix pat) & stdout
wc :: Shell Text -> Shell ()
wc importLines =
importLines & flip fold Fold.length & view
extractImports :: FilePath -> Shell Text
extractImports dir =
findFiles "hs" dir & xargsGrep (prefix "import ")
findFiles :: Pattern Text -> FilePath -> Shell FilePath
findFiles ext path =
let pat = suffix ("." <> ext)
in find pat path
xargsGrep :: Pattern Text -> Shell FilePath -> Shell Text
xargsGrep pat files = do
file <- files
input file & grep pat
parser :: Parser (Maybe Text, Bool)
parser = (,) <$> optional (optText "dir" 'd' "directory to count")
<*> switch "show" 's' "show module names"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment