2021-09-14 21:56:10 -04:00
{- # LANGUAGE LambdaCase # -}
module Main where
import Options.Applicative
import SortImports ( sortImports )
import System.Environment ( getArgs )
import System.IO ( hReady , stdin )
2023-07-24 11:36:19 -04:00
import SortImports.Types ( Qualified ( .. ) )
2021-09-14 21:56:10 -04:00
versionNumber :: String
versionNumber = " v1.2.0 "
2023-07-24 11:36:19 -04:00
version :: Parser Mode
2021-09-14 21:56:10 -04:00
version = flag' Version $ mconcat
[ long " version "
, short 'v'
, help " Version number "
]
2023-07-24 11:36:19 -04:00
data Mode
2021-09-14 21:56:10 -04:00
= Version
| FileInput FilePath
| StdInput
2023-07-24 11:36:19 -04:00
data Options = Options
{ _options_mode :: Mode
, _options_convert :: Maybe Qualified
}
fileInput :: Parser Mode
2021-09-14 21:56:10 -04:00
fileInput = FileInput <$> strOption ( mconcat
[ long " file "
, short 'f'
, metavar " FILENAME "
, help " Input file "
] )
2023-07-24 11:36:19 -04:00
stdInput :: Parser Mode
2021-09-14 21:56:10 -04:00
stdInput = flag' StdInput $ mconcat
[ long " stdin "
, help " Read input from stdin "
]
2023-07-24 11:36:19 -04:00
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 " )
2021-09-14 21:56:10 -04:00
options :: Parser Options
2023-07-24 11:36:19 -04:00
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 )
2021-09-14 21:56:10 -04:00
run :: Options -> IO ()
2023-07-24 11:36:19 -04:00
run opts = case _options_mode opts of
2021-09-14 21:56:10 -04:00
Version -> putStrLn versionNumber
2023-07-24 11:36:19 -04:00
FileInput path -> readFile path >>= putStr . ( sortImports convert )
StdInput -> interact ( sortImports convert )
where
convert = _options_convert opts
2021-09-14 21:56:10 -04:00
main :: IO ()
main = do
noArgs <- null <$> getArgs
anyStdin <- hReady stdin
if noArgs && anyStdin
2023-07-24 11:36:19 -04:00
then run ( Options StdInput Nothing )
2021-09-14 21:56:10 -04:00
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. "
]