79 lines
2.1 KiB
Haskell
79 lines
2.1 KiB
Haskell
{-# LANGUAGE LambdaCase #-}
|
|
|
|
module Main where
|
|
|
|
import Options.Applicative
|
|
import SortImports (sortImports)
|
|
import System.Environment (getArgs)
|
|
import System.IO (hReady, stdin)
|
|
import SortImports.Types (Qualified(..))
|
|
|
|
versionNumber :: String
|
|
versionNumber = "v1.2.0"
|
|
|
|
version :: Parser Mode
|
|
version = flag' Version $ mconcat
|
|
[ long "version"
|
|
, short 'v'
|
|
, help "Version number"
|
|
]
|
|
|
|
data Mode
|
|
= Version
|
|
| FileInput FilePath
|
|
| StdInput
|
|
|
|
data Options = Options
|
|
{ _options_mode :: Mode
|
|
, _options_convert :: Maybe Qualified
|
|
}
|
|
|
|
fileInput :: Parser Mode
|
|
fileInput = FileInput <$> strOption (mconcat
|
|
[ long "file"
|
|
, short 'f'
|
|
, metavar "FILENAME"
|
|
, help "Input file"
|
|
])
|
|
|
|
stdInput :: Parser Mode
|
|
stdInput = flag' StdInput $ mconcat
|
|
[ long "stdin"
|
|
, help "Read input from stdin"
|
|
]
|
|
|
|
convertToQualifiedPost :: Parser Bool
|
|
convertToQualifiedPost = switch (long "convert-to-qualified-post" <> help "Whether to convert all qualified imports to use ImportQualifiedPost")
|
|
|
|
convertToQualifiedPre :: Parser Bool
|
|
convertToQualifiedPre = switch (long "convert-to-qualified-pre" <> help "Whether to convert all ImportQualifiedPost imports to use older \"import qualified\" syntax")
|
|
|
|
options :: Parser Options
|
|
options = Options
|
|
<$> (version <|> fileInput <|> stdInput)
|
|
<*> (post <|> pre)
|
|
where
|
|
post = ((\x -> if x then Just Qualified_Post else Nothing) <$> convertToQualifiedPost)
|
|
pre = ((\x -> if x then Just Qualified_Pre else Nothing) <$> convertToQualifiedPre)
|
|
|
|
run :: Options -> IO ()
|
|
run opts = case _options_mode opts of
|
|
Version -> putStrLn versionNumber
|
|
FileInput path -> readFile path >>= putStr . (sortImports convert)
|
|
StdInput -> interact (sortImports convert)
|
|
where
|
|
convert = _options_convert opts
|
|
|
|
main :: IO ()
|
|
main = do
|
|
noArgs <- null <$> getArgs
|
|
anyStdin <- hReady stdin
|
|
if noArgs && anyStdin
|
|
then run (Options StdInput Nothing)
|
|
else execParser opts >>= run
|
|
where opts = info (options <**> helper) $ mconcat
|
|
[ briefDesc
|
|
, header "sort-imports - Sort Haskell import statements"
|
|
, footer "Input is read from stdin by default if no arguments are provided."
|
|
]
|