-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathMain.hs
420 lines (343 loc) · 12.1 KB
/
Main.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
{-# language LambdaCase #-}
{-# language NoMonomorphismRestriction #-}
{-# language NamedFieldPuns #-}
{-# language OverloadedStrings #-}
{-# language RecordWildCards #-}
{-# language ViewPatterns #-}
module Main ( main ) where
import Control.Applicative ( (<**>), optional, (<|>) )
import Control.Monad ( join )
import Data.Char ( isAlphaNum )
import Data.Foldable ( asum, foldl' )
import Data.Function ( (&) )
import Data.Maybe ( fromMaybe )
import Data.String ( fromString )
import Data.Version ( showVersion )
import Lens.Micro ( set )
import System.Directory ( createDirectoryIfMissing )
import System.FilePath ( (</>), (<.>), addTrailingPathSeparator, normalise, takeDirectory )
import CabalToDhall ( KnownDefault, getDefault, resolvePreludeVar )
import DhallLocation ( preludeLocation, typesLocation, dhallFromGitHub )
import DhallToCabal
import DhallToCabal.FactorType ( KnownType(..), factored, mapWithBindings )
import DhallToCabal.Util ( relativeTo )
import qualified Paths_dhall_to_cabal as Paths
import qualified Data.Text.IO as StrictText
import qualified Data.Text.Prettyprint.Doc as Pretty
import qualified Data.Text.Prettyprint.Doc.Render.Text as Pretty
import qualified Dhall
import qualified Dhall.Core as Dhall
import qualified Dhall.Core as Expr ( Expr(..) )
import qualified Dhall.Lint as Lint
import qualified Dhall.Parser
import qualified Distribution.PackageDescription as Cabal
import qualified Distribution.PackageDescription.PrettyPrint as Cabal
import qualified Distribution.Types.PackageId as Cabal
import qualified Distribution.Types.PackageName as Cabal
import qualified Options.Applicative as OptParse
import qualified System.IO
data Command
= RunDhallToCabal DhallToCabalOptions
| PrintType PrintTypeOptions
| PrintDefault PrintDefaultOptions
| PrintVersion
shouldBeImported :: KnownType -> Bool
shouldBeImported Extension = True
shouldBeImported LicenseId = True
shouldBeImported LicenseExceptionId = True
shouldBeImported _ = False
data DhallToCabalOptions = DhallToCabalOptions
{ dhallFilePath :: Maybe String
, explain :: Bool
, outputDirection :: OutputDirection
}
data OutputDirection
= OutputStdout
| OutputDir RelativeDir
data RelativeDir
= RelativeToCWD FilePath
| RelativeToInput FilePath
dhallToCabalOptionsParser :: OptParse.Parser DhallToCabalOptions
dhallToCabalOptionsParser =
DhallToCabalOptions
<$>
optional
( OptParse.argument
OptParse.str
( mconcat
[ OptParse.metavar "<dhall input file>"
, OptParse.help "The Dhall expression to convert to a Cabal file"
]
)
)
<*>
OptParse.flag
False
True
( mconcat
[ OptParse.long "explain"
, OptParse.help "Provide explanations to type Dhall syntax and type errors."
]
)
<*>
outputDirectionParser
where
-- Note order: the --output-dir-input does not fail because it has a default value.
outputDirectionParser =
OptParse.flag'
OutputStdout
( mconcat
[ OptParse.long "output-stdout"
, OptParse.help "Write the .cabal file to standard output."
]
)
<|> OutputDir . RelativeToCWD <$> OptParse.strOption
( mconcat
[ OptParse.long "output-dir-cwd"
, OptParse.metavar "DIR"
, OptParse.help "Write the resulting .cabal file to DIR/NAME.cabal, where NAME is taken from the .cabal file's 'name' field, and DIR is relative to the current working directory."
]
)
<|> OutputDir . RelativeToInput <$> OptParse.strOption
( mconcat
[ OptParse.long "output-dir-input"
, OptParse.metavar "DIR"
, OptParse.help "Write the resulting .cabal file to DIR/NAME.cabal, where NAME is taken from the .cabal file's 'name' field, and DIR is relative to the directory containing the input Dhall file (or the current working directory if the input is from standard input)."
, OptParse.value "."
]
)
data PrintTypeOptions = PrintTypeOptions
{ typeToPrint :: KnownType
, selfContained :: Bool
}
printTypeOptionsParser :: OptParse.Parser PrintTypeOptions
printTypeOptionsParser =
PrintTypeOptions
<$>
OptParse.option OptParse.auto modifiers
<*>
OptParse.flag
False
True
( mconcat
[ OptParse.long "self-contained"
, OptParse.help "Emit self-contained types. Without this flag, some large enumerations are referenced by import."
]
)
where
modifiers =
mconcat
[ OptParse.long "print-type"
, OptParse.help "Print out the description of a type. For a full description, try --print-type Package"
, OptParse.metavar "TYPE"
]
printVersionParser :: OptParse.Parser ()
printVersionParser =
OptParse.flag'
()
( mconcat
[ OptParse.long "version"
, OptParse.help "Display dhall-to-cabal's version and exit."
]
)
data PrintDefaultOptions =
PrintDefaultOptions
{ defaultToPrint :: KnownDefault }
printDefaultOptionsParser :: OptParse.Parser PrintDefaultOptions
printDefaultOptionsParser =
PrintDefaultOptions
<$>
OptParse.option OptParse.auto
( mconcat
[ OptParse.long "print-default"
, OptParse.help "Print out the default values for a type, as found in prelude.defaults"
, OptParse.metavar "TYPE"
]
)
runDhallToCabal :: DhallToCabalOptions -> IO ()
runDhallToCabal DhallToCabalOptions { dhallFilePath, explain, outputDirection } = do
source <-
case dhallFilePath of
Nothing ->
StrictText.getContents
Just filePath ->
StrictText.readFile filePath
let
settings = Dhall.defaultInputSettings
& set Dhall.rootDirectory inputDir
& set Dhall.sourceName ( fromMaybe "(STDIN)" dhallFilePath )
pkgDesc <- explaining ( dhallToCabal settings source )
let
rendered =
addWarningHeader
( Cabal.showGenericPackageDescription pkgDesc )
case outputDirection of
OutputStdout ->
putStrLn rendered
OutputDir _ -> do
createDirectoryIfMissing True destDir
let dest = destDir </> pkgDescName pkgDesc <.> "cabal"
putStrLn ( "Writing to " ++ normalise dest ++ "." )
writeFile dest rendered
where
inputDir = maybe "." takeDirectory dhallFilePath
destDir =
case outputDirection of
OutputStdout ->
"."
OutputDir (RelativeToCWD dir) ->
dir
OutputDir (RelativeToInput relativeDir) ->
inputDir </> relativeDir
explaining =
if explain then Dhall.detailed else id
pkgDescName = Cabal.unPackageName . Cabal.pkgName . Cabal.package . Cabal.packageDescription
-- Make sure that the displayed source path is copy-pasteable to
-- the command line, and won't break the generated Cabal
-- file. This is a somewhat conservative check.
isAcceptableCommentChar c =
isAlphaNum c || c == '.' || c == '/' || c == '_' || c == '-'
-- These regeneration instructions assume that (a) if we are
-- writing to stdout, the user is redirecting it a file in the
-- current directory, (b) the generated file is not moved after we
-- produce it, (c) there are no symlinks breaking .. components,
-- and (d) they will run the regeneration instructions from the
-- directory of the generated .cabal file.
--
-- These assumptions are necessarily approximations, but they're a
-- reasonable guess at the common case and at least give the user
-- something to go on.
regenerationInstructions =
case dhallFilePath of
Just filePath | all isAcceptableCommentChar filePath ->
[ "-- Instead, edit the source Dhall file, namely"
, "-- '" ++ filePath ++ "', and re-generate this file by running"
, "-- 'dhall-to-cabal -- " ++ sourcePath ++ "'."
]
where
sourcePath =
relativeTo ( addTrailingPathSeparator destDir ) filePath
_ ->
[ "-- Instead, edit the source Dhall file (which may have the"
, "-- '.dhall' extension) and re-run dhall-to-cabal, passing "
, "-- the source file's name as its argument."
]
-- Starting with Cabal 2.2, the cabal-version field *has* to be
-- the first thing in the .cabal file. So split that off and plonk
-- the warning header after it.
addWarningHeader str =
case lines str of
[] ->
error "addWarningHeader: no cabal-version line found?"
cabalVersion : rest ->
unlines $ concat
[ [ cabalVersion
, "-- * * * * * * * * * * * * WARNING * * * * * * * * * * * *"
, "-- This file has been AUTO-GENERATED by dhall-to-cabal."
, "--"
, "-- Do not edit it by hand, because your changes will be over-written!"
, "--"
]
, regenerationInstructions
, [ "-- * * * * * * * * * * * * WARNING * * * * * * * * * * * *" ]
, rest
]
main :: IO ()
main = do
command <-
OptParse.execParser opts
case command of
RunDhallToCabal options ->
runDhallToCabal options
PrintType options ->
printType options
PrintDefault options ->
printDefault options
PrintVersion ->
printVersion
where
parser =
asum
[ RunDhallToCabal <$> dhallToCabalOptionsParser
, PrintType <$> printTypeOptionsParser
, PrintDefault <$> printDefaultOptionsParser
, PrintVersion <$ printVersionParser
]
opts =
OptParse.info ( parser <**> OptParse.helper ) modifiers
modifiers =
mconcat
[ OptParse.progDesc "Generate Cabal files from Dhall expressions"
, OptParse.footer
( "The default behaviour is to generate a .cabal file in the "
++ "directory of the input file with a name corresponding to the "
++ "'name' field of the generated package description (i.e., the "
++ "same behaviour as specifying '--output-dir-input .'). In the "
++ "case of reading from standard input, the .cabal file will be "
++ "placed in the current working directory."
)
]
-- Shamelessly taken from dhall-format
opts :: Pretty.LayoutOptions
opts =
Pretty.defaultLayoutOptions
{ Pretty.layoutPageWidth = Pretty.AvailablePerLine 80 1.0 }
printType :: PrintTypeOptions -> IO ()
printType PrintTypeOptions { .. } = do
Pretty.renderIO
System.IO.stdout
( Pretty.layoutSmart opts
( Pretty.pretty ( Lint.lint result ) )
)
putStrLn ""
where
linkedType =
join . mapWithBindings linkType . factored
linkType var t =
let
name = fromString ( show t )
in if shouldBeImported t && not selfContained
then Expr.Var ( var "types" ) `Expr.Field` name
else Expr.Var ( var name )
bindTypes expr =
foldl' bindType expr [ minBound .. maxBound ]
bindType expr t =
Expr.Let
( Dhall.makeBinding
( fromString ( show t ) )
( linkedType t )
)
expr
bindImport =
Expr.Let
( Dhall.makeBinding
"types"
( Expr.Embed ( typesLocation dhallFromGitHub ) )
)
-- Unconditionally add everything, since lint will remove the
-- redundant bindings.
result =
bindImport
( bindTypes ( linkedType typeToPrint ) )
printVersion :: IO ()
printVersion = do
putStrLn ( "dhall-to-cabal version " ++ showVersion Paths.version )
printDefault :: PrintDefaultOptions -> IO ()
printDefault PrintDefaultOptions {..} = do
Pretty.renderIO
System.IO.stdout
( Pretty.layoutSmart opts
( Pretty.pretty ( Lint.lint ( withPreludeImport expr ) ) )
)
putStrLn ""
where
withPreludeImport =
Expr.Let
( Dhall.makeBinding
"prelude"
( Expr.Embed ( preludeLocation dhallFromGitHub ) )
)
expr :: Expr.Expr Dhall.Parser.Src Dhall.Import
expr = getDefault
( typesLocation dhallFromGitHub )
resolvePreludeVar defaultToPrint