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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- | A general purpose build tool.
--
-- : out bild
-- : dep conduit
-- : dep conduit-extra
-- : dep docopt
-- : dep regex-applicative
-- : dep rainbow
-- : dep tasty
-- : dep tasty-hunit
--
-- == Design constraints
--
-- * only input is one or more a namespaces. no subcommands, no packages
--
-- * no need to write specific build rules
--
-- * one rule for hs, one for rs, one for scm, and so on
--
-- * rules are written in Haskell as much as possible
--
-- * no need to distinguish between exe and lib, just have a single output
--
-- * never concerned with deployment/packaging - leave that to another tool
-- (scp? tar?)
--
-- == Features
--
-- * namespace maps to filesystem
--
-- * no need for `bild -l` for listing available targets.
-- Use `ls` or `tree`
--
-- * you build namespaces, not files/modules/packages/etc
--
-- * namespace maps to language modules
--
-- * build settings can be set in the file comments
--
-- * pwd is always considered the the source directory,
-- no `src` vs `doc` etc.
--
-- * build methods automaticatly detected with file extensions
--
-- * flags modify the way to interact with the build, some ideas:
--
-- * -s = jump into a shell and/or repl
--
-- * -p = turn on profiling
--
-- * -t = limit build by type (file extension)
--
-- * -e = exclude some regex in the ns tree
--
-- * -o = optimize level
--
-- == Example Commands
--
-- > bild [opts] <target..>
--
-- The general scheme is to build the things described by the targets. A target
-- is a namespace. You can list as many as you want, but you must list at least
-- one. It could just be `.` for the current directory. Build outputs will go
-- into the _/bild directory in the root of the project.
--
-- > bild A/B.hs
--
-- This will build the file at ./A/B.hs, which translates to something like
-- `ghc --make A.B`.
--
-- > bild -s <target>
--
-- Starts a repl/shell for target.
-- - if target.hs, load ghci
-- - if target.scm, load scheme repl
-- - if target.clj, load a clojure repl
-- - if target.nix, load nix-shell
-- - and so on.
--
-- > bild -p <target>
--
-- build target with profiling (if available)
--
-- > bild -t nix target
--
-- only build target.nix, not target.hs and so on (in the case of multiple
-- targets with the same name but different extension).
--
-- == Build Metadata
--
-- Metadata is set in the comments with a special syntax. For third-party deps,
-- we list the deps in comments in the target file, like:
--
-- > -- : dep aeson
--
-- The output executable is named with:
--
-- > -- : out my-program
--
-- or
--
-- > -- : out my-ap.js
--
-- When multiple compilers are possible (e.g. ghc vs ghcjs) we use the @out@
-- extension, for example we chose ghcjs when the target @out@ ends in .js. If
-- @out@ does not have an extension, each build type falls back to a default,
-- usually an executable binary.
--
-- This method of setting metadata in the module comments works pretty well,
-- and really only needs to be done in the entrypoint module anyway.
--
-- Local module deps are included by just giving the repo root to the underlying
-- compiler for the target, and the compiler does work of walking the source
-- tree.
module Biz.Bild where
import Alpha hiding (sym, (<.>))
import qualified Biz.Cli as Cli
import qualified Biz.Log as Log
import Biz.Namespace (Namespace (..))
import qualified Biz.Namespace as Namespace
import qualified Biz.Test as Test
import qualified Control.Concurrent.Async as Async
import qualified Data.Char as Char
import Data.Conduit ((.|))
import qualified Data.Conduit as Conduit
import qualified Data.Conduit.List as Conduit
import qualified Data.Conduit.Process as Conduit
import qualified Data.List as List
import qualified Data.String as String
import qualified Data.Text as Text
import qualified System.Directory as Dir
import qualified System.Environment as Env
import qualified System.Exit as Exit
import System.FilePath ((</>))
import qualified System.IO as IO
import qualified Text.Regex.Applicative as Regex
import qualified Prelude
main :: IO ()
main = Cli.main <| Cli.Plan help move test
where
test =
Test.group
"Biz.Bild"
[ Test.unit "can bild bild" <| do
let ns = Namespace ["Biz", "Bild"] Namespace.Hs
analyze ns >>= build False False >>= \case
Exit.ExitFailure _ -> Test.assertFailure "can't bild bild"
_ -> pure ()
]
move :: Cli.Arguments -> IO ()
move args =
IO.hSetBuffering stdout IO.NoBuffering
>> mapM getNamespace (Cli.getAllArgs args (Cli.argument "target"))
/> catMaybes
/> filter isBuildableNs
>>= mapM analyze
>>= mapM
( build
(args `Cli.has` Cli.longOption "test")
(args `Cli.has` Cli.longOption "loud")
)
>>= exitSummary
help :: Cli.Docopt
help =
[Cli.docopt|
bild
Usage:
bild test
bild [options] <target>...
Options:
--test Run tests on a target after building.
--loud Show all output from compiler.
--help Print this info
|]
exitSummary :: [Exit.ExitCode] -> IO ()
exitSummary exits =
if failures > 0
then Exit.die <| show failures
else Exit.exitSuccess
where
failures = length <| filter isFailure exits
type Dep = String
type Out = String
data Compiler
= GhcLib
| GhcExe
| GhcjsLib
| GhcjsExe
| Guile
| NixBuild
| Copy
deriving (Show)
data Target = Target
{ -- | Output name
out :: Out,
-- | Fully qualified namespace partitioned by '.'
namespace :: Namespace,
-- | Absolute path to file
path :: FilePath,
-- | Parsed/detected dependencies
deps :: [Dep],
-- | Which compiler should we use?
compiler :: Compiler,
-- | Where is this machine being built? Schema: user@location
builder :: Text
}
deriving (Show)
isBuildableNs :: Namespace -> Bool
isBuildableNs (Namespace _ Namespace.Hs) = True
isBuildableNs ns
| ns `elem` nixTargets = True
| otherwise = False
nixTargets :: [Namespace]
nixTargets =
[ Namespace ["Biz", "Pie"] Namespace.Nix,
Namespace ["Biz", "Que", "Prod"] Namespace.Nix,
Namespace ["Biz", "Cloud"] Namespace.Nix,
Namespace ["Biz", "Dev"] Namespace.Nix,
Namespace ["Hero", "Prod"] Namespace.Nix
]
getNamespace :: String -> IO (Maybe Namespace)
getNamespace s = do
root <- Env.getEnv "BIZ_ROOT"
cwd <- Dir.getCurrentDirectory
return <| Namespace.fromPath root <| cwd </> s
analyze :: Namespace -> IO Target
analyze namespace@(Namespace.Namespace _ ext) = do
user <- Env.getEnv "USER" /> Text.pack
host <- chomp </ readFile "/etc/hostname"
let path = Namespace.toPath namespace
case ext of
Namespace.Hs -> do
content <- String.lines </ Prelude.readFile path
let out =
content
/> Regex.match metaOut
|> catMaybes
|> head
|> fromMaybe mempty
let compiler = detectGhcCompiler out <| String.unlines content
return
Target
{ deps = content /> Regex.match metaDep |> catMaybes,
builder = user <> "@localhost",
..
}
Namespace.Nix ->
return
Target
{ deps = [],
compiler = NixBuild,
out = "",
builder =
if host == "lithium"
then mempty
else
Text.concat
[ "ssh://",
user,
"@dev.simatime.com?ssh-key=/home/",
user,
"/.ssh/id_rsa"
],
..
}
Namespace.Scm ->
return
Target
{ deps = [],
compiler = Guile,
out = "",
builder = user <> "@localhost",
..
}
_ ->
return
Target
{ deps = [],
compiler = Copy,
out = "",
builder = user <> "@localhost",
..
}
-- | Some rules for detecting the how to compile a ghc module. If there is an
-- out, then we know it's some Exe; if the out ends in .js then it's GhcjsExe,
-- otherwise GhcExe. That part is solved.
--
-- Detecting a Lib is harder, and much code can be compiled by both ghc and
-- ghcjs. For now I'm just guarding against known ghcjs-only modules in the
-- import list.
detectGhcCompiler :: String -> String -> Compiler
detectGhcCompiler out _ | jsSuffix out = GhcjsExe
detectGhcCompiler out _ | not <| jsSuffix out || null out = GhcExe
detectGhcCompiler _ content
| match "import GHCJS" = GhcjsLib
| otherwise = GhcLib
where
match s = s `List.isInfixOf` content
jsSuffix :: String -> Bool
jsSuffix = List.isSuffixOf ".js"
isFailure :: Exit.ExitCode -> Bool
isFailure (Exit.ExitFailure _) = True
isFailure Exit.ExitSuccess = False
isSuccess :: Exit.ExitCode -> Bool
isSuccess Exit.ExitSuccess = True
isSuccess _ = False
build :: Bool -> Bool -> Target -> IO Exit.ExitCode
build andTest loud Target {..} = do
root <- Env.getEnv "BIZ_ROOT"
case compiler of
GhcExe -> do
Log.info ["bild", "dev", "ghc-exe", nschunk namespace]
let outDir = root </> "_/bild/dev/bin"
Dir.createDirectoryIfMissing True outDir
exitcode <-
proc
loud
namespace
"ghc"
[ "-Werror",
"-i" <> root,
"-odir",
root </> "_/bild/int",
"-hidir",
root </> "_/bild/int",
"--make",
path,
"-main-is",
Namespace.toHaskellModule namespace,
"-o",
outDir </> out
]
if andTest && isSuccess exitcode
then
run
<| Proc
{ loud = loud,
cmd = outDir </> out,
args = ["test"],
ns = namespace,
onFailure = Log.fail ["test", nschunk namespace] >> Log.br,
onSuccess = Log.pass ["test", nschunk namespace] >> Log.br
}
else return exitcode
GhcLib -> do
Log.info ["bild", "dev", "ghc-lib", nschunk namespace]
proc
loud
namespace
"ghc"
[ "-Werror",
"-i" <> root,
"-odir",
root </> "_/bild/int",
"-hidir",
root </> "_/bild/int",
"--make",
path
]
GhcjsExe -> do
Log.info ["bild", "dev", "ghcjs-exe", nschunk namespace]
let outDir = root </> "_/bild/dev/static"
Dir.createDirectoryIfMissing True outDir
proc
loud
namespace
"ghcjs"
[ "-Werror",
"-i" <> root,
"-odir",
root </> "_/bild/int",
"-hidir",
root </> "_/bild/int",
"--make",
path,
"-main-is",
Namespace.toHaskellModule namespace,
"-o",
outDir </> out
]
GhcjsLib -> do
Log.info ["bild", "dev", "ghcjs-lib", nschunk namespace]
proc
loud
namespace
"ghcjs"
[ "-Werror",
"-i" <> root,
"-odir",
root </> "_/bild/int",
"-hidir",
root </> "_/bild/int",
"--make",
path
]
Guile -> do
Log.warn ["bild", "guile", "TODO", nschunk namespace]
return Exit.ExitSuccess
NixBuild -> do
Log.info
[ "bild",
"nix",
if Text.null builder
then "local"
else builder,
nschunk namespace
]
let outDir = root </> "_/bild/nix"
Dir.createDirectoryIfMissing True outDir
proc
loud
namespace
"nix-build"
[ path,
"-o",
outDir </> Namespace.toPath namespace,
-- Set default arguments to nix functions
"--arg",
"bild",
"import " <> root
</> "Biz/Bild/Rules.nix"
<> " { nixpkgs = import "
<> root
</> "Biz/Bild/Nixpkgs.nix"
<> "; }",
"--arg",
"lib",
"(import " <> root </> "Biz/Bild/Nixpkgs.nix).lib",
"--builders",
Text.unpack builder
]
Copy -> do
Log.warn ["bild", "copy", "TODO", nschunk namespace]
return Exit.ExitSuccess
data Proc = Proc
{ loud :: Bool,
cmd :: String,
args :: [String],
ns :: Namespace,
onFailure :: IO (),
onSuccess :: IO ()
}
-- | Run a subprocess, streaming output if --loud is set.
run :: Proc -> IO Exit.ExitCode
run Proc {..} = do
(Conduit.Inherited, stdout_, stderr_, cph) <- Conduit.streamingProcess <| Conduit.proc cmd args
exitcode <-
if loud
then
Async.runConcurrently
<| Async.Concurrently (puts stdout_)
*> (Async.Concurrently <| Conduit.waitForStreamingProcess cph)
else Async.runConcurrently <| Async.Concurrently <| Conduit.waitForStreamingProcess cph
if isFailure exitcode
then puts stderr_ >> onFailure >> return exitcode
else onSuccess >> return exitcode
-- | Helper for running a standard bild subprocess.
proc :: Bool -> Namespace -> String -> [String] -> IO Exit.ExitCode
proc loud namespace cmd args =
run
<| Proc
{ loud = loud,
ns = namespace,
cmd = cmd,
args = args,
onFailure = Log.fail ["bild", nschunk namespace] >> Log.br,
onSuccess = Log.good ["bild", nschunk namespace] >> Log.br
}
-- | Helper for printing during a subprocess
puts :: Conduit.ConduitM () ByteString IO () -> IO ()
puts thing = Conduit.runConduit <| thing .| Conduit.mapM_ putStr
nschunk :: Namespace -> Text
nschunk = Namespace.toPath .> Text.pack
metaDep :: Regex.RE Char Dep
metaDep = Regex.string "-- : dep " *> Regex.many (Regex.psym Char.isAlpha)
metaOut :: Regex.RE Char Out
metaOut = Regex.string "-- : out " *> Regex.many (Regex.psym (/= ' '))
|