Skip to content

Instantly share code, notes, and snippets.

@Kiwi
Last active June 11, 2019 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kiwi/5e8ce26a765720d6116e1fe572acf712 to your computer and use it in GitHub Desktop.
Save Kiwi/5e8ce26a765720d6116e1fe572acf712 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text
import qualified Data.Text.IO
filterImports :: Text -> Maybe Text
filterImports t =
let a = fst $ Data.Text.breakOn "(" t
in if Data.Text.isPrefixOf "import" a
then Just $ Data.Text.strip a
else Nothing
adjustText :: Text -> Text
adjustText oldText = newText
where
oldLines = Data.Text.lines oldText
newLines = mapMaybe filterImports oldLines
newText = Data.Text.unlines newLines
main :: IO ()
main = Data.Text.IO.interact adjustText
{-# LANGUAGE OverloadedStrings #-}
module Main where
-- Main.imports
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import qualified Data.Text
( breakOnEnd
, isPrefixOf
, isSuffixOf
, lines
, pack
, strip
, unpack
)
import qualified Data.Text.IO (getContents, putStrLn, readFile)
import System.Directory (getCurrentDirectory)
import System.Directory.Extra (listFilesRecursive)
import System.FilePath (takeFileName)
headMay :: [a] -> Maybe a
headMay [] = Nothing
headMay (x:xs) = Just x
findFile :: (FilePath -> Bool) -> FilePath -> IO (Maybe FilePath)
findFile p path = do
names <- listFilesRecursive path
return $ headMay (filter p names)
findImportsFile :: Text -> IO (Maybe FilePath)
findImportsFile f = do
cd <- getCurrentDirectory
findFile (\x -> takeFileName x == (Data.Text.unpack f :: FilePath)) cd
filterImportsName :: Text -> Maybe Text
filterImportsName t = name
where
isComment = Data.Text.isPrefixOf "--" t
isImport = Data.Text.isSuffixOf ".imports" t
name =
if isComment && isImport
then Just $ Data.Text.strip $ snd $ Data.Text.breakOnEnd "--" t
else Nothing
main :: IO ()
main = do
input <- Data.Text.IO.getContents
let importFileName = mapMaybe filterImportsName $ Data.Text.lines input
importFile <-
case headMay importFileName of
Nothing -> return Nothing
Just file -> findImportsFile file
importContents <-
case importFile of
Nothing -> return input
Just file -> do
x <- Data.Text.IO.readFile file
return $ "-- " <> Data.Text.pack (takeFileName file) <> "\n" <> x
let output = importContents
Data.Text.IO.putStrLn output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment