{-# 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 -- -- * the build is planned out with an analysis, which can be viewed -- beforehand with `--json`. The analysis includes compiler flags, which -- can be used in `repl` for testing compilation locally. -- -- == 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, or `fd .hs -X bild` to build all Haskell -- files. -- -- 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.Bild.Meta as Meta 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 as BS import qualified Data.ByteString.Char8 as Char8 import qualified Data.ByteString.Internal as BSI 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.Map as Map 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 System.IO.Unsafe (unsafePerformIO) 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 root <- Env.getEnv "BIZ_ROOT" path <- Dir.makeAbsolute "Biz/Bild.hs" case Namespace.fromPath root path of Nothing -> Test.assertFailure "can't find ns for bild" Just ns -> analyze mempty ns +> build False False +> \case [Exit.ExitFailure _] -> Test.assertFailure "can't bild bild" _ -> pure () ] move :: Cli.Arguments -> IO () move args = do root <- Env.getEnv "BIZ_ROOT" IO.hSetBuffering stdout IO.NoBuffering >> pure (Cli.getAllArgs args (Cli.argument "target")) /> filter (not <. Namespace.isCab) +> filterM Dir.doesFileExist +> traverse Dir.makeAbsolute /> map (Namespace.fromPath root) /> catMaybes +> foldM analyze mempty /> Map.filter (namespace .> isBuildableNs) +> printOrBuild +> exitSummary where printOrBuild :: Analysis -> IO [ExitCode] printOrBuild targets | args `Cli.has` Cli.longOption "json" = Log.wipe >> putJSON targets >> pure [Exit.ExitSuccess] | otherwise = do root <- Env.getEnv "BIZ_ROOT" createHier root 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 Print the build plan 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 data Compiler = Copy | Gcc | Ghc | Guile | NixBuild | Rustc | Sbcl deriving (Eq, Show, Generic) compilerExe :: IsString a => Compiler -> a compilerExe = \case Copy -> "cp" Gcc -> "gcc" Ghc -> "ghc" Guile -> "guild" NixBuild -> "nix-build" Rustc -> "rustc" Sbcl -> "sbcl" instance Aeson.ToJSON Compiler where toJSON = Aeson.String <. compilerExe instance ToNixFlag Compiler where toNixFlag = compilerExe data Target = Target { -- | Output name out :: Meta.Out, -- | Output path (into cabdir) outPath :: FilePath, -- | Fully qualified namespace partitioned by '.' namespace :: Namespace, -- | Absolute path to file path :: FilePath, -- | Language-specific dependencies, required during compilation langdeps :: Set Meta.Dep, -- | System-level dependencies, required during runtime either via PATH or -- linking, depending on the language sysdeps :: Set Meta.Dep, -- | Which compiler should we use? compiler :: Compiler, -- | Where is this machine being built? builder :: Builder, -- | Flags and arguments passed to 'Compiler' when building compilerFlags :: [Text], -- | Wrapper script (if necessary) wrapper :: Maybe Text } deriving (Show, Generic, Aeson.ToJSON) data Builder = -- | Local Local Text | -- | Remote Remote Text Text deriving (Show, Generic) instance Aeson.ToJSON Builder where toJSON (Local u) = Aeson.String u toJSON (Remote u host) = Aeson.String <| u <> "@" <> host class ToNixFlag a where toNixFlag :: a -> String instance ToNixFlag Builder where toNixFlag = \case Local _ -> "" Remote u h -> Text.unpack <| Text.concat ["ssh://", u, "@", h, "?ssh-key=/home/", u, "/.ssh/id_rsa"] -- | 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"] ] -- | The default output directory. This is not IO because I don't want to -- refactor all of my code right now, but it probably should be. cab :: FilePath cab = Env.lookupEnv "CABDIR" /> fromMaybe "_" |> unsafePerformIO outToPath :: Meta.Out -> FilePath outToPath = \case Meta.Bin o -> cab "bin" o Meta.Lib o -> cab "lib" o Meta.None -> mempty intdir, nixdir, vardir :: FilePath intdir = cab "int" nixdir = cab "nix" vardir = cab "var" -- | Emulate the *nix hierarchy in the cabdir. createHier :: String -> IO () createHier root = traverse_ (Dir.createDirectoryIfMissing True) [ root (outToPath <| Meta.Bin ""), root (outToPath <| Meta.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 type Analysis = Map Namespace Target analyze :: Analysis -> Namespace -> IO Analysis analyze hmap ns = case Map.lookup ns hmap of Nothing -> do mTarget <- analyzeOne ns pure <| maybe hmap (\t -> Map.insert ns t hmap) mTarget Just _ -> pure hmap where analyzeOne :: Namespace -> IO (Maybe Target) analyzeOne namespace@(Namespace _ ext) = do let path = Namespace.toPath namespace contentLines <- withFile path ReadMode <| \h -> IO.hSetEncoding h IO.utf8_bom >> Text.IO.hGetContents h /> Text.lines root <- Env.getEnv "BIZ_ROOT" absPath <- Dir.makeAbsolute path user <- Env.getEnv "USER" /> Text.pack host <- Env.lookupEnv "HOSTNAME" /> fromMaybe "interactive" /> Text.pack Log.info ["bild", "analyze", str path] let runw cmd args = Process.readProcess cmd args "" /> Text.pack /> Text.words 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 -> Meta.detectAll "//" contentLines |> \Meta.Parsed {..} -> do langdepFlags <- null pdep ?. ( runw "pkg-config" ("--cflags" : Set.toList pdep), pure [] ) sysdepFlags <- null psys ?. ( runw "pkg-config" ("--libs" : Set.toList psys), pure [] ) Target { langdeps = pdep, sysdeps = psys, wrapper = Nothing, compiler = Gcc, builder = Local user, out = pout, compilerFlags = concat [ [o, dir, Text.pack absPath] ++ langdepFlags ++ sysdepFlags ++ (map Text.pack <| Set.toList parg) | let outable = pout /= Meta.None, o <- outable ?: (["-o"], []), dir <- outable ?: ([Text.pack <| root outToPath pout], []) ], outPath = outToPath pout, .. } |> Just |> pure Namespace.Hs -> Meta.detectOut (Meta.out "--") contentLines |> \out -> do langdeps <- detectHaskellImports contentLines Target { builder = Local user, wrapper = Nothing, compiler = Ghc, compilerFlags = [ "-Werror", "-i" <> root, "-odir", root intdir, "-hidir", root intdir, "--make", absPath ] ++ (out /= Meta.None) ?: ( [ "-main-is", Namespace.toHaskellModule namespace, "-o", root outToPath out ], [] ) |> map Text.pack, sysdeps = Meta.detect (Meta.sys "--") contentLines, outPath = outToPath out, .. } |> Just |> pure Namespace.Lisp -> Meta.detectOut (Meta.out ";;") contentLines |> \out -> do langdeps <- detectLispImports contentLines Just (root outToPath out) <> "\" :toplevel #'main :executable t)" ], builder = Local <| user, outPath = outToPath out, .. } Namespace.Nix -> (host == "lithium") ?: (Local user, Remote user "dev.simatime.com") |> \builder -> Target { langdeps = Set.empty, wrapper = Nothing, sysdeps = Set.empty, compiler = NixBuild, compilerFlags = [ absPath, "--out-link", root nixdir Namespace.toPath namespace, "--builders", toNixFlag builder ] |> map Text.pack, out = Meta.None, outPath = outToPath Meta.None, .. } |> Just |> pure Namespace.Scm -> Meta.detectOut (Meta.out ";;") contentLines |> \out -> Target { langdeps = Set.empty, sysdeps = Set.empty, compiler = Guile, compilerFlags = [ "compile", "--r7rs", "--load-path=" ++ root, "--output=" ++ root intdir replaceExtension path ".scm.go", absPath ] |> map Text.pack, builder = Local user, outPath = outToPath out, wrapper = [ "#!/usr/bin/env bash", "guile -C \"" <> root intdir <> "\" -e main " <> "-s " <> Namespace.toPath namespace <> " \"$@\"" ] |> joinWith "\n" |> Text.pack |> Just, .. } |> Just |> pure Namespace.Rs -> Meta.detectOut (Meta.out "//") contentLines |> \out -> Target { langdeps = Set.empty, wrapper = Nothing, sysdeps = Set.empty, compiler = Rustc, compilerFlags = map Text.pack [absPath, "-o", root outToPath out], builder = Local user, outPath = outToPath out, .. } |> Just |> pure fromPath :: String -> IO (Maybe Namespace) --String ->IO (Maybe Namespace) fromPath x = Env.getEnv "BIZ_ROOT" +> \root -> pure <| Namespace.fromPath root x detectHaskellImports :: [Text] -> IO (Set Meta.Dep) detectHaskellImports contentLines = contentLines /> Text.unpack /> Regex.match haskellImports |> catMaybes |> \imports -> foldM ghcPkgFindModule Set.empty imports +> \pkgs -> imports |> map Namespace.fromHaskellModule |> map Namespace.toPath |> traverse Dir.makeAbsolute +> filterM Dir.doesFileExist +> traverse fromPath /> catMaybes -- this is still an inefficiency, because this recurses before the -- hmap is updated by the fold, transitive imports will be -- re-visited. you can see this with `TERM=dumb bild`. to fix this i -- need shared state instead of a fold, or figure out how to do a -- breadth-first search instead of depth-first. +> foldM analyze hmap /> Map.elems /> map langdeps /> mconcat /> (<> pkgs) detectLispImports :: [Text] -> IO (Set Meta.Dep) 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 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 Ghc -> do root <- Env.getEnv "BIZ_ROOT" run <| Proc { loud = loud, cmd = root outToPath 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.ExitFailure 1) build :: Bool -> Bool -> Analysis -> IO [Exit.ExitCode] build andTest loud analysis = do root <- Env.getEnv "BIZ_ROOT" forM (Map.elems analysis) <| \target@Target {..} -> do case compiler of Gcc -> Log.info ["bild", label, "gcc", nschunk namespace] >> proc loud namespace compiler compilerFlags where label = case out of Meta.Bin _ -> "bin" _ -> "lib" Ghc -> case out of Meta.None -> pure Exit.ExitSuccess Meta.Bin _ -> do Log.info ["bild", "dev", "ghc-exe", nschunk namespace] exitcode <- proc loud namespace compiler compilerFlags if andTest && isSuccess exitcode then test loud target else pure exitcode Meta.Lib _ -> do Log.info ["bild", "dev", "ghc-lib", nschunk namespace] proc loud namespace compiler compilerFlags Guile -> do Log.info ["bild", "dev", "guile", nschunk namespace] _ <- proc loud namespace compiler compilerFlags case wrapper of Nothing -> pure Exit.ExitSuccess Just content -> do writeFile (root outToPath out) content p <- Dir.getPermissions <| root outToPath out Dir.setPermissions (root outToPath out) (Dir.setOwnerExecutable True p) pure Exit.ExitSuccess NixBuild -> do Log.info ["bild", "nix", toLog builder, nschunk namespace] proc loud namespace compiler compilerFlags where toLog (Local u) = u toLog (Remote u h) = u <> "@" <> h Copy -> do Log.warn ["bild", "copy", "not implemented yet", nschunk namespace] pure Exit.ExitSuccess Rustc -> do Log.info ["bild", "dev", "rust", nschunk namespace] proc loud namespace compiler compilerFlags Sbcl -> do Log.info ["bild", "dev", "lisp", nschunk namespace] proc loud namespace compiler 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 {..} = Conduit.proc cmd args |> Conduit.streamingProcess +> \(Conduit.UseProvidedHandle, stdin_, stderr_, hdl) -> loud ?: (verboseLog stdin_ stderr_ hdl, shortLog stdin_ stderr_ hdl) +> \case Exit.ExitFailure n -> puts stderr_ >> onFailure >> pure (Exit.ExitFailure n) Exit.ExitSuccess -> onSuccess >> pure Exit.ExitSuccess where verboseLog stdin_ stderr_ hdl = Async.runConcurrently <| Async.Concurrently (puts stdin_) *> Async.Concurrently (puts stderr_) *> Async.Concurrently (Conduit.waitForStreamingProcess hdl) shortLog stdin_ stderr_ hdl = Async.runConcurrently <| Async.Concurrently (logs ns stdin_) *> Async.Concurrently (logs ns stderr_) *> Async.Concurrently (Conduit.waitForStreamingProcess hdl) -- | Helper for running a standard bild subprocess. proc :: ToNixFlag a => Bool -> Namespace -> a -> [Text] -> IO Exit.ExitCode proc loud namespace cmd args = run <| Proc { loud = loud, ns = namespace, cmd = toNixFlag 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 src = Conduit.runConduit <| src .| Conduit.mapM_ putStr -- | Like 'puts' but logs the output via 'Biz.Log'. logs :: Namespace -> Conduit.ConduitM () ByteString IO () -> IO () logs ns src = Conduit.runConduit <| src .| Conduit.mapM_ ( BS.filter (/= BSI.c2w '\n') .> (\t -> Log.fmt ["info", "bild", nschunk ns, decodeUtf8 t]) .> Text.take 77 .> (<> "...\r") .> putStr ) nschunk :: Namespace -> Text nschunk = Namespace.toPath .> Text.pack 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` ['\'', ':']