-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCompile.hs
68 lines (60 loc) · 2.31 KB
/
Compile.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module LambdaBuffers.Compiler.Cli.Compile (CompileOpts (..), compile) where
import Control.Lens (makeLenses, (^.))
import Data.ByteString qualified as BS
import Data.ProtoLens qualified as Pb
import Data.ProtoLens.TextFormat qualified as PbText
import Data.Text.Lazy qualified as Text
import Data.Text.Lazy.IO qualified as Text
import LambdaBuffers.Compiler (runCompiler)
import Proto.Compiler (Input, Output)
import Proto.Compiler_Fields (maybe'error)
import System.Exit (exitFailure)
import System.FilePath.Lens (extension)
data CompileOpts = CompileOpts
{ _input :: FilePath
, _output :: FilePath
, _debug :: Bool
}
deriving stock (Eq, Show)
makeLenses ''CompileOpts
logInfo :: FilePath -> String -> IO ()
logInfo "" msg = putStrLn $ msg <> " [INFO]"
logInfo fp msg = putStrLn $ fp <> ": " <> msg <> " [INFO]"
logError :: FilePath -> String -> IO ()
logError "" msg = putStrLn $ msg <> " [ERROR]"
logError fp msg = putStrLn $ fp <> ": " <> msg <> " [ERROR]"
-- | Compile LambdaBuffers modules
compile :: CompileOpts -> IO ()
compile opts = do
logInfo "" $ "Reading Compiler Input from " <> (opts ^. input)
compInp <- readCompilerInput (opts ^. input)
let compOut = runCompiler (opts ^. debug) compInp
case compOut ^. maybe'error of
Nothing -> do
logInfo (opts ^. input) "Compilation succeeded"
Just _ -> do
logError (opts ^. input) "Compilation failed"
logInfo "" $ "Writing Compiler Output at " <> (opts ^. output)
writeCompilerOutput (opts ^. output) compOut
readCompilerInput :: FilePath -> IO Input
readCompilerInput fp = do
let ext = fp ^. extension
case ext of
".pb" -> do
content <- BS.readFile fp
return $ Pb.decodeMessageOrDie content
".textproto" -> do
content <- Text.readFile fp
return $ PbText.readMessageOrDie content
_ -> do
logError "" $ "Unknown Compiler Input format, wanted .pb or .textproto but got " <> ext <> " (" <> fp <> ")"
exitFailure
writeCompilerOutput :: FilePath -> Output -> IO ()
writeCompilerOutput fp cr = do
let ext = fp ^. extension
case ext of
".pb" -> BS.writeFile fp (Pb.encodeMessage cr)
".textproto" -> Text.writeFile fp (Text.pack . show $ PbText.pprintMessage cr)
_ -> do
logError "" $ "Unknown Codegen Input format, wanted .pb or .textproto but got " <> ext <> " (" <> fp <> ")"
exitFailure