{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE NoImplicitPrelude #-} -- | A general purpose build tool. -- -- : out bild -- -- == 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 -- -- * no need to distinguish between exe and lib, just have a single output, -- or figure it out automatically -- -- * never concerned with deployment/packaging - leave that to another tool -- (scp? tar?) -- -- * local dev builds should be preserved, while remote nix builds are used -- for the final package -- -- == 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: -- -- * -p = turn on profiling -- -- * -o = optimize level -- -- == Example Commands -- -- > bild [opts] -- -- 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 `:!bild %` in vim to build whatever you're working on, -- or `bild **/*` to build everything. -- -- Build outputs will go into the `_` 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`. -- -- == Build Metadata -- -- Metadata is set in the comments with a special syntax. For system-level deps, -- we list the deps in comments in the target file, like: -- -- > -- : sys cmark -- -- The name is used to lookup the package in `nixpkgs.pkgs.`. -- Language-level deps can automatically determined by passing parsed import -- statements to a package database, eg `ghc-pkg find-module`. -- -- The output executable is named with: -- -- > -- : out my-program -- -- or -- -- > -- : out my-app.js -- -- When multiple compilers are possible we use the @out@ extension to determine -- target platform. If @out@ does not have an extension, each build type falls -- back to a default, namely 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.Aeson as Aeson import qualified Data.ByteString.Char8 as Char8 import qualified Data.ByteString.Lazy as ByteString 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.Maybe as Maybe import qualified Data.Set as Set import qualified Data.String as String import qualified Data.Text as Text import qualified Data.Text.IO as Text.IO import qualified System.Directory as Dir import qualified System.Environment as Env import qualified System.Exit as Exit import System.FilePath (replaceExtension, ()) import qualified System.IO as IO import qualified System.Process as Process import qualified Text.Regex.Applicative as Regex main :: IO () main = Cli.main <| Cli.Plan help move test_ pure where test_ = Test.group "Biz.Bild" [ Test.unit "can bild bild" <| do analyze "Biz/Bild.hs" /> Maybe.fromJust +> build False False +> \case Exit.ExitFailure _ -> Test.assertFailure "can't bild bild" _ -> pure () ] move :: Cli.Arguments -> IO () move args = IO.hSetBuffering stdout IO.NoBuffering >> pure (Cli.getAllArgs args (Cli.argument "target")) /> filter (not <. Namespace.isCab) +> filterM Dir.doesFileExist +> traverse analyze /> filter isJust /> map Maybe.fromJust /> filter (namespace .> isBuildableNs) +> printOrBuild +> exitSummary where printOrBuild :: [Target] -> IO [ExitCode] printOrBuild targets | args `Cli.has` Cli.longOption "json" = Log.wipe >> traverse_ putJSON targets >> pure [Exit.ExitSuccess] | otherwise = do root <- Env.getEnv "BIZ_ROOT" createHier root traverse (build isTest isLoud) targets isTest = args `Cli.has` Cli.longOption "test" isLoud = args `Cli.has` Cli.longOption "loud" putJSON = Aeson.encode .> ByteString.toStrict .> Char8.putStrLn nixStore :: String nixStore = "/nix/store/00000000000000000000000000000000-" help :: Cli.Docopt help = [Cli.docopt| bild Usage: bild test bild [options] ... Options: --test Run tests on a target after building --loud Show all output from compiler --json Only analyze and print as JSON, don't build -h, --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 data Out = Lib String | Bin String | None deriving (Show, Eq) instance Aeson.ToJSON Out where toJSON out = outdir out |> Text.pack |> Aeson.String data Compiler = Copy | Gcc | GhcLib | GhcExe | Guile | NixBuild | Rustc | Sbcl deriving (Eq, Show, Generic) instance Aeson.ToJSON Compiler where toJSON = Aeson.String <. \case Copy -> "cp" Gcc -> "gcc" GhcLib -> "ghc" GhcExe -> "ghc" Guile -> "guile" NixBuild -> "nix-build" Rustc -> "rustc" Sbcl -> "sbcl" data Target = Target { -- | Output name out :: Out, -- | Fully qualified namespace partitioned by '.' namespace :: Namespace, -- | Absolute path to file path :: FilePath, -- | Language-specific dependencies langdeps :: Set Dep, -- | System-level dependencies sysdeps :: Set Dep, -- | Which compiler should we use? compiler :: Compiler, -- | Where is this machine being built? Schema: user@location builder :: Text, -- | Flags and arguments passed to 'Compiler' when building compilerFlags :: [Text] } deriving (Show, Generic, Aeson.ToJSON) -- | We can't build everything yet... isBuildableNs :: Namespace -> Bool isBuildableNs = \case (Namespace _ Namespace.C) -> True (Namespace _ Namespace.Css) -> False (Namespace _ Namespace.Hs) -> True (Namespace _ Namespace.Json) -> False (Namespace _ Namespace.Keys) -> False (Namespace _ Namespace.Lisp) -> True (Namespace _ Namespace.Md) -> False (Namespace _ Namespace.None) -> False (Namespace _ Namespace.Py) -> False (Namespace _ Namespace.Sh) -> False (Namespace _ Namespace.Scm) -> True (Namespace _ Namespace.Rs) -> True (Namespace path Namespace.Nix) | path `elem` nixTargets -> True | otherwise -> False where nixTargets = [ ["Biz", "Pie"], ["Biz", "Que"], ["Biz", "Cloud"], ["Biz", "Dev"], ["Biz", "Dragons", "Analysis"] ] -- | Emulate the *nix hierarchy in the cabdir. outdir :: Out -> String outdir = \case Bin o -> "_/bin" o Lib o -> "_/lib" o None -> mempty intdir, nixdir, vardir :: String intdir = "_/int" nixdir = "_/nix" vardir = "_/var" createHier :: String -> IO () createHier root = traverse_ (Dir.createDirectoryIfMissing True) [ root (outdir <| Bin ""), root (outdir <| Lib ""), root intdir, root nixdir, root vardir ] -- >>> removeVersion "array-0.5.4.0-DFLKGIjfsadi" -- "array" removeVersion :: String -> String removeVersion = takeWhile (/= '.') .> butlast2 where butlast2 s = take (length s - 2) s -- | TODO: globally cache analyses, so I'm not re-analyzing modules all the -- time. This is important as it would speed up building by a lot. analyze :: FilePath -> IO (Maybe Target) analyze path = do content <- withFile path ReadMode <| \h -> IO.hSetEncoding h IO.utf8_bom >> Text.IO.hGetContents h let contentLines = Text.lines content root <- Env.getEnv "BIZ_ROOT" absPath <- Dir.makeAbsolute path user <- Env.getEnv "USER" /> Text.pack host <- Text.pack Log.warn ["bild", "analyze", str path, "could not find namespace"] >> Log.br >> pure Nothing Just namespace@(Namespace _ ext) -> case ext of -- basically we don't support building these Namespace.Css -> pure Nothing Namespace.Json -> pure Nothing Namespace.Keys -> pure Nothing Namespace.Md -> pure Nothing Namespace.None -> pure Nothing Namespace.Py -> pure Nothing Namespace.Sh -> pure Nothing Namespace.C -> do let out = contentLines /> Text.unpack /> Regex.match (metaOut "//" <|> metaLib "//") |> catMaybes |> head |> fromMaybe None let sysdeps = contentLines /> Text.unpack /> Regex.match (metaSys "//") |> catMaybes |> Set.fromList guileFlags <- if "guile_3_0" `elem` sysdeps then Process.readProcess "guile-config" ["compile"] "" /> String.words /> (++ ["-shared", "-fPIC"]) /> map Text.pack else pure mempty Just "@localhost", compilerFlags = concat [ [o, dir, Text.pack absPath] ++ guileFlags | let outable = out /= None, o <- outable ?: (["-o"], []), dir <- outable ?: ([Text.pack <| root outdir out], []) ], .. } Namespace.Hs -> do langdeps <- detectHaskellImports contentLines let out = contentLines /> Text.unpack /> Regex.match (metaOut "--") |> catMaybes |> head |> fromMaybe None Just "@localhost", compiler = detectGhcCompiler out, compilerFlags = map Text.pack [ "-Werror", "-i" <> root, "-odir", root intdir, "-hidir", root intdir, "--make", path ] ++ (out /= None) ?: ( map Text.pack [ "-main-is", Namespace.toHaskellModule namespace, "-o", root outdir out ], [] ), sysdeps = contentLines /> Text.unpack /> Regex.match (metaSys "--") |> catMaybes |> Set.fromList, .. } Namespace.Lisp -> do let out = contentLines /> Text.unpack /> Regex.match (metaOut ";;") |> catMaybes |> head |> fromMaybe None langdeps <- detectLispImports contentLines Just (root outdir out) <> "\" :toplevel #'main :executable t)" ], builder = user <> "@localhost", .. } Namespace.Nix -> do let builder = (host == "lithium") ?: ( "local", Text.concat [ "ssh://", user, "@dev.simatime.com?ssh-key=/home/", user, "/.ssh/id_rsa" ] ) Just nixdir Namespace.toPath namespace, "--builders", Text.unpack builder ], out = None, .. } Namespace.Scm -> do let out = contentLines /> Text.unpack /> Regex.match (metaOut ";;") |> catMaybes |> head |> fromMaybe None Just intdir replaceExtension path ".scm.go", path ], builder = user <> "@localhost", .. } Namespace.Rs -> do let out = contentLines /> Text.unpack /> Regex.match (metaOut "//") |> catMaybes |> head |> fromMaybe None Just outdir out], builder = user <> "@localhost", .. } where detectHaskellImports :: [Text] -> IO (Set Dep) detectHaskellImports contentLines = do let imports = contentLines /> Text.unpack /> Regex.match haskellImports |> catMaybes pkgs <- foldM ghcPkgFindModule Set.empty imports transitivePkgs <- imports |> map (Namespace.fromHaskellModule .> Namespace.toPath) |> traverse Dir.makeAbsolute +> filterM Dir.doesFileExist +> Async.mapConcurrently analyze /> catMaybes /> map langdeps /> mconcat pure <| pkgs <> transitivePkgs detectLispImports contentLines = do let requires = contentLines /> Text.unpack /> Regex.match lispRequires |> catMaybes pure <| Set.fromList requires ghcPkgFindModule :: Set String -> String -> IO (Set String) ghcPkgFindModule acc m = do packageDb <- Env.getEnv "GHC_PACKAGE_PATH" Process.readProcess "ghc-pkg" ["--package-db", packageDb, "--names-only", "--simple-output", "find-module", m] "" /> String.lines /> Set.fromList /> Set.union acc -- | Some rules for detecting the how to compile a ghc module. If there is an -- out, then we know it's some Exe, otherwise it's a Lib. detectGhcCompiler :: Out -> Compiler detectGhcCompiler = \case Bin _ -> GhcExe Lib _ -> GhcLib None -> GhcLib isFailure :: Exit.ExitCode -> Bool isFailure (Exit.ExitFailure _) = True isFailure Exit.ExitSuccess = False isSuccess :: Exit.ExitCode -> Bool isSuccess Exit.ExitSuccess = True isSuccess _ = False test :: Bool -> Target -> IO Exit.ExitCode test loud Target {..} = case compiler of GhcExe -> do root <- Env.getEnv "BIZ_ROOT" run <| Proc { loud = loud, cmd = root outdir out, args = ["test"], ns = namespace, onFailure = Log.fail ["test", nschunk namespace] >> Log.br, onSuccess = Log.pass ["test", nschunk namespace] >> Log.br } _ -> Log.warn ["test", nschunk namespace, "unavailable"] >> Log.br >> pure Exit.ExitSuccess build :: Bool -> Bool -> Target -> IO Exit.ExitCode build andTest loud target@Target {..} = do root <- Env.getEnv "BIZ_ROOT" case compiler of Gcc -> Log.info ["bild", label, "gcc", nschunk namespace] >> proc loud namespace "gcc" compilerFlags where label = case out of Bin _ -> "bin" _ -> "lib" GhcExe -> do Log.info ["bild", "dev", "ghc-exe", nschunk namespace] exitcode <- proc loud namespace "ghc" compilerFlags if andTest && isSuccess exitcode then test loud target else pure exitcode GhcLib -> do Log.info ["bild", "dev", "ghc-lib", nschunk namespace] proc loud namespace "ghc" compilerFlags Guile -> do Log.info ["bild", "dev", "guile", nschunk namespace] _ <- proc loud namespace "guild" compilerFlags when (out /= None) <| do writeFile (root outdir out) <| Text.pack <| joinWith "\n" [ "#!/usr/bin/env bash", "guile -C \"" <> root intdir <> "\" -e main " <> "-s " <> Namespace.toPath namespace <> " \"$@\"" ] p <- Dir.getPermissions <| root outdir out Dir.setPermissions (root outdir out) (Dir.setOwnerExecutable True p) pure Exit.ExitSuccess NixBuild -> do Log.info ["bild", "nix", builder, nschunk namespace] proc loud namespace "nix-build" compilerFlags Copy -> do Log.warn ["bild", "copy", "TODO", nschunk namespace] pure Exit.ExitSuccess Rustc -> do Log.info ["bild", "dev", "rust", nschunk namespace] proc loud namespace "rustc" compilerFlags Sbcl -> do Log.info ["bild", "dev", "lisp", nschunk namespace] proc loud namespace "sbcl" compilerFlags 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 >> pure exitcode else onSuccess >> pure exitcode -- | Helper for running a standard bild subprocess. proc :: Bool -> Namespace -> String -> [Text] -> IO Exit.ExitCode proc loud namespace cmd args = run <| Proc { loud = loud, ns = namespace, cmd = cmd, args = map Text.unpack 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) metaSys :: [Char] -> Regex.RE Char Dep metaSys comment = Regex.string (comment ++ " : sys ") *> Regex.many (Regex.psym (not <. Char.isSpace)) metaOut :: [Char] -> Regex.RE Char Out metaOut comment = Regex.string (comment ++ " : out ") *> Regex.many (Regex.psym (/= ' ')) /> Bin metaLib :: [Char] -> Regex.RE Char Out metaLib comment = Regex.string (comment ++ " : lib ") *> Regex.many (Regex.psym (/= ' ')) /> Lib haskellImports :: Regex.RE Char String haskellImports = Regex.string "import" *> Regex.some (Regex.psym Char.isSpace) *> Regex.many (Regex.psym Char.isLower) *> Regex.many (Regex.psym Char.isSpace) *> Regex.some (Regex.psym isModuleChar) <* Regex.many Regex.anySym isModuleChar :: Char -> Bool isModuleChar c = elem c <| concat [['A' .. 'Z'], ['a' .. 'z'], ['.', '_'], ['0' .. '9']] -- Matches on `(require :package)` forms and returns `package`. The `require` -- function is technically deprecated in Common Lisp, but no new spec has been -- published with a replacement, and I don't wanna use asdf, so this is what we -- use for Lisp imports. lispRequires :: Regex.RE Char String lispRequires = Regex.string "(require" *> Regex.some (Regex.psym Char.isSpace) *> Regex.many (Regex.psym isQuote) *> Regex.many (Regex.psym isModuleChar) <* Regex.many (Regex.psym (== ')')) where isQuote :: Char -> Bool isQuote c = c `elem` ['\'', ':']