-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A tool and library for building virtual machine images. -- -- Build virtual machine images for vm-deployments; resize, un-partition, -- create from scratch or convert disk image files in a variety of -- formats; assemble and generate all associated files from templates and -- regular files. VM images can further be modifed through scripts, which -- are executed in LXC containers into which the vm-images as well as -- arbitrary directories from the host are mounted. All assembled files -- can also be accessed by vm build scripts through a special directory -- mounted in the build container, and/or can be written to directories, -- ISO- or VFAT-images. The ISO/VFAT images that B9 creates are -- compatible to 'cloud-init's NoCloud data source; B9 is also -- very well suited for compiling in a containerized environment. For -- these applications, the images can be marked as Transient to -- indicate no further interest in the VM-image itself, and B9 will -- discard them after the build. B9 will never over-write source files, -- not even large vm-image files - there is no intended way to modify a -- source vm-image file 'in-place'. B9 operates in random build -- directories, which are discarded when the build exists. @package b9 @version 3.1.0 -- | Programmatic Interface to b9 artifact generation. -- -- An extensible approach to vm deployment configuration management. -- -- TODO: do it. module B9.Artifact -- | Error handling in B9 via extensible effects. B9 wraps errors in -- SomeException. module B9.B9Error -- | SomeException wrapped into Excecption Effects throwSomeException :: (Member ExcB9 e, Exception x) => x -> Eff e a -- | SomeException wrapped into Excecption Effects throwSomeException_ :: (Member ExcB9 e, Exception x) => x -> Eff e () -- | SomeException wrapped into Excecption Effects throwB9Error :: Member ExcB9 e => String -> Eff e a -- | SomeException wrapped into Excecption Effects throwB9Error_ :: Member ExcB9 e => String -> Eff e () -- | Run an ExcB9 and rethrow the exception with error. errorOnException :: Lifted IO e => Eff (ExcB9 : e) a -> Eff e a -- | The exception effect used in most places in B9. This is Exc -- specialized with SomeException. type ExcB9 = Exc SomeException -- | Constraint alias for the exception effect that allows to throw -- SomeException. type WithIoExceptions e = SetMember Exc (Exc SomeException) e -- | Run an ExcB9. runExcB9 :: Eff (ExcB9 : e) a -> Eff e (Either SomeException a) -- | This is a simple runtime exception to indicate that B9 code -- encountered some exceptional event. newtype B9Error MkB9Error :: String -> B9Error fromB9Error :: B9Error -> String -- | Catch exceptions. catchB9Error :: Member ExcB9 e => Eff e a -> (SomeException -> Eff e a) -> Eff e a -- | Catch exceptions and return them via Either. catchB9ErrorAsEither :: Member ExcB9 e => Eff e a -> Eff e (Either SomeException a) -- | Always execute an action and rethrow any exceptions caught. finallyB9 :: Member ExcB9 e => Eff e a -> Eff e () -> Eff e a instance Data.String.IsString B9.B9Error.B9Error instance GHC.Show.Show B9.B9Error.B9Error instance GHC.Exception.Type.Exception B9.B9Error.B9Error -- | Utility module to extract a primary partition from an MBR partition on -- a raw image file. module B9.MBR getPartition :: Int -> FilePath -> IO (Word64, Word64) data PrimaryPartition PrimaryPartition :: !Word8 -> !CHS -> !Word8 -> !CHS -> !Word32 -> !Word32 -> PrimaryPartition [primPartStatus] :: PrimaryPartition -> !Word8 [primPartChsStart] :: PrimaryPartition -> !CHS [primPartPartType] :: PrimaryPartition -> !Word8 [primPartChsEnd] :: PrimaryPartition -> !CHS [primPartLbaStart] :: PrimaryPartition -> !Word32 [primPartSectors] :: PrimaryPartition -> !Word32 data MBR MBR :: !PrimaryPartition -> !PrimaryPartition -> !PrimaryPartition -> !PrimaryPartition -> MBR [mbrPart1] :: MBR -> !PrimaryPartition [mbrPart2] :: MBR -> !PrimaryPartition [mbrPart3] :: MBR -> !PrimaryPartition [mbrPart4] :: MBR -> !PrimaryPartition data CHS CHS :: !Word8 -> !Word8 -> !Word8 -> CHS [chsH] :: CHS -> !Word8 [chs_CUpper2_S] :: CHS -> !Word8 [chs_CLower8] :: CHS -> !Word8 instance GHC.Show.Show B9.MBR.MBR instance GHC.Show.Show B9.MBR.PrimaryPartition instance GHC.Show.Show B9.MBR.CHS -- | Function to find the file offsets of primary partitions in raw disk -- images. Currently only MBR partitions are supported. See MBR module B9.PartitionTable getPartition :: Int -> FilePath -> IO (Word64, Word64, Word64) -- | Some QuickCheck utility functions. module B9.QCUtil arbitraryEnv :: Arbitrary a => Gen [(String, a)] halfSize :: Gen a -> Gen a smaller :: Gen a -> Gen a arbitraryFilePath :: Gen FilePath arbitraryLetter :: Gen Char arbitraryLetterUpper :: Gen Char arbitraryLetterLower :: Gen Char arbitraryDigit :: Gen Char -- | Data types that describe all B9 relevant elements of virtual machine -- disk images. module B9.DiskImages -- | Build target for disk images; the destination, format and size of the -- image to generate, as well as how to create or obtain the image before -- a VmScript is executed with the image mounted at a -- MountPoint. data ImageTarget ImageTarget :: ImageDestination -> ImageSource -> MountPoint -> ImageTarget -- | A mount point or NotMounted data MountPoint MountPoint :: FilePath -> MountPoint NotMounted :: MountPoint -- | The destination of an image. data ImageDestination -- | Create the image and some meta data so that other builds can use them -- as ImageSources via From. Share :: String -> ImageType -> ImageResize -> ImageDestination -- | DEPRECATED Export a raw image that can directly be booted. LiveInstallerImage :: String -> FilePath -> ImageResize -> ImageDestination -- | Write an image file to the path in the first argument., possible -- resizing it, LocalFile :: Image -> ImageResize -> ImageDestination -- | Do not export the image. Usefule if the main objective of the b9 build -- is not an image file, but rather some artifact produced by executing -- by a containerize build. Transient :: ImageDestination -- | Specification of how the image to build is obtained. data ImageSource -- | Create an empty image file having a file system label (first -- parameter), a file system type (e.g. Ext4) and an -- ImageSize EmptyImage :: String -> FileSystem -> ImageType -> ImageSize -> ImageSource -- | DEPRECATED CopyOnWrite :: Image -> ImageSource -- | Clone an existing image file; if the image file contains partitions, -- select the partition to use, b9 will extract that partition by reading -- the offset of the partition from the partition table and extract it -- using dd. SourceImage :: Image -> Partition -> ImageResize -> ImageSource -- | Use an image previously shared by via Share. From :: String -> ImageResize -> ImageSource -- | The partition to extract. data Partition -- | There is no partition table on the image NoPT :: Partition -- | Extract partition n n must be in 0..3 Partition :: Int -> Partition -- | A vm disk image file consisting of a path to the image file, and the -- type and file system. data Image Image :: FilePath -> ImageType -> FileSystem -> Image -- | An image type defines the actual file format of a file -- containing file systems. These are like virtual harddrives data ImageType Raw :: ImageType QCow2 :: ImageType Vmdk :: ImageType -- | The file systems that b9 can use and convert. data FileSystem NoFileSystem :: FileSystem Ext4 :: FileSystem Ext4_64 :: FileSystem ISO9660 :: FileSystem VFAT :: FileSystem -- | A data type for image file or file system size; instead of passing -- Ints around this also captures a size unit so that the -- Int can be kept small data ImageSize ImageSize :: Int -> SizeUnit -> ImageSize -- | Convert a size in bytes to an ImageSize bytesToKiloBytes :: Int -> ImageSize -- | Convert an ImageSize to kibi bytes. imageSizeToKiB :: ImageSize -> Int -- | Convert a SizeUnit to the number of kibi bytes one element -- represents. sizeUnitKiB :: SizeUnit -> Int -- | Choose the greatest unit possible to exactly represent an -- ImageSize. normalizeSize :: ImageSize -> ImageSize -- | Return the sum of two ImageSizes. addImageSize :: ImageSize -> ImageSize -> ImageSize -- | Enumeration of size multipliers. The exact semantics may vary -- depending on what external tools look at these. E.g. the size unit is -- convert to a size parameter of the qemu-img command line -- tool. data SizeUnit KB :: SizeUnit MB :: SizeUnit GB :: SizeUnit -- | How to resize an image file. data ImageResize -- | Resize the image but not the file system. Note that a file -- system contained in the image file might be corrupted by this -- operation. To not only resize the image file but also the fil system -- contained in it, use Resize. ResizeImage :: ImageSize -> ImageResize -- | Resize an image and the contained file system. Resize :: ImageSize -> ImageResize -- | Shrink to minimum size needed and increase by the amount given. ShrinkToMinimumAndIncrease :: ImageSize -> ImageResize -- | Resize an image and the contained file system to the smallest size to -- fit the contents of the file system. ShrinkToMinimum :: ImageResize -- | Do not change the image size. KeepSize :: ImageResize -- | A type alias that indicates that something of type a is mount -- at a MountPoint type Mounted a = (a, MountPoint) -- | SharedImage holds all data necessary to describe an -- instance of a shared image identified by a -- SharedImageName. Shared images are stored in -- Repositorys. data SharedImage SharedImage :: SharedImageName -> SharedImageDate -> SharedImageBuildId -> ImageType -> FileSystem -> SharedImage -- | The name of the image is the de-facto identifier for push, pull, -- From and Share. B9 always selects the newest version the -- shared image identified by that name when using a shared image as an -- ImageSource. This is a wrapper around a string that identifies -- a SharedImage newtype SharedImageName SharedImageName :: String -> SharedImageName -- | Get the String representation of a SharedImageName. fromSharedImageName :: SharedImageName -> String -- | The exact time that build job started. This is a wrapper around -- a string contains the build date of a SharedImage; this is -- purely additional convenience and typesafety newtype SharedImageDate SharedImageDate :: String -> SharedImageDate -- | Every B9 build running in a B9Monad contains a random unique -- id that is generated once per build (no matter how many artifacts are -- created in that build) This field contains the build id of the build -- that created the shared image instance. This is A wrapper around a -- string contains the build id of a SharedImage; this is purely -- additional convenience and typesafety newtype SharedImageBuildId SharedImageBuildId :: String -> SharedImageBuildId -- | Get the String representation of a SharedImageBuildId. fromSharedImageBuildId :: SharedImageBuildId -> String -- | Transform a list of SharedImage values into a Map that -- associates each SharedImageName with a Set of the actual -- images with that name. -- -- The Set contains values of type SharedImage. -- -- The Ord instance of SharedImage sorts by name first and -- then by sharedImageDate, since the values in a Set share -- the same sharedImageName, they are effectively orderd by build -- date, which is useful the shared image cleanup. sharedImagesToMap :: [SharedImage] -> Map SharedImageName (Set SharedImage) -- | Return the SharedImage with the highest sharedImageDate. takeLatestSharedImage :: [SharedImage] -> Maybe SharedImage -- | Return the name of the file corresponding to an Image imageFileName :: Image -> FilePath -- | Return the ImageType of an Image imageImageType :: Image -> ImageType -- | Return the files generated for a LocalFile or a -- LiveInstallerImage; SharedImage and Transient are -- treated like they have no output files because the output files are -- manged by B9. getImageDestinationOutputFiles :: ImageTarget -> [FilePath] -- | Return the name of a shared image, if the ImageDestination is a -- Share destination imageDestinationSharedImageName :: ImageDestination -> Maybe SharedImageName -- | Return the name of a shared source image, if the ImageSource is -- a From source imageSourceSharedImageName :: ImageSource -> Maybe SharedImageName -- | Get the ImageDestination of an ImageTarget itImageDestination :: ImageTarget -> ImageDestination -- | Get the ImageSource of an ImageTarget itImageSource :: ImageTarget -> ImageSource -- | Get the MountPoint of an ImageTarget itImageMountPoint :: ImageTarget -> MountPoint -- | Return true if a Partition parameter is actually referring to a -- partition, false if it is NoPT isPartitioned :: Partition -> Bool -- | Return the Partition index or throw a runtime error if applied -- to NoPT getPartition :: Partition -> Int -- | Return the file name extension of an image file with a specific image -- format. imageFileExtension :: ImageType -> String -- | Change the image file format and also rename the image file name to -- have the appropriate file name extension. See -- imageFileExtension and replaceExtension changeImageFormat :: ImageType -> Image -> Image changeImageDirectory :: FilePath -> Image -> Image getImageSourceImageType :: ImageSource -> Maybe ImageType -- | Return the name of a shared image. sharedImageName :: SharedImage -> SharedImageName -- | Return the build date of a shared image. sharedImageDate :: SharedImage -> SharedImageDate -- | Return the build id of a shared image. sharedImageBuildId :: SharedImage -> SharedImageBuildId -- | Print the contents of the shared image in one line prettyPrintSharedImages :: Set SharedImage -> String -- | Return the disk image of an sharedImage sharedImageImage :: SharedImage -> Image -- | Calculate the path to the text file holding the serialized -- SharedImage relative to the directory of shared images in a -- repository. sharedImageFileName :: SharedImage -> FilePath sharedImagesRootDirectory :: FilePath sharedImageFileExtension :: String -- | The internal image type to use as best guess when dealing with a -- From value. sharedImageDefaultImageType :: ImageType -- | Use a QCow2 image with an Ext4 file system transientCOWImage :: FilePath -> FilePath -> ImageTarget -- | Use a shared image transientSharedImage :: SharedImageName -> FilePath -> ImageTarget -- | Use a shared image transientLocalImage :: FilePath -> FilePath -> ImageTarget -- | Share a QCow2 image with Ext4 fs shareCOWImage :: FilePath -> SharedImageName -> FilePath -> ImageTarget -- | Share an image based on a shared image shareSharedImage :: SharedImageName -> SharedImageName -> FilePath -> ImageTarget -- | Share a QCow2 image with Ext4 fs shareLocalImage :: FilePath -> SharedImageName -> FilePath -> ImageTarget -- | Export a QCow2 image with Ext4 fs cowToliveInstallerImage :: String -> FilePath -> FilePath -> FilePath -> ImageTarget -- | Export a QCow2 image file with Ext4 fs as a local file cowToLocalImage :: FilePath -> FilePath -> FilePath -> ImageTarget -- | Export a QCow2 image file with Ext4 fs as a local file localToLocalImage :: FilePath -> FilePath -> FilePath -> ImageTarget -- | Create a local image file from the contents of the first partition of -- a local QCow2 image. partition1ToLocalImage :: FilePath -> FilePath -> FilePath -> ImageTarget -- | Split any image target into two image targets, one for creating an -- intermediate shared image and one from the intermediate shared image -- to the output image. splitToIntermediateSharedImage :: ImageTarget -> SharedImageName -> (ImageTarget, ImageTarget) arbitrarySharedImageName :: Gen String unitTests :: Spec instance GHC.Generics.Generic B9.DiskImages.SharedImage instance Data.Data.Data B9.DiskImages.SharedImage instance GHC.Show.Show B9.DiskImages.SharedImage instance GHC.Read.Read B9.DiskImages.SharedImage instance GHC.Classes.Eq B9.DiskImages.SharedImage instance Test.QuickCheck.Arbitrary.CoArbitrary B9.DiskImages.SharedImageBuildId instance Control.DeepSeq.NFData B9.DiskImages.SharedImageBuildId instance Data.Binary.Class.Binary B9.DiskImages.SharedImageBuildId instance Data.Hashable.Class.Hashable B9.DiskImages.SharedImageBuildId instance Data.Data.Data B9.DiskImages.SharedImageBuildId instance GHC.Show.Show B9.DiskImages.SharedImageBuildId instance GHC.Read.Read B9.DiskImages.SharedImageBuildId instance GHC.Classes.Ord B9.DiskImages.SharedImageBuildId instance GHC.Classes.Eq B9.DiskImages.SharedImageBuildId instance Test.QuickCheck.Arbitrary.CoArbitrary B9.DiskImages.SharedImageDate instance Control.DeepSeq.NFData B9.DiskImages.SharedImageDate instance Data.Binary.Class.Binary B9.DiskImages.SharedImageDate instance Data.Hashable.Class.Hashable B9.DiskImages.SharedImageDate instance Data.Data.Data B9.DiskImages.SharedImageDate instance GHC.Show.Show B9.DiskImages.SharedImageDate instance GHC.Read.Read B9.DiskImages.SharedImageDate instance GHC.Classes.Ord B9.DiskImages.SharedImageDate instance GHC.Classes.Eq B9.DiskImages.SharedImageDate instance Test.QuickCheck.Arbitrary.CoArbitrary B9.DiskImages.SharedImageName instance Control.DeepSeq.NFData B9.DiskImages.SharedImageName instance Data.Binary.Class.Binary B9.DiskImages.SharedImageName instance Data.Hashable.Class.Hashable B9.DiskImages.SharedImageName instance Data.Data.Data B9.DiskImages.SharedImageName instance GHC.Show.Show B9.DiskImages.SharedImageName instance GHC.Read.Read B9.DiskImages.SharedImageName instance GHC.Classes.Ord B9.DiskImages.SharedImageName instance GHC.Classes.Eq B9.DiskImages.SharedImageName instance GHC.Generics.Generic B9.DiskImages.ImageTarget instance GHC.Classes.Eq B9.DiskImages.ImageTarget instance Data.Data.Data B9.DiskImages.ImageTarget instance GHC.Show.Show B9.DiskImages.ImageTarget instance GHC.Read.Read B9.DiskImages.ImageTarget instance GHC.Generics.Generic B9.DiskImages.ImageDestination instance GHC.Classes.Eq B9.DiskImages.ImageDestination instance Data.Data.Data B9.DiskImages.ImageDestination instance GHC.Show.Show B9.DiskImages.ImageDestination instance GHC.Read.Read B9.DiskImages.ImageDestination instance GHC.Generics.Generic B9.DiskImages.ImageSource instance GHC.Classes.Eq B9.DiskImages.ImageSource instance Data.Data.Data B9.DiskImages.ImageSource instance GHC.Read.Read B9.DiskImages.ImageSource instance GHC.Show.Show B9.DiskImages.ImageSource instance GHC.Generics.Generic B9.DiskImages.ImageResize instance Data.Data.Data B9.DiskImages.ImageResize instance GHC.Read.Read B9.DiskImages.ImageResize instance GHC.Show.Show B9.DiskImages.ImageResize instance GHC.Classes.Eq B9.DiskImages.ImageResize instance GHC.Generics.Generic B9.DiskImages.ImageSize instance Data.Data.Data B9.DiskImages.ImageSize instance GHC.Read.Read B9.DiskImages.ImageSize instance GHC.Show.Show B9.DiskImages.ImageSize instance GHC.Classes.Eq B9.DiskImages.ImageSize instance GHC.Generics.Generic B9.DiskImages.SizeUnit instance Data.Data.Data B9.DiskImages.SizeUnit instance GHC.Enum.Bounded B9.DiskImages.SizeUnit instance GHC.Enum.Enum B9.DiskImages.SizeUnit instance GHC.Classes.Ord B9.DiskImages.SizeUnit instance GHC.Read.Read B9.DiskImages.SizeUnit instance GHC.Show.Show B9.DiskImages.SizeUnit instance GHC.Classes.Eq B9.DiskImages.SizeUnit instance GHC.Generics.Generic B9.DiskImages.Image instance Data.Data.Data B9.DiskImages.Image instance GHC.Read.Read B9.DiskImages.Image instance GHC.Show.Show B9.DiskImages.Image instance GHC.Classes.Eq B9.DiskImages.Image instance GHC.Generics.Generic B9.DiskImages.FileSystem instance Data.Data.Data B9.DiskImages.FileSystem instance GHC.Read.Read B9.DiskImages.FileSystem instance GHC.Show.Show B9.DiskImages.FileSystem instance GHC.Classes.Eq B9.DiskImages.FileSystem instance GHC.Generics.Generic B9.DiskImages.ImageType instance GHC.Show.Show B9.DiskImages.ImageType instance Data.Data.Data B9.DiskImages.ImageType instance GHC.Read.Read B9.DiskImages.ImageType instance GHC.Classes.Eq B9.DiskImages.ImageType instance GHC.Generics.Generic B9.DiskImages.Partition instance Data.Data.Data B9.DiskImages.Partition instance GHC.Read.Read B9.DiskImages.Partition instance GHC.Show.Show B9.DiskImages.Partition instance GHC.Classes.Eq B9.DiskImages.Partition instance GHC.Generics.Generic B9.DiskImages.MountPoint instance GHC.Classes.Eq B9.DiskImages.MountPoint instance Data.Data.Data B9.DiskImages.MountPoint instance GHC.Read.Read B9.DiskImages.MountPoint instance GHC.Show.Show B9.DiskImages.MountPoint instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.SharedImage instance Test.QuickCheck.Arbitrary.CoArbitrary B9.DiskImages.SharedImage instance Test.QuickCheck.Function.Function B9.DiskImages.SharedImage instance Data.Hashable.Class.Hashable B9.DiskImages.SharedImage instance Data.Binary.Class.Binary B9.DiskImages.SharedImage instance Control.DeepSeq.NFData B9.DiskImages.SharedImage instance GHC.Classes.Ord B9.DiskImages.SharedImage instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.SharedImageBuildId instance Test.QuickCheck.Function.Function B9.DiskImages.SharedImageBuildId instance Test.QuickCheck.Function.Function B9.DiskImages.SharedImageDate instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.SharedImageDate instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.SharedImageName instance Test.QuickCheck.Function.Function B9.DiskImages.SharedImageName instance Data.Hashable.Class.Hashable B9.DiskImages.ImageTarget instance Data.Binary.Class.Binary B9.DiskImages.ImageTarget instance Control.DeepSeq.NFData B9.DiskImages.ImageTarget instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.ImageTarget instance Data.Hashable.Class.Hashable B9.DiskImages.ImageDestination instance Data.Binary.Class.Binary B9.DiskImages.ImageDestination instance Control.DeepSeq.NFData B9.DiskImages.ImageDestination instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.ImageDestination instance Data.Hashable.Class.Hashable B9.DiskImages.ImageSource instance Data.Binary.Class.Binary B9.DiskImages.ImageSource instance Control.DeepSeq.NFData B9.DiskImages.ImageSource instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.ImageSource instance Data.Hashable.Class.Hashable B9.DiskImages.ImageResize instance Data.Binary.Class.Binary B9.DiskImages.ImageResize instance Control.DeepSeq.NFData B9.DiskImages.ImageResize instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.ImageResize instance Data.Hashable.Class.Hashable B9.DiskImages.ImageSize instance Data.Binary.Class.Binary B9.DiskImages.ImageSize instance Control.DeepSeq.NFData B9.DiskImages.ImageSize instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.ImageSize instance Data.Hashable.Class.Hashable B9.DiskImages.SizeUnit instance Data.Binary.Class.Binary B9.DiskImages.SizeUnit instance Control.DeepSeq.NFData B9.DiskImages.SizeUnit instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.SizeUnit instance Data.Hashable.Class.Hashable B9.DiskImages.Image instance Data.Binary.Class.Binary B9.DiskImages.Image instance Control.DeepSeq.NFData B9.DiskImages.Image instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.Image instance Test.QuickCheck.Function.Function B9.DiskImages.FileSystem instance Test.QuickCheck.Arbitrary.CoArbitrary B9.DiskImages.FileSystem instance Data.Hashable.Class.Hashable B9.DiskImages.FileSystem instance Data.Binary.Class.Binary B9.DiskImages.FileSystem instance Control.DeepSeq.NFData B9.DiskImages.FileSystem instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.FileSystem instance Test.QuickCheck.Arbitrary.CoArbitrary B9.DiskImages.ImageType instance Test.QuickCheck.Function.Function B9.DiskImages.ImageType instance Data.Hashable.Class.Hashable B9.DiskImages.ImageType instance Data.Binary.Class.Binary B9.DiskImages.ImageType instance Control.DeepSeq.NFData B9.DiskImages.ImageType instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.ImageType instance Data.Hashable.Class.Hashable B9.DiskImages.Partition instance Data.Binary.Class.Binary B9.DiskImages.Partition instance Control.DeepSeq.NFData B9.DiskImages.Partition instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.Partition instance Data.Hashable.Class.Hashable B9.DiskImages.MountPoint instance Data.Binary.Class.Binary B9.DiskImages.MountPoint instance Control.DeepSeq.NFData B9.DiskImages.MountPoint instance Test.QuickCheck.Arbitrary.Arbitrary B9.DiskImages.MountPoint -- | Data types describing the execution environment of virtual machine -- builds. ExecEnv, Resources and SharedDirectory -- describe how B9.LibVirtLXC should configure and execute build -- scripts, as defined in B9.ShellScript and B9.Vm. module B9.ExecEnv -- | The environment for the execution of Scripts inside a -- Container data ExecEnv ExecEnv :: String -> [Mounted Image] -> [SharedDirectory] -> Resources -> ExecEnv [envName] :: ExecEnv -> String [envImageMounts] :: ExecEnv -> [Mounted Image] [envSharedDirectories] :: ExecEnv -> [SharedDirectory] [envResources] :: ExecEnv -> Resources data Resources Resources :: RamSize -> Int -> CPUArch -> Resources [maxMemory] :: Resources -> RamSize [cpuCount] :: Resources -> Int [cpuArch] :: Resources -> CPUArch noResources :: Resources data SharedDirectory SharedDirectory :: FilePath -> MountPoint -> SharedDirectory SharedDirectoryRO :: FilePath -> MountPoint -> SharedDirectory SharedSources :: MountPoint -> SharedDirectory data CPUArch X86_64 :: CPUArch I386 :: CPUArch data RamSize RamSize :: Int -> SizeUnit -> RamSize AutomaticRamSize :: RamSize instance GHC.Generics.Generic B9.ExecEnv.ExecEnv instance GHC.Classes.Eq B9.ExecEnv.ExecEnv instance Data.Data.Data B9.ExecEnv.ExecEnv instance GHC.Show.Show B9.ExecEnv.ExecEnv instance GHC.Read.Read B9.ExecEnv.ExecEnv instance GHC.Generics.Generic B9.ExecEnv.Resources instance Data.Data.Data B9.ExecEnv.Resources instance GHC.Show.Show B9.ExecEnv.Resources instance GHC.Read.Read B9.ExecEnv.Resources instance GHC.Classes.Eq B9.ExecEnv.Resources instance GHC.Generics.Generic B9.ExecEnv.RamSize instance Data.Data.Data B9.ExecEnv.RamSize instance GHC.Classes.Ord B9.ExecEnv.RamSize instance GHC.Show.Show B9.ExecEnv.RamSize instance GHC.Read.Read B9.ExecEnv.RamSize instance GHC.Classes.Eq B9.ExecEnv.RamSize instance GHC.Generics.Generic B9.ExecEnv.CPUArch instance GHC.Classes.Eq B9.ExecEnv.CPUArch instance Data.Data.Data B9.ExecEnv.CPUArch instance GHC.Show.Show B9.ExecEnv.CPUArch instance GHC.Read.Read B9.ExecEnv.CPUArch instance GHC.Generics.Generic B9.ExecEnv.SharedDirectory instance GHC.Classes.Eq B9.ExecEnv.SharedDirectory instance Data.Data.Data B9.ExecEnv.SharedDirectory instance GHC.Show.Show B9.ExecEnv.SharedDirectory instance GHC.Read.Read B9.ExecEnv.SharedDirectory instance Data.Hashable.Class.Hashable B9.ExecEnv.ExecEnv instance Data.Binary.Class.Binary B9.ExecEnv.ExecEnv instance Control.DeepSeq.NFData B9.ExecEnv.ExecEnv instance Data.Hashable.Class.Hashable B9.ExecEnv.Resources instance Data.Binary.Class.Binary B9.ExecEnv.Resources instance Control.DeepSeq.NFData B9.ExecEnv.Resources instance GHC.Base.Semigroup B9.ExecEnv.Resources instance GHC.Base.Monoid B9.ExecEnv.Resources instance Data.Hashable.Class.Hashable B9.ExecEnv.RamSize instance Data.Binary.Class.Binary B9.ExecEnv.RamSize instance Control.DeepSeq.NFData B9.ExecEnv.RamSize instance GHC.Base.Semigroup B9.ExecEnv.RamSize instance GHC.Base.Monoid B9.ExecEnv.RamSize instance Data.Hashable.Class.Hashable B9.ExecEnv.CPUArch instance Data.Binary.Class.Binary B9.ExecEnv.CPUArch instance Control.DeepSeq.NFData B9.ExecEnv.CPUArch instance GHC.Base.Semigroup B9.ExecEnv.CPUArch instance GHC.Base.Monoid B9.ExecEnv.CPUArch instance Data.Hashable.Class.Hashable B9.ExecEnv.SharedDirectory instance Data.Binary.Class.Binary B9.ExecEnv.SharedDirectory instance Control.DeepSeq.NFData B9.ExecEnv.SharedDirectory -- | Definition of Script and functions to convert Scripts to -- bash scripts. module B9.ShellScript -- | Convert script to bash-shell-script written to file -- and make file executable. writeSh :: FilePath -> Script -> IO () renderScript :: Script -> String -- | Check if a script has the same effect as NoOP emptyScript :: Script -> Bool data CmdVerbosity Debug :: CmdVerbosity Verbose :: CmdVerbosity OnlyStdErr :: CmdVerbosity Quiet :: CmdVerbosity data Cwd Cwd :: FilePath -> Cwd NoCwd :: Cwd data User User :: String -> User NoUser :: User data Script In :: FilePath -> [Script] -> Script As :: String -> [Script] -> Script IgnoreErrors :: Bool -> [Script] -> Script Verbosity :: CmdVerbosity -> [Script] -> Script Begin :: [Script] -> Script Run :: FilePath -> [String] -> Script NoOP :: Script instance GHC.Generics.Generic B9.ShellScript.Ctx instance GHC.Classes.Eq B9.ShellScript.Ctx instance Data.Data.Data B9.ShellScript.Ctx instance GHC.Read.Read B9.ShellScript.Ctx instance GHC.Show.Show B9.ShellScript.Ctx instance GHC.Generics.Generic B9.ShellScript.Cmd instance GHC.Classes.Eq B9.ShellScript.Cmd instance Data.Data.Data B9.ShellScript.Cmd instance GHC.Read.Read B9.ShellScript.Cmd instance GHC.Show.Show B9.ShellScript.Cmd instance GHC.Generics.Generic B9.ShellScript.User instance GHC.Classes.Eq B9.ShellScript.User instance Data.Data.Data B9.ShellScript.User instance GHC.Read.Read B9.ShellScript.User instance GHC.Show.Show B9.ShellScript.User instance GHC.Generics.Generic B9.ShellScript.Cwd instance GHC.Classes.Eq B9.ShellScript.Cwd instance Data.Data.Data B9.ShellScript.Cwd instance GHC.Read.Read B9.ShellScript.Cwd instance GHC.Show.Show B9.ShellScript.Cwd instance GHC.Generics.Generic B9.ShellScript.Script instance GHC.Classes.Eq B9.ShellScript.Script instance Data.Data.Data B9.ShellScript.Script instance GHC.Read.Read B9.ShellScript.Script instance GHC.Show.Show B9.ShellScript.Script instance GHC.Generics.Generic B9.ShellScript.CmdVerbosity instance GHC.Classes.Eq B9.ShellScript.CmdVerbosity instance Data.Data.Data B9.ShellScript.CmdVerbosity instance GHC.Read.Read B9.ShellScript.CmdVerbosity instance GHC.Show.Show B9.ShellScript.CmdVerbosity instance Data.Hashable.Class.Hashable B9.ShellScript.Ctx instance Data.Binary.Class.Binary B9.ShellScript.Ctx instance Control.DeepSeq.NFData B9.ShellScript.Ctx instance Data.Hashable.Class.Hashable B9.ShellScript.Cmd instance Data.Binary.Class.Binary B9.ShellScript.Cmd instance Control.DeepSeq.NFData B9.ShellScript.Cmd instance Data.Hashable.Class.Hashable B9.ShellScript.User instance Data.Binary.Class.Binary B9.ShellScript.User instance Control.DeepSeq.NFData B9.ShellScript.User instance Data.Hashable.Class.Hashable B9.ShellScript.Cwd instance Data.Binary.Class.Binary B9.ShellScript.Cwd instance Control.DeepSeq.NFData B9.ShellScript.Cwd instance Data.Hashable.Class.Hashable B9.ShellScript.Script instance Data.Binary.Class.Binary B9.ShellScript.Script instance Control.DeepSeq.NFData B9.ShellScript.Script instance GHC.Base.Semigroup B9.ShellScript.Script instance GHC.Base.Monoid B9.ShellScript.Script instance Data.Hashable.Class.Hashable B9.ShellScript.CmdVerbosity instance Data.Binary.Class.Binary B9.ShellScript.CmdVerbosity instance Control.DeepSeq.NFData B9.ShellScript.CmdVerbosity -- | This module enables debugging all ByteString to Text to -- String conversions. This is an internal module. module B9.Text -- | A space efficient, packed, unboxed Unicode text type. data Text -- | Lazy texts. -- -- A type alias to Text that can be used everywhere such that -- references don't need to be qualified with the complete module name -- everywere. type LazyText = Text -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | Lazy byte strings. -- -- A type alias to ByteString that can be used everywhere such -- that references don't need to be qualified with the complete module -- name everywere. type LazyByteString = ByteString -- | A class for values that can be converted to/from Text. class Textual a -- | Convert a String to Text If an error occured, return -- Left with the error message. renderToText :: (Textual a, HasCallStack) => a -> Either String Text -- | Convert a Text to String parseFromText :: (Textual a, HasCallStack) => Text -> Either String a -- | Render a Text to a file. writeTextFile :: (HasCallStack, MonadIO m) => FilePath -> Text -> m () -- | Render a Text via renderToText and throw a runtime -- exception when rendering fails. unsafeRenderToText :: (Textual a, HasCallStack) => a -> Text -- | Parse a Text via parseFromText and throw a runtime -- exception when parsing fails. unsafeParseFromText :: (Textual a, HasCallStack) => Text -> a -- | Parse the given Text. -- Return Left errorMessage or -- Right a. parseFromTextWithErrorMessage :: (HasCallStack, Textual a) => String -> Text -> Either String a -- | Encode a String as UTF-8 encoded into a LazyByteString. encodeAsUtf8LazyByteString :: HasCallStack => String -> LazyByteString instance B9.Text.Textual Data.Text.Internal.Text instance B9.Text.Textual GHC.Base.String instance B9.Text.Textual Data.ByteString.Internal.ByteString instance B9.Text.Textual B9.Text.LazyByteString -- | An Environment contains textual key value pairs, relavant for -- string template substitution. -- -- The variables are passed to the B9 build either via command line, OS -- environment variables or configuration file. module B9.Environment -- | A map of textual keys to textual values. data Environment -- | Create an Environment from a list of pairs (Strings). -- Duplicated entries are ignored. fromStringPairs :: [(String, String)] -> Environment -- | Insert a key value binding to the Environment. -- -- Throw DuplicateKey if the key already exists, but the value is -- not equal to the given value. addBinding :: Member ExcB9 e => (Text, Text) -> Environment -> Eff e Environment -- | Insert Strings into the Environment, see -- addBinding. addStringBinding :: Member ExcB9 e => (String, String) -> Environment -> Eff e Environment -- | Insert a value into an Environment like -- addStringBinding, but add it to the environment of the given -- effect, as in localEnvironment. addLocalStringBinding :: (Member EnvironmentReader e, Member ExcB9 e) => (String, String) -> Eff e a -> Eff e a -- | If environment variables arg_1 .. arg_n are bound and a list -- of k additional values are passed to this function, store -- them with keys arg_(n+1) .. arg_(n+k). -- -- Note that the Environment contains an index of the next position. addPositionalArguments :: [Text] -> Environment -> Environment -- | Convenient wrapper around addPositionalArguments and -- localEnvironment. addLocalPositionalArguments :: Member EnvironmentReader e => [String] -> Eff e a -> Eff e a -- | A monad transformer providing a MonadReader instance for -- Environment type EnvironmentReader = Reader Environment -- | A predicate that is satisfied when a key exists in the environment. hasKey :: Member EnvironmentReader e => Text -> Eff e Bool -- | Run a ReaderT of Environment. runEnvironmentReader :: Environment -> Eff (EnvironmentReader : e) a -> Eff e a -- | Get the current Environment askEnvironment :: Member EnvironmentReader e => Eff e Environment -- | Run a computation with a modified Environment localEnvironment :: Member EnvironmentReader e => (Environment -> Environment) -> Eff e a -> Eff e a -- | Lookup a key for a value. -- -- throwM a KeyNotFound Exception if no value with -- the given key exists in the Environment. -- -- @Since 0.5.62 lookupOrThrow :: '[ExcB9, EnvironmentReader] <:: e => Text -> Eff e Text -- | Lookup a key for a value. -- -- Return Either Left KeyNotFound, if no value with -- the given key exists in the Environment, or Right the -- value. -- -- @Since 0.5.62 lookupEither :: Member EnvironmentReader e => Text -> Eff e (Either KeyNotFound Text) -- | An Exception thrown by lookupOrThrow indicating that a -- key does not exist. -- -- @Since 0.5.62 data KeyNotFound MkKeyNotFound :: Text -> Environment -> KeyNotFound -- | An Exception thrown by addBinding indicating that a key -- already exists. -- -- @Since 0.5.62 data DuplicateKey MkDuplicateKey :: Text -> Text -> Text -> DuplicateKey [duplicateKey] :: DuplicateKey -> Text [duplicateKeyOldValue] :: DuplicateKey -> Text [duplicateKeyNewValue] :: DuplicateKey -> Text instance GHC.Classes.Eq B9.Environment.KeyNotFound instance GHC.Classes.Eq B9.Environment.DuplicateKey instance GHC.Show.Show B9.Environment.DuplicateKey instance GHC.Generics.Generic B9.Environment.Environment instance GHC.Classes.Eq B9.Environment.Environment instance Data.Data.Data B9.Environment.Environment instance GHC.Show.Show B9.Environment.Environment instance GHC.Exception.Type.Exception B9.Environment.KeyNotFound instance GHC.Show.Show B9.Environment.KeyNotFound instance GHC.Exception.Type.Exception B9.Environment.DuplicateKey instance Control.DeepSeq.NFData B9.Environment.Environment instance GHC.Base.Semigroup B9.Environment.Environment instance GHC.Base.Monoid B9.Environment.Environment -- | Erlang term parser and pretty printer. module B9.Artifact.Content.ErlTerms -- | Parse a subset of valid Erlang terms. It parses no maps and binaries -- are restricted to either empty binaries or binaries with a string. The -- input encoding must be restricted to ascii compatible 8-bit characters -- (e.g. latin-1 or UTF8). parseErlTerm :: String -> Text -> Either String SimpleErlangTerm erlTermParser :: Parser SimpleErlangTerm -- | Convert an abstract Erlang term to a pretty byte string preserving the -- encoding. renderErlTerm :: SimpleErlangTerm -> Text -- | Simplified Erlang term representation. data SimpleErlangTerm ErlString :: String -> SimpleErlangTerm ErlFloat :: Double -> SimpleErlangTerm ErlNatural :: Integer -> SimpleErlangTerm ErlAtom :: String -> SimpleErlangTerm ErlChar :: Char -> SimpleErlangTerm ErlBinary :: String -> SimpleErlangTerm ErlList :: [SimpleErlangTerm] -> SimpleErlangTerm ErlTuple :: [SimpleErlangTerm] -> SimpleErlangTerm arbitraryErlSimpleAtom :: Gen SimpleErlangTerm arbitraryErlString :: Gen SimpleErlangTerm arbitraryErlNumber :: Gen SimpleErlangTerm arbitraryErlNatural :: Gen SimpleErlangTerm arbitraryErlFloat :: Gen SimpleErlangTerm arbitraryErlNameChar :: Gen Char instance GHC.Generics.Generic B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance Data.Data.Data B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance GHC.Show.Show B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance GHC.Read.Read B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance GHC.Classes.Ord B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance GHC.Classes.Eq B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance Data.Hashable.Class.Hashable B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance Data.Binary.Class.Binary B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance Control.DeepSeq.NFData B9.Artifact.Content.ErlTerms.SimpleErlangTerm instance Test.QuickCheck.Arbitrary.Arbitrary B9.Artifact.Content.ErlTerms.SimpleErlangTerm -- | Some utilities to deal with IO in B9. module System.IO.B9Extras -- | A data type encapsulating different kinds of relative or absolute -- paths. data SystemPath -- | A path that will just be passed through Path :: FilePath -> SystemPath -- | A OS specific path relative to the home directory of a user. InHomeDir :: FilePath -> SystemPath -- | A path relative to the b9 sub of the users application -- configuration directory getAppUserDataDirectory InB9UserDir :: FilePath -> SystemPath -- | A path relative to the systems temporary directory. InTempDir :: FilePath -> SystemPath -- | Transform a SystemPath overSystemPath :: (FilePath -> FilePath) -> SystemPath -> SystemPath -- | Convert a SystemPath to a FilePath. resolve :: MonadIO m => SystemPath -> m FilePath -- | Create all missing parent directories of a file path. ensureSystemPath :: MonadIO m => SystemPath -> m () -- | Create all missing parent directories of a file path. Note that the -- file path is assumed to be of a regular file, and takeDirectory -- is applied before creating the directory. ensureDir :: MonadIO m => FilePath -> m () -- | Get all files from dir that is get ONLY files not directories getDirectoryFiles :: MonadIO m => FilePath -> m [FilePath] -- | Write a value of a type that is an instance of Show to file. -- This function uses ppShow instead of the given Show -- instance. prettyPrintToFile :: (MonadIO m, Show a) => FilePath -> a -> m () -- | Read a value of a type that is an instance of Read from a file. -- This function throws a ConsultException when the read the file -- failed. consult :: (MonadIO m, Read a) => FilePath -> m a -- | An Exception thrown by consult to indicate the file does -- not contain a readable String data ConsultException ConsultException :: FilePath -> String -> ConsultException -- | Generate a random UUID. randomUUID :: MonadIO m => m UUID -- | A bunch of numbers, enough to make globally unique IDs. Create one of -- these using randomUUID. data UUID removeIfExists :: FilePath -> IO () instance GHC.Classes.Ord System.IO.B9Extras.UUID instance GHC.Classes.Eq System.IO.B9Extras.UUID instance GHC.Show.Show System.IO.B9Extras.UUID instance GHC.Read.Read System.IO.B9Extras.UUID instance GHC.Show.Show System.IO.B9Extras.ConsultException instance Data.Data.Data System.IO.B9Extras.SystemPath instance GHC.Show.Show System.IO.B9Extras.SystemPath instance GHC.Read.Read System.IO.B9Extras.SystemPath instance GHC.Classes.Eq System.IO.B9Extras.SystemPath instance Text.Printf.PrintfArg System.IO.B9Extras.UUID instance GHC.Exception.Type.Exception System.IO.B9Extras.ConsultException -- | Extensions to ConfigFile and utility functions for dealing with -- configuration in general and reading/writing files. module Data.ConfigFile.B9Extras -- | An alias for add_section. addSectionCP :: MonadError CPError m => CPDocument -> CPSectionSpec -> m CPDocument -- | An alias for setshow. setShowCP :: (Show a, MonadError CPError m) => CPDocument -> CPSectionSpec -> CPOptionSpec -> a -> m CPDocument -- | An alias for set. setCP :: MonadError CPError m => CPDocument -> CPSectionSpec -> CPOptionSpec -> String -> m CPDocument -- | An alias for get. readCP :: (CPGet a, MonadError CPError m) => CPDocument -> CPSectionSpec -> CPOptionSpec -> m a -- | An alias for merge. mergeCP :: CPDocument -> CPDocument -> CPDocument -- | An alias for to_string toStringCP :: CPDocument -> String -- | An alias for sections. sectionsCP :: CPDocument -> [SectionSpec] -- | The default empty ConfigFile object. -- -- The content contains only an empty mandatory DEFAULT section. -- -- optionxform is set to map toLower. -- -- usedefault is set to True. -- -- accessfunc is set to simpleAccess. emptyCP :: ConfigParser -- | An alias for Get_C type CPGet a = Get_C a -- | An alias for OptionSpec type CPOptionSpec = OptionSpec -- | An alias for SectionSpec. type CPSectionSpec = SectionSpec -- | An alias for ConfigParser type CPDocument = ConfigParser -- | Indicates an error occurred. The String is an explanation of the -- location of the error. type CPError = (CPErrorData, String) -- | Read a file and try to parse the contents as a CPDocument, if -- something goes wrong throw a CPReadException readCPDocument :: MonadIO m => SystemPath -> m CPDocument -- | An exception thrown by readCPDocument. data CPReadException CPReadException :: FilePath -> CPError -> CPReadException instance GHC.Show.Show Data.ConfigFile.B9Extras.CPReadException instance GHC.Exception.Type.Exception Data.ConfigFile.B9Extras.CPReadException module B9.B9Config.Repository data RemoteRepo RemoteRepo :: String -> FilePath -> SshPrivKey -> SshRemoteHost -> SshRemoteUser -> RemoteRepo remoteRepoRepoId :: RemoteRepo -> String newtype RepoCache RepoCache :: FilePath -> RepoCache newtype SshPrivKey SshPrivKey :: FilePath -> SshPrivKey newtype SshRemoteHost SshRemoteHost :: (String, Int) -> SshRemoteHost newtype SshRemoteUser SshRemoteUser :: String -> SshRemoteUser -- | Persist a repo to a configuration file. remoteRepoToCPDocument :: RemoteRepo -> CPDocument -> Either CPError CPDocument -- | Load a repository from a configuration file that has been written by -- writeRepositoryToB9Config. parseRemoteRepos :: CPDocument -> Either CPError [RemoteRepo] instance GHC.Classes.Ord B9.B9Config.Repository.RemoteRepo instance GHC.Classes.Eq B9.B9Config.Repository.RemoteRepo instance Data.Data.Data B9.B9Config.Repository.RemoteRepo instance GHC.Show.Show B9.B9Config.Repository.RemoteRepo instance GHC.Read.Read B9.B9Config.Repository.RemoteRepo instance GHC.Classes.Ord B9.B9Config.Repository.SshRemoteUser instance GHC.Classes.Eq B9.B9Config.Repository.SshRemoteUser instance Data.Data.Data B9.B9Config.Repository.SshRemoteUser instance GHC.Show.Show B9.B9Config.Repository.SshRemoteUser instance GHC.Read.Read B9.B9Config.Repository.SshRemoteUser instance GHC.Classes.Ord B9.B9Config.Repository.SshRemoteHost instance GHC.Classes.Eq B9.B9Config.Repository.SshRemoteHost instance Data.Data.Data B9.B9Config.Repository.SshRemoteHost instance GHC.Show.Show B9.B9Config.Repository.SshRemoteHost instance GHC.Read.Read B9.B9Config.Repository.SshRemoteHost instance GHC.Classes.Ord B9.B9Config.Repository.SshPrivKey instance GHC.Classes.Eq B9.B9Config.Repository.SshPrivKey instance Data.Data.Data B9.B9Config.Repository.SshPrivKey instance GHC.Show.Show B9.B9Config.Repository.SshPrivKey instance GHC.Read.Read B9.B9Config.Repository.SshPrivKey instance Data.Data.Data B9.B9Config.Repository.RepoCache instance GHC.Show.Show B9.B9Config.Repository.RepoCache instance GHC.Read.Read B9.B9Config.Repository.RepoCache instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.Repository.RemoteRepo instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.Repository.SshRemoteUser instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.Repository.SshRemoteHost instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.Repository.SshPrivKey module B9.B9Config.Container parseContainerCapabilities :: CPDocument -> CPSectionSpec -> Either CPError [ContainerCapability] -- | Available capabilities for Linux containers. This maps directly to the -- capabilities defined in 'man 7 capabilities'. data ContainerCapability CAP_MKNOD :: ContainerCapability CAP_AUDIT_CONTROL :: ContainerCapability CAP_AUDIT_READ :: ContainerCapability CAP_AUDIT_WRITE :: ContainerCapability CAP_BLOCK_SUSPEND :: ContainerCapability CAP_CHOWN :: ContainerCapability CAP_DAC_OVERRIDE :: ContainerCapability CAP_DAC_READ_SEARCH :: ContainerCapability CAP_FOWNER :: ContainerCapability CAP_FSETID :: ContainerCapability CAP_IPC_LOCK :: ContainerCapability CAP_IPC_OWNER :: ContainerCapability CAP_KILL :: ContainerCapability CAP_LEASE :: ContainerCapability CAP_LINUX_IMMUTABLE :: ContainerCapability CAP_MAC_ADMIN :: ContainerCapability CAP_MAC_OVERRIDE :: ContainerCapability CAP_NET_ADMIN :: ContainerCapability CAP_NET_BIND_SERVICE :: ContainerCapability CAP_NET_BROADCAST :: ContainerCapability CAP_NET_RAW :: ContainerCapability CAP_SETGID :: ContainerCapability CAP_SETFCAP :: ContainerCapability CAP_SETPCAP :: ContainerCapability CAP_SETUID :: ContainerCapability CAP_SYS_ADMIN :: ContainerCapability CAP_SYS_BOOT :: ContainerCapability CAP_SYS_CHROOT :: ContainerCapability CAP_SYS_MODULE :: ContainerCapability CAP_SYS_NICE :: ContainerCapability CAP_SYS_PACCT :: ContainerCapability CAP_SYS_PTRACE :: ContainerCapability CAP_SYS_RAWIO :: ContainerCapability CAP_SYS_RESOURCE :: ContainerCapability CAP_SYS_TIME :: ContainerCapability CAP_SYS_TTY_CONFIG :: ContainerCapability CAP_SYSLOG :: ContainerCapability CAP_WAKE_ALARM :: ContainerCapability containerCapsToCPDocument :: CPDocument -> CPSectionSpec -> [ContainerCapability] -> Either CPError CPDocument instance GHC.Enum.Bounded B9.B9Config.Container.ContainerCapability instance GHC.Enum.Enum B9.B9Config.Container.ContainerCapability instance GHC.Classes.Eq B9.B9Config.Container.ContainerCapability instance GHC.Show.Show B9.B9Config.Container.ContainerCapability instance GHC.Read.Read B9.B9Config.Container.ContainerCapability instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.Container.ContainerCapability module B9.B9Config.SystemdNspawn systemdNspawnConfigToCPDocument :: SystemdNspawnConfig -> CPDocument -> Either CPError CPDocument defaultSystemdNspawnConfig :: SystemdNspawnConfig parseSystemdNspawnConfig :: CPDocument -> Either CPError SystemdNspawnConfig data SystemdNspawnConfig SystemdNspawnConfig :: [ContainerCapability] -> Bool -> Maybe Int -> Maybe String -> Maybe FilePath -> SystemdNspawnConsole -> SystemdNspawnConfig [_systemdNspawnCapabilities] :: SystemdNspawnConfig -> [ContainerCapability] [_systemdNspawnUseSudo] :: SystemdNspawnConfig -> Bool [_systemdNspawnMaxLifetimeSeconds] :: SystemdNspawnConfig -> Maybe Int [_systemdNspawnExtraArgs] :: SystemdNspawnConfig -> Maybe String [_systemdNspawnExecutable] :: SystemdNspawnConfig -> Maybe FilePath [_systemdNspawnConsole] :: SystemdNspawnConfig -> SystemdNspawnConsole data SystemdNspawnConsole SystemdNspawnInteractive :: SystemdNspawnConsole SystemdNspawnReadOnly :: SystemdNspawnConsole SystemdNspawnPassive :: SystemdNspawnConsole SystemdNspawnPipe :: SystemdNspawnConsole systemdNspawnCapabilities :: Lens' SystemdNspawnConfig [ContainerCapability] systemdNspawnUseSudo :: Lens' SystemdNspawnConfig Bool systemdNspawnMaxLifetimeSeconds :: Lens' SystemdNspawnConfig (Maybe Int) systemdNspawnExtraArgs :: Lens' SystemdNspawnConfig (Maybe String) systemdNspawnExecutable :: Lens' SystemdNspawnConfig (Maybe FilePath) systemdNspawnConsole :: Lens' SystemdNspawnConfig SystemdNspawnConsole instance GHC.Classes.Eq B9.B9Config.SystemdNspawn.SystemdNspawnConfig instance GHC.Show.Show B9.B9Config.SystemdNspawn.SystemdNspawnConfig instance GHC.Read.Read B9.B9Config.SystemdNspawn.SystemdNspawnConfig instance GHC.Classes.Eq B9.B9Config.SystemdNspawn.SystemdNspawnConsole instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.SystemdNspawn.SystemdNspawnConfig instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.SystemdNspawn.SystemdNspawnConsole instance GHC.Show.Show B9.B9Config.SystemdNspawn.SystemdNspawnConsole instance GHC.Read.Read B9.B9Config.SystemdNspawn.SystemdNspawnConsole module B9.B9Config.Podman podmanConfigToCPDocument :: PodmanConfig -> CPDocument -> Either CPError CPDocument defaultPodmanConfig :: PodmanConfig parsePodmanConfig :: CPDocument -> Either CPError PodmanConfig data PodmanConfig PodmanConfig :: Maybe String -> [ContainerCapability] -> PodmanConfig [_podmanNetworkId] :: PodmanConfig -> Maybe String [_podmanCapabilities] :: PodmanConfig -> [ContainerCapability] podmanNetworkId :: Lens' PodmanConfig (Maybe String) podmanCapabilities :: Lens' PodmanConfig [ContainerCapability] instance GHC.Classes.Eq B9.B9Config.Podman.PodmanConfig instance GHC.Show.Show B9.B9Config.Podman.PodmanConfig instance GHC.Read.Read B9.B9Config.Podman.PodmanConfig module B9.B9Config.LibVirtLXC libVirtLXCConfigToCPDocument :: LibVirtLXCConfig -> CPDocument -> Either CPError CPDocument defaultLibVirtLXCConfig :: LibVirtLXCConfig parseLibVirtLXCConfig :: CPDocument -> Either CPError LibVirtLXCConfig data LibVirtLXCConfig LibVirtLXCConfig :: Bool -> Maybe FilePath -> FilePath -> Maybe String -> [ContainerCapability] -> RamSize -> LibVirtLXCConfig [useSudo] :: LibVirtLXCConfig -> Bool [emulator] :: LibVirtLXCConfig -> Maybe FilePath [virshURI] :: LibVirtLXCConfig -> FilePath [_networkId] :: LibVirtLXCConfig -> Maybe String [guestCapabilities] :: LibVirtLXCConfig -> [ContainerCapability] [guestRamSize] :: LibVirtLXCConfig -> RamSize networkId :: Lens' LibVirtLXCConfig (Maybe String) -- | Return the path to -- usrliblibvirtlibexec/libvirt_lxc the -- emulatorK field from the config file, or set the path in the -- environment variable named like the value in emulatorEnvVar -- dictates. getEmulatorPath :: MonadIO m => LibVirtLXCConfig -> m FilePath instance GHC.Classes.Eq B9.B9Config.LibVirtLXC.LibVirtLXCConfig instance GHC.Show.Show B9.B9Config.LibVirtLXC.LibVirtLXCConfig instance GHC.Read.Read B9.B9Config.LibVirtLXC.LibVirtLXCConfig instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.LibVirtLXC.LibVirtLXCConfig module B9.B9Config.Docker dockerConfigToCPDocument :: DockerConfig -> CPDocument -> Either CPError CPDocument defaultDockerConfig :: DockerConfig parseDockerConfig :: CPDocument -> Either CPError DockerConfig data DockerConfig DockerConfig :: Maybe String -> [ContainerCapability] -> DockerConfig [_dockerNetworkId] :: DockerConfig -> Maybe String [_dockerCapabilities] :: DockerConfig -> [ContainerCapability] dockerNetworkId :: Lens' DockerConfig (Maybe String) dockerCapabilities :: Lens' DockerConfig [ContainerCapability] instance GHC.Classes.Eq B9.B9Config.Docker.DockerConfig instance GHC.Show.Show B9.B9Config.Docker.DockerConfig instance GHC.Read.Read B9.B9Config.Docker.DockerConfig -- | Static B9 configuration. Read, write and merge configurable -- properties. The properties are independent of specific build targets. module B9.B9Config data B9Config B9Config :: Maybe LogLevel -> Maybe FilePath -> Maybe FilePath -> Bool -> Bool -> Maybe SystemPath -> Maybe String -> Maybe Int -> Maybe SystemdNspawnConfig -> Maybe PodmanConfig -> Maybe DockerConfig -> Maybe LibVirtLXCConfig -> Set RemoteRepo -> Maybe Timeout -> Maybe Int -> [String] -> B9Config [_verbosity] :: B9Config -> Maybe LogLevel [_logFile] :: B9Config -> Maybe FilePath [_projectRoot] :: B9Config -> Maybe FilePath [_keepTempDirs] :: B9Config -> Bool [_uniqueBuildDirs] :: B9Config -> Bool [_repositoryCache] :: B9Config -> Maybe SystemPath [_repository] :: B9Config -> Maybe String [_maxLocalSharedImageRevisions] :: B9Config -> Maybe Int [_systemdNspawnConfigs] :: B9Config -> Maybe SystemdNspawnConfig [_podmanConfigs] :: B9Config -> Maybe PodmanConfig [_dockerConfigs] :: B9Config -> Maybe DockerConfig [_libVirtLXCConfigs] :: B9Config -> Maybe LibVirtLXCConfig [_remoteRepos] :: B9Config -> Set RemoteRepo [_defaultTimeout] :: B9Config -> Maybe Timeout [_timeoutFactor] :: B9Config -> Maybe Int [_ext4Attributes] :: B9Config -> [String] -- | A way to specify a time intervall for example for the timeouts of -- system commands. newtype Timeout TimeoutMicros :: Int -> Timeout -- | Run a B9ConfigReader. runB9ConfigReader :: HasCallStack => B9Config -> Eff (B9ConfigReader : e) a -> Eff e a -- | Reader for B9Config. See getB9Config and -- localB9Config. type B9ConfigReader = Reader B9Config -- | Return the runtime configuration, that should be the configuration -- merged from all configuration sources. This is the configuration to be -- used during a VM image build. getB9Config :: Member B9ConfigReader e => Eff e B9Config -- | An alias for getB9Config. -- -- @deprecated getConfig :: Member B9ConfigReader e => Eff e B9Config -- | Ask for the LogLevel. getLogVerbosity :: Member B9ConfigReader e => Eff e (Maybe LogLevel) -- | Ask for the project root directory. getProjectRoot :: Member B9ConfigReader e => Eff e FilePath -- | Ask for the RemoteRepos. getRemoteRepos :: Member B9ConfigReader e => Eff e (Set RemoteRepo) -- | Accumulate B9Config changes that go back to the config file. -- See B9ConfigAction and modifyPermanentConfig. type B9ConfigWriter = Writer (Endo B9Config) verbosity :: Lens' B9Config (Maybe LogLevel) logFile :: Lens' B9Config (Maybe FilePath) ext4Attributes :: Lens' B9Config [String] projectRoot :: Lens' B9Config (Maybe FilePath) keepTempDirs :: Lens' B9Config Bool uniqueBuildDirs :: Lens' B9Config Bool repositoryCache :: Lens' B9Config (Maybe SystemPath) repository :: Lens' B9Config (Maybe String) defaultTimeout :: Lens' B9Config (Maybe Timeout) libVirtLXCConfigs :: Lens' B9Config (Maybe LibVirtLXCConfig) dockerConfigs :: Lens' B9Config (Maybe DockerConfig) podmanConfigs :: Lens' B9Config (Maybe PodmanConfig) systemdNspawnConfigs :: Lens' B9Config (Maybe SystemdNspawnConfig) remoteRepos :: Lens' B9Config (Set RemoteRepo) timeoutFactor :: Lens' B9Config (Maybe Int) maxLocalSharedImageRevisionsK :: String maxLocalSharedImageRevisions :: Lens' B9Config (Maybe Int) -- | Override b9 configuration items and/or the path of the b9 -- configuration file. This is useful, i.e. when dealing with command -- line parameters. data B9ConfigOverride B9ConfigOverride :: [SystemPath] -> Endo B9Config -> Environment -> Maybe SystemPath -> B9ConfigOverride [_customB9ConfigPath] :: B9ConfigOverride -> [SystemPath] [_customB9Config] :: B9ConfigOverride -> Endo B9Config [_customEnvironment] :: B9ConfigOverride -> Environment [_customDefaulB9ConfigPath] :: B9ConfigOverride -> Maybe SystemPath -- | An empty default B9ConfigOverride value, that will neither -- apply any additional B9Config nor change the path of the -- configuration file. noB9ConfigOverride :: B9ConfigOverride -- | A monad that gives access to the (transient) B9Config to be -- used at _runtime_ with getB9Config or localB9Config, and -- that allows to write permanent B9Config changes back to the -- configuration file using modifyPermanentConfig. This is the -- amalgamation of B9ConfigWriter B9ConfigReader and -- IO. type B9ConfigAction a = Eff '[B9ConfigWriter, B9ConfigReader, EnvironmentReader, Lift IO] a -- | Execute a B9ConfigAction. It will take a -- B9ConfigOverride as input. The B9Config in that value is -- treated as the _runtime_ configuration, and the -- _customConfigPath is used as the alternative location of the -- configuration file. The configuration file is read from either the -- path in _customB9ConfigPath or from defaultB9ConfigFile. -- Every modification done via modifyPermanentConfig is applied to -- the **contents** of the configuration file and written back to that -- file, note that these changes are ONLY reflected in the configuration -- file and **not** in the _runtime configuration_. -- -- See also runB9ConfigAction, which does not need the -- B9ConfigOverride parameter. runB9ConfigActionWithOverrides :: HasCallStack => B9ConfigAction a -> B9ConfigOverride -> IO a -- | Run a B9ConfigAction using noB9ConfigOverride. See -- runB9ConfigActionWithOverrides for more details. runB9ConfigAction :: HasCallStack => B9ConfigAction a -> IO a -- | Run an action with an updated runtime configuration. localB9Config :: Member B9ConfigReader e => (B9Config -> B9Config) -> Eff e a -> Eff e a -- | Add a modification to the permanent configuration file. modifyPermanentConfig :: (HasCallStack, Member B9ConfigWriter e) => Endo B9Config -> Eff e () customB9Config :: Lens' B9ConfigOverride (Endo B9Config) customB9ConfigPath :: Lens' B9ConfigOverride [SystemPath] customEnvironment :: Lens' B9ConfigOverride Environment customDefaulB9ConfigPath :: Lens' B9ConfigOverride (Maybe SystemPath) -- | Convenience utility to override the B9 configuration file path. overrideB9ConfigPath :: SystemPath -> B9ConfigOverride -> B9ConfigOverride -- | Convenience utility to override the *default* B9 configuration file -- path. overrideDefaultB9ConfigPath :: SystemPath -> B9ConfigOverride -> B9ConfigOverride -- | Modify the runtime configuration. overrideB9Config :: (B9Config -> B9Config) -> B9ConfigOverride -> B9ConfigOverride -- | Define the current working directory to be used when building. overrideWorkingDirectory :: FilePath -> B9ConfigOverride -> B9ConfigOverride -- | Define the default timeout for external commands. overrideDefaultTimeout :: Maybe Timeout -> B9ConfigOverride -> B9ConfigOverride -- | Define the timeout factor for external commands. overrideTimeoutFactor :: Maybe Int -> B9ConfigOverride -> B9ConfigOverride -- | Overwrite the verbosity settings in the configuration with -- those given. overrideVerbosity :: LogLevel -> B9ConfigOverride -> B9ConfigOverride -- | Overwrite the keepTempDirs flag in the configuration with those -- given. overrideKeepBuildDirs :: Bool -> B9ConfigOverride -> B9ConfigOverride -- | Overwrite the ext4Attributes overrideExt4Attributes :: [String] -> B9ConfigOverride -> B9ConfigOverride defaultB9ConfigFile :: SystemPath defaultRepositoryCache :: SystemPath defaultB9Config :: B9Config -- | Open the configuration file that contains the B9Config. If the -- configuration does not exist, write a default configuration file, and -- create a all missing directories. openOrCreateB9Config :: (HasCallStack, MonadIO m) => FilePath -> m CPDocument -- | Write the configuration in the CPDocument to either the user -- supplied configuration file path or to defaultB9ConfigFile. -- Create all missing (parent) directories. writeB9CPDocument :: (HasCallStack, MonadIO m) => Maybe SystemPath -> CPDocument -> m () readB9Config :: (HasCallStack, MonadIO m) => Maybe SystemPath -> m CPDocument parseB9Config :: HasCallStack => CPDocument -> Either CPError B9Config -- | Parse a B9Config, modify it, and merge it back to the given -- CPDocument. modifyCPDocument :: CPDocument -> Endo B9Config -> Either CPError CPDocument -- | Append a config file section for the B9Config to an empty -- CPDocument. b9ConfigToCPDocument :: HasCallStack => B9Config -> Either CPError CPDocument data LogLevel LogTrace :: LogLevel LogDebug :: LogLevel LogInfo :: LogLevel LogError :: LogLevel LogNothing :: LogLevel -- | A map of textual keys to textual values. data Environment instance GHC.Classes.Eq B9.B9Config.B9Config instance GHC.Show.Show B9.B9Config.B9Config instance GHC.Read.Read B9.B9Config.LogLevel instance GHC.Classes.Ord B9.B9Config.LogLevel instance GHC.Show.Show B9.B9Config.LogLevel instance GHC.Classes.Eq B9.B9Config.LogLevel instance GHC.Read.Read B9.B9Config.Timeout instance GHC.Classes.Ord B9.B9Config.Timeout instance GHC.Classes.Eq B9.B9Config.Timeout instance GHC.Show.Show B9.B9Config.Timeout instance GHC.Show.Show B9.B9Config.B9ConfigOverride instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.B9Config instance GHC.Base.Semigroup B9.B9Config.B9Config instance GHC.Base.Monoid B9.B9Config.B9Config instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.LogLevel instance Test.QuickCheck.Arbitrary.Arbitrary B9.B9Config.Timeout -- | B9 has a concept of SharedImaged. Shared images can be pulled -- and pushed to/from remote locations via rsync+ssh. B9 also maintains a -- local cache; the whole thing is supposed to be build-server-safe, that -- means no two builds shall interfere with each other. This is -- accomplished by refraining from automatic cache updates from/to remote -- repositories. module B9.Repository -- | Alias for a Reader Effect that reads a list of -- RemoteRepos. type RepoCacheReader = Reader RepoCache -- | Ask for the RepoCache initialized by withRemoteRepos. getRepoCache :: Member RepoCacheReader e => Eff e RepoCache -- | Run a SelectedRemoteRepoReader with the -- SelectedRemoteRepo selected in the B9Config. -- -- If the selected repo does not exist, and exception is thrown. withSelectedRemoteRepo :: (Member B9ConfigReader e, Member ExcB9 e) => Eff (SelectedRemoteRepoReader : e) a -> Eff e a -- | Ask for the RemoteRepo selected by the B9Config value -- _repository. See withSelectedRemoteRepo. getSelectedRemoteRepo :: Member SelectedRemoteRepoReader e => Eff e SelectedRemoteRepo -- | Alias for a Reader Effect that reads the -- RemoteRepo selected by the B9Config value -- _repository. See withSelectedRemoteRepo. type SelectedRemoteRepoReader = Reader SelectedRemoteRepo data Repository Cache :: Repository Remote :: String -> Repository -- | A Map that maps Repositorys to the SharedImages -- they hold. type RepoImagesMap = Map Repository (Set SharedImage) -- | Convert a RemoteRepo down to a mere Repository toRemoteRepository :: RemoteRepo -> Repository -- | Contains the Just the RemoteRepo selected by the -- B9Config value _repository, or Nothing of no -- RemoteRepo was selected in the B9Config. newtype SelectedRemoteRepo MkSelectedRemoteRepo :: Maybe RemoteRepo -> SelectedRemoteRepo [fromSelectedRemoteRepo] :: SelectedRemoteRepo -> Maybe RemoteRepo -- | Return the cache directory for a remote repository relative to the -- root cache dir. remoteRepoCacheDir :: RepoCache -> String -> FilePath -- | Return the local repository directory. localRepoDir :: RepoCache -> FilePath -- | Select the first RemoteRepo with a given repoId. lookupRemoteRepo :: Set RemoteRepo -> String -> Maybe RemoteRepo -- | Filter the SharedImages returned by getSharedImages -- using a Repository-, and a SharedImage predicate. filterRepoImagesMap :: (Repository -> Bool) -> (SharedImage -> Bool) -> RepoImagesMap -> RepoImagesMap -- | Return the versions of a shared image named name from the -- local cache. lookupCachedImages :: SharedImageName -> RepoImagesMap -> Set SharedImage -- | Keep SharedImages that are in the Cache -- Repository. allCachedSharedImages :: RepoImagesMap -> Set SharedImage -- | Fetch all SharedImages like allSharedImages but attach -- the Repository that the image belongs to. -- -- Usage example: In combination with filterRepoImagesMap to find -- the latest version of a certain image in all known repositories. allSharedImagesWithRepo :: RepoImagesMap -> Set (SharedImage, Repository) -- | Return the maximum with regard to the Ord instance of -- SharedImage from an RepoImagesMap maxSharedImageOfAllRepos :: RepoImagesMap -> Maybe (SharedImage, Repository) -- | Return the SharedImages, that are contained in a -- Repository. allSharedImagesInRepo :: Repository -> RepoImagesMap -> Set SharedImage -- | Get a Set of all SharedImages in all Repositorys. allSharedImages :: RepoImagesMap -> Set SharedImage -- | Return a Set of Repository names from a -- RepoImagesMap allRepositories :: RepoImagesMap -> Set Repository -- | Group by SharedImageName. groupBySharedImageName :: Set SharedImage -> Map SharedImageName (Set SharedImage) -- | Take a subset that contains the n latest versions of -- SharedImages with the same name. -- -- For example, if the input contains: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:31" , -- SharedImage "foo" "2020-07-07 13:34:32" , SharedImage "foo" -- "2020-07-07 13:34:33" , SharedImage "bar" "2020-07-07 13:34:34" , -- SharedImage "bar" "2020-07-07 13:34:35" , SharedImage "bar" -- "2020-07-07 13:34:36" ] @@ -- -- The output of keepNLatestSharedImages 2 will be: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:32" , -- SharedImage "foo" "2020-07-07 13:34:33" , SharedImage "bar" -- "2020-07-07 13:34:35" , SharedImage "bar" "2020-07-07 13:34:36" ] -- @@ keepNLatestSharedImages :: Int -> Set SharedImage -> Set SharedImage -- | Take a subset that contains obsolete images. -- -- Do the opposite of keepNLatestSharedImages, and return all -- **but** the n latest versions of SharedImages with the -- same name. -- -- For example, if the input contains: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:31" , -- SharedImage "foo" "2020-07-07 13:34:32" , SharedImage "foo" -- "2020-07-07 13:34:33" , SharedImage "bar" "2020-07-07 13:34:34" , -- SharedImage "bar" "2020-07-07 13:34:35" , SharedImage "bar" -- "2020-07-07 13:34:36" ] @@ -- -- The output of keepNLatestSharedImages 2 will be: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:31" , -- SharedImage "bar" "2020-07-07 13:34:34" ] @@ dropAllButNLatestSharedImages :: Int -> Set SharedImage -> Set SharedImage instance GHC.Generics.Generic B9.Repository.Repository instance GHC.Show.Show B9.Repository.Repository instance GHC.Read.Read B9.Repository.Repository instance GHC.Classes.Ord B9.Repository.Repository instance GHC.Classes.Eq B9.Repository.Repository instance Test.QuickCheck.Arbitrary.Arbitrary B9.Repository.Repository instance Test.QuickCheck.Function.Function B9.Repository.Repository instance Test.QuickCheck.Arbitrary.CoArbitrary B9.Repository.Repository -- | This modules contains support for logging. module B9.B9Logging -- | The logger to write log messages to. newtype Logger MkLogger :: Maybe Handle -> Logger [logFileHandle] :: Logger -> Maybe Handle -- | Convenience type alias for Effects that have a B9Config, -- a Logger, MonadIO and MonadBaseControl. type CommandIO e = (MonadBaseControl IO (Eff e), MonadIO (Eff e), Member LoggerReader e, Member B9ConfigReader e) -- | Effect that reads a Logger. type LoggerReader = Reader Logger -- | Lookup the selected getLogVerbosity and _logFile from -- the B9Config and open it. -- -- Then run the given action; if the action crashes, the log file will be -- closed. withLogger :: (MonadBaseControl IO (Eff e), MonadIO (Eff e), Member B9ConfigReader e) => Eff (LoggerReader : e) a -> Eff e a b9Log :: CommandIO e => LogLevel -> String -> Eff e () traceL :: CommandIO e => String -> Eff e () dbgL :: CommandIO e => String -> Eff e () infoL :: CommandIO e => String -> Eff e () errorL :: CommandIO e => String -> Eff e () errorExitL :: (CommandIO e, Member ExcB9 e) => String -> Eff e a printHash :: Hashable a => a -> String -- | Provide information about the current build. -- -- This module provides build meta information like build directory, -- build-id and build-time. module B9.BuildInfo getBuildId :: Member BuildInfoReader e => Eff e String getBuildDate :: Member BuildInfoReader e => Eff e String getBuildDir :: Member BuildInfoReader e => Eff e FilePath -- | Create the build directories, generate (hash) the build-id and execute -- the given action. -- -- Bindings added to the text template parameter environment: -- --
-- Let [ ... bindings ... ] -- [ Sources -- [ ... list all input files ... ] -- [ Artifact ... -- , Artifact ... -- , Let [ ... ] [ ... ] -- ] -- ] ---- -- The reasons why Sources takes a list of -- ArtifactGenerators is that -- --
-- LetX [("x", ["1","2","3"]), ("y", ["a","b"])] [..]
--
--
-- Is equal to:
--
--
-- Let [] [
-- Let [("x", "1"), ("y", "a")] [..]
-- Let [("x", "1"), ("y", "b")] [..]
-- Let [("x", "2"), ("y", "a")] [..]
-- Let [("x", "2"), ("y", "b")] [..]
-- Let [("x", "3"), ("y", "a")] [..]
-- Let [("x", "3"), ("y", "b")] [..]
-- ]
--
--
-- @deprecated TODO remove this when switching to Dhall
LetX :: [(String, [String])] -> [ArtifactGenerator] -> ArtifactGenerator
-- | Bind each variable to their first value, then each variable to the
-- second value, etc ... and execute the nested generator in every step.
-- LetX represents a product of all variables, whereas Each
-- represents a sum of variable bindings - Each is more like a
-- zip whereas LetX is more like a list comprehension.
-- @deprecated TODO remove this when switching to Dhall
Each :: [(String, [String])] -> [ArtifactGenerator] -> ArtifactGenerator
-- | The transposed version of Each: Bind the variables in the first
-- list to each a set of values from the second argument; execute the
-- nested generators for each binding @deprecated TODO remove this when
-- switching to Dhall
EachT :: [String] -> [[String]] -> [ArtifactGenerator] -> ArtifactGenerator
-- | Generate an artifact defined by an ArtifactAssembly; the
-- assembly can access the files created from the Sources and
-- variables bound by Letish elements. An artifact has an instance
-- id, that is a unique, human readable string describing the artifact to
-- assemble.
Artifact :: InstanceId -> ArtifactAssembly -> ArtifactGenerator
EmptyArtifact :: ArtifactGenerator
-- | Identify an artifact. Deprecated TODO: B9 does not check if all
-- instances IDs are unique.
newtype InstanceId
IID :: String -> InstanceId
data ArtifactTarget
CloudInitTarget :: CloudInitType -> FilePath -> ArtifactTarget
VmImagesTarget :: ArtifactTarget
data CloudInitType
CI_ISO :: CloudInitType
CI_VFAT :: CloudInitType
CI_DIR :: CloudInitType
-- | Define an output of a build. Assemblies are nested into
-- ArtifactGenerators. They contain all the files defined by the
-- Sources they are nested into.
data ArtifactAssembly
-- | Generate a cloud-init compatible directory, ISO- or VFAT image,
-- as specified by the list of CloudInitTypes. Every item will use
-- the second argument to create an appropriate file name, e.g.
-- for the CI_ISO type the output is second_param.iso.
CloudInit :: [CloudInitType] -> FilePath -> ArtifactAssembly
-- | a set of VM-images that were created by executing a build script on
-- them.
VmImages :: [ImageTarget] -> VmScript -> ArtifactAssembly
-- | A symbolic representation of the targets assembled by assemble
-- from an ArtifactAssembly. There is a list of
-- ArtifactTargets because e.g. a single CloudInit can
-- produce up to three output files, a directory, an ISO image and a VFAT
-- image.
data AssembledArtifact
AssembledArtifact :: InstanceId -> [ArtifactTarget] -> AssembledArtifact
-- | The output of an ArtifactAssembly is either a set of generated
-- files, or it might be a directory that contains the artifacts sources.
data AssemblyOutput
AssemblyGeneratesOutputFiles :: [FilePath] -> AssemblyOutput
AssemblyCopiesSourcesToDirectory :: FilePath -> AssemblyOutput
-- | The variable containing the instance id. Deprecated
instanceIdKey :: String
-- | The variable containing the buildId that identifies each execution of
-- B9. For more info about variable substitution in source files see
-- StringTemplate
buildIdKey :: String
-- | The variable containing the date and time a build was started. For
-- more info about variable substitution in source files see
-- StringTemplate
buildDateKey :: String
-- | Return the files that the artifact assembly consist of.
getAssemblyOutput :: ArtifactAssembly -> [AssemblyOutput]
-- | Describe how input files for artifacts to build are obtained. The
-- general structure of each constructor is FromXXX
-- destination source
data ArtifactSource
-- | Copy a SourceFile potentially replacing variable defined in
-- Let-like parent elements.
FromFile :: FilePath -> SourceFile -> ArtifactSource
-- | Create a file from some Content
FromContent :: FilePath -> Content -> ArtifactSource
-- | Set the unix file permissions to all files generated by the
-- nested list of ArtifactSources.
SetPermissions :: Int -> Int -> Int -> [ArtifactSource] -> ArtifactSource
-- | Assume a local directory as starting point for all relative source
-- files in the nested ArtifactSources.
FromDirectory :: FilePath -> [ArtifactSource] -> ArtifactSource
-- | Specify an output directory for all the files generated by the nested
-- ArtifactSources
IntoDirectory :: FilePath -> [ArtifactSource] -> ArtifactSource
-- | Return all source files generated by an ArtifactSource.
getArtifactSourceFiles :: ArtifactSource -> [FilePath]
instance GHC.Generics.Generic B9.Artifact.Readable.AssemblyOutput
instance GHC.Classes.Eq B9.Artifact.Readable.AssemblyOutput
instance Data.Data.Data B9.Artifact.Readable.AssemblyOutput
instance GHC.Show.Show B9.Artifact.Readable.AssemblyOutput
instance GHC.Read.Read B9.Artifact.Readable.AssemblyOutput
instance GHC.Generics.Generic B9.Artifact.Readable.ArtifactGenerator
instance Data.Data.Data B9.Artifact.Readable.ArtifactGenerator
instance GHC.Classes.Eq B9.Artifact.Readable.ArtifactGenerator
instance GHC.Show.Show B9.Artifact.Readable.ArtifactGenerator
instance GHC.Read.Read B9.Artifact.Readable.ArtifactGenerator
instance GHC.Generics.Generic B9.Artifact.Readable.ArtifactAssembly
instance GHC.Classes.Eq B9.Artifact.Readable.ArtifactAssembly
instance Data.Data.Data B9.Artifact.Readable.ArtifactAssembly
instance GHC.Show.Show B9.Artifact.Readable.ArtifactAssembly
instance GHC.Read.Read B9.Artifact.Readable.ArtifactAssembly
instance GHC.Generics.Generic B9.Artifact.Readable.AssembledArtifact
instance GHC.Classes.Eq B9.Artifact.Readable.AssembledArtifact
instance Data.Data.Data B9.Artifact.Readable.AssembledArtifact
instance GHC.Show.Show B9.Artifact.Readable.AssembledArtifact
instance GHC.Read.Read B9.Artifact.Readable.AssembledArtifact
instance GHC.Generics.Generic B9.Artifact.Readable.ArtifactTarget
instance GHC.Classes.Eq B9.Artifact.Readable.ArtifactTarget
instance Data.Data.Data B9.Artifact.Readable.ArtifactTarget
instance GHC.Show.Show B9.Artifact.Readable.ArtifactTarget
instance GHC.Read.Read B9.Artifact.Readable.ArtifactTarget
instance GHC.Generics.Generic B9.Artifact.Readable.CloudInitType
instance GHC.Classes.Eq B9.Artifact.Readable.CloudInitType
instance Data.Data.Data B9.Artifact.Readable.CloudInitType
instance GHC.Show.Show B9.Artifact.Readable.CloudInitType
instance GHC.Read.Read B9.Artifact.Readable.CloudInitType
instance Data.Hashable.Class.Hashable B9.Artifact.Readable.InstanceId
instance Data.Binary.Class.Binary B9.Artifact.Readable.InstanceId
instance Control.DeepSeq.NFData B9.Artifact.Readable.InstanceId
instance GHC.Classes.Eq B9.Artifact.Readable.InstanceId
instance Data.Data.Data B9.Artifact.Readable.InstanceId
instance GHC.Show.Show B9.Artifact.Readable.InstanceId
instance GHC.Read.Read B9.Artifact.Readable.InstanceId
instance Control.DeepSeq.NFData B9.Artifact.Readable.ArtifactGenerator
instance GHC.Base.Semigroup B9.Artifact.Readable.ArtifactGenerator
instance GHC.Base.Monoid B9.Artifact.Readable.ArtifactGenerator
instance Test.QuickCheck.Arbitrary.Arbitrary B9.Artifact.Readable.ArtifactGenerator
instance Data.Hashable.Class.Hashable B9.Artifact.Readable.ArtifactAssembly
instance Data.Binary.Class.Binary B9.Artifact.Readable.ArtifactAssembly
instance Control.DeepSeq.NFData B9.Artifact.Readable.ArtifactAssembly
instance Test.QuickCheck.Arbitrary.Arbitrary B9.Artifact.Readable.ArtifactAssembly
instance Data.Hashable.Class.Hashable B9.Artifact.Readable.AssembledArtifact
instance Data.Binary.Class.Binary B9.Artifact.Readable.AssembledArtifact
instance Control.DeepSeq.NFData B9.Artifact.Readable.AssembledArtifact
instance Data.Hashable.Class.Hashable B9.Artifact.Readable.ArtifactTarget
instance Data.Binary.Class.Binary B9.Artifact.Readable.ArtifactTarget
instance Control.DeepSeq.NFData B9.Artifact.Readable.ArtifactTarget
instance Data.Hashable.Class.Hashable B9.Artifact.Readable.CloudInitType
instance Data.Binary.Class.Binary B9.Artifact.Readable.CloudInitType
instance Control.DeepSeq.NFData B9.Artifact.Readable.CloudInitType
instance Test.QuickCheck.Arbitrary.Arbitrary B9.Artifact.Readable.CloudInitType
instance Test.QuickCheck.Arbitrary.Arbitrary B9.Artifact.Readable.InstanceId
-- | Effectful functions to execute and build virtual machine images using
-- an execution environment like e.g. libvirt-lxc.
module B9.VmBuilder
buildWithVm :: IsB9 e => InstanceId -> [ImageTarget] -> FilePath -> VmScript -> Eff e Bool
-- | Mostly effectful functions to assemble artifacts.
module B9.Artifact.Readable.Interpreter
-- | Execute an ArtifactGenerator and return a B9Invocation
-- that returns the build id obtained by getBuildId.
buildArtifacts :: ArtifactGenerator -> B9 String
-- | Run an artifact generator to produce the artifacts.
assemble :: ArtifactGenerator -> B9 [AssembledArtifact]
-- | Return a list of relative paths for the local files to be
-- generated by the ArtifactGenerator. This excludes Shared and
-- Transient image targets.
getArtifactOutputFiles :: ArtifactGenerator -> Either SomeException [FilePath]
-- | Interpret an ArtifactGenerator into a list of simple commands,
-- i.e. InstanceGenerators
runArtifactGenerator :: Environment -> String -> String -> ArtifactGenerator -> Either SomeException [InstanceGenerator [TextFileWriter]]
-- | Create the ArtifactTarget from an ArtifactAssembly in
-- the directory instanceDir
runArtifactAssembly :: IsB9 e => InstanceId -> FilePath -> ArtifactAssembly -> Eff e [ArtifactTarget]
data InstanceGenerator e
IG :: InstanceId -> e -> ArtifactAssembly -> InstanceGenerator e
-- | Run an
runInstanceGenerator :: IsB9 e => InstanceGenerator FilePath -> Eff e AssembledArtifact
-- | Internal data structure. Only exposed for unit testing.
data InstanceSources
InstanceSources :: Environment -> [ArtifactSource] -> InstanceSources
[isEnv] :: InstanceSources -> Environment
[isSources] :: InstanceSources -> [ArtifactSource]
instance GHC.Classes.Eq B9.Artifact.Readable.Interpreter.TextFileWriter
instance GHC.Show.Show B9.Artifact.Readable.Interpreter.TextFileWriter
instance GHC.Classes.Eq B9.Artifact.Readable.Interpreter.FilePermissionAction
instance Data.Data.Data B9.Artifact.Readable.Interpreter.FilePermissionAction
instance GHC.Show.Show B9.Artifact.Readable.Interpreter.FilePermissionAction
instance GHC.Read.Read B9.Artifact.Readable.Interpreter.FilePermissionAction
instance GHC.Classes.Eq B9.Artifact.Readable.Interpreter.TextFileWriterInput
instance GHC.Show.Show B9.Artifact.Readable.Interpreter.TextFileWriterInput
instance GHC.Read.Read B9.Artifact.Readable.Interpreter.TextFileWriterInput
instance GHC.Classes.Eq e => GHC.Classes.Eq (B9.Artifact.Readable.Interpreter.InstanceGenerator e)
instance Data.Data.Data e => Data.Data.Data (B9.Artifact.Readable.Interpreter.InstanceGenerator e)
instance GHC.Show.Show e => GHC.Show.Show (B9.Artifact.Readable.Interpreter.InstanceGenerator e)
instance GHC.Read.Read e => GHC.Read.Read (B9.Artifact.Readable.Interpreter.InstanceGenerator e)
instance GHC.Classes.Eq B9.Artifact.Readable.Interpreter.InstanceSources
instance GHC.Show.Show B9.Artifact.Readable.Interpreter.InstanceSources
-- | B9 is a library and build tool with which one can create/convert
-- different types of VM images. Additionally installation steps - like
-- installing software - can be done in a LXC container, running on the
-- disk images.
--
-- B9 allows to create and convert virtual machine image files as well as
-- related ISO and VFAT disk images for e.g. cloud-init configuration
-- sources.
--
-- This module re-exports the modules needed to build a tool around the
-- library, e.g. see src/cli/Main.hs as an example.
--
-- B9.Artifact.Generator is the module containing the basic data
-- structure used to describe a B9 build.
module B9
-- | Return the cabal package version of the B9 library.
b9Version :: Version
-- | Return the cabal package version of the B9 library, formatted using
-- showVersion.
b9VersionString :: String
-- | Just print the b9VersionString
runShowVersion :: MonadIO m => m ()
-- | Execute the artifact generators defined in a list of text files. Read
-- the text files in the list and parse them as ArtifactGenerators
-- then mappend them and apply buildArtifacts to them.
runBuildArtifacts :: [FilePath] -> B9ConfigAction String
-- | Read all text files and parse them as ArtifactGenerators. Then
-- overwrite the files with their contents but _pretty printed_ (i.e.
-- formatted).
runFormatBuildFiles :: MonadIO m => [FilePath] -> m ()
-- | Upload a SharedImageName to the default remote repository.
-- Note: The remote repository is specified in the B9Config.
runPush :: SharedImageName -> B9ConfigAction ()
-- | Either pull a list of available SharedImageNames from the
-- remote repository if Nothing is passed as parameter, or pull
-- the latest version of the image from the remote repository. Note: The
-- remote repository is specified in the B9Config.
runPull :: Maybe SharedImageName -> B9ConfigAction ()
-- | Execute an interactive root shell in a running container from a
-- SharedImageName.
runRun :: SharedImageName -> [String] -> B9ConfigAction String
-- | Delete all obsolete versions of all SharedImageNames.
runGcLocalRepoCache :: B9ConfigAction ()
-- | Clear the shared image cache for a remote. Note: The remote repository
-- is specified in the B9Config.
runGcRemoteRepoCache :: B9ConfigAction ()
-- | Print a list of shared images cached locally or remotely, if a remote
-- repository was selected. Note: The remote repository is specified in
-- the B9Config.
runListSharedImages :: B9ConfigAction (Set SharedImage)
-- | Check the SSH settings for a remote repository and add it to the user
-- wide B9 configuration file.
runAddRepo :: RemoteRepo -> B9ConfigAction ()
-- | Find the most recent version of a SharedImageName in the local
-- image cache.
runLookupLocalSharedImage :: SharedImageName -> B9ConfigAction (Maybe SharedImageBuildId)
-- | Append two lists, i.e.,
--
-- -- [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] -- [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...] ---- -- If the first list is not finite, the result is the first list. (++) :: () => [a] -> [a] -> [a] infixr 5 ++ -- | filter, applied to a predicate and a list, returns the list of -- those elements that satisfy the predicate; i.e., -- --
-- filter p xs = [ x | x <- xs, p x] --filter :: () => (a -> Bool) -> [a] -> [a] -- | zip takes two lists and returns a list of corresponding pairs. -- --
-- zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')] ---- -- If one input list is short, excess elements of the longer list are -- discarded: -- --
-- zip [1] ['a', 'b'] = [(1, 'a')] -- zip [1, 2] ['a'] = [(1, 'a')] ---- -- zip is right-lazy: -- --
-- zip [] _|_ = [] -- zip _|_ [] = _|_ --zip :: () => [a] -> [b] -> [(a, b)] -- | map f xs is the list obtained by applying f -- to each element of xs, i.e., -- --
-- map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] -- map f [x1, x2, ...] == [f x1, f x2, ...] --map :: () => (a -> b) -> [a] -> [b] -- | Conditional failure of Alternative computations. Defined by -- --
-- guard True = pure () -- guard False = empty ---- --
-- >>> safeDiv 4 0 -- Nothing -- >>> safeDiv 4 2 -- Just 2 ---- -- A definition of safeDiv using guards, but not guard: -- --
-- safeDiv :: Int -> Int -> Maybe Int -- safeDiv x y | y /= 0 = Just (x `div` y) -- | otherwise = Nothing ---- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
-- safeDiv :: Int -> Int -> Maybe Int -- safeDiv x y = do -- guard (y /= 0) -- return (x `div` y) --guard :: Alternative f => Bool -> f () -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. -- --
-- atomically :: STM a -> IO a ---- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
-- atomically :: STM (IO b) -> IO (IO b) -- join :: IO (IO b) -> IO b ---- -- we can compose them as -- --
-- join . atomically :: STM (IO b) -> IO b ---- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following laws: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. (>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a -- | Fail with a message. This operation is not part of the mathematical -- definition of a monad, but is invoked on pattern-match failure in a -- do expression. -- -- As part of the MonadFail proposal (MFP), this function is moved to its -- own class MonadFail (see Control.Monad.Fail for more -- details). The definition here will be removed in a future release. fail :: Monad m => String -> m a infixl 1 >>= infixl 1 >> -- | The Functor class is used for types that can be mapped over. -- Instances of Functor should satisfy the following laws: -- --
-- fmap id == id -- fmap (f . g) == fmap f . fmap g ---- -- The instances of Functor for lists, Maybe and IO -- satisfy these laws. class Functor (f :: Type -> Type) fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. (<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | A functor with application, providing operations to -- --
-- (<*>) = liftA2 id ---- --
-- liftA2 f x y = f <$> x <*> y ---- -- Further, any definition must satisfy the following: -- --
pure id <*> -- v = v
pure (.) <*> u -- <*> v <*> w = u <*> (v -- <*> w)
pure f <*> -- pure x = pure (f x)
u <*> pure y = -- pure ($ y) <*> u
-- forall x y. p (q x y) = f x . g y ---- -- it follows from the above that -- --
-- liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v ---- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. (*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <*> infixl 4 *> infixl 4 <* -- | Right-associative fold of a structure. -- -- In the case of lists, foldr, when applied to a binary operator, -- a starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- --
-- foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) ---- -- Note that, since the head of the resulting expression is produced by -- an application of the operator to the first element of the list, -- foldr can produce a terminating expression from an infinite -- list. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldr f z = foldr f z . toList --foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. null :: Foldable t => t a -> Bool -- | Left-associative fold of a structure. -- -- In the case of lists, foldl, when applied to a binary operator, -- a starting value (typically the left-identity of the operator), and a -- list, reduces the list using the binary operator, from left to right: -- --
-- foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn ---- -- Note that to produce the outermost application of the operator the -- entire input list must be traversed. This means that foldl' -- will diverge if given an infinite list. -- -- Also note that if you want an efficient left-fold, you probably want -- to use foldl' instead of foldl. The reason for this is -- that latter does not force the "inner" results (e.g. z f -- x1 in the above example) before applying them to the operator -- (e.g. to (f x2)). This results in a thunk chain -- O(n) elements long, which then must be evaluated from the -- outside-in. -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl f z . toList --foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to weak head normal -- form before being applied, avoiding the collection of thunks that -- would otherwise occur. This is often what you want to strictly reduce -- a finite list to a single, monolithic result (e.g. length). -- -- For a general Foldable structure this should be semantically -- identical to, -- --
-- foldl f z = foldl' f z . toList --foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | A variant of foldl that has no base case, and thus may only be -- applied to non-empty structures. -- --
-- foldl1 f = foldl1 f . toList --foldl1 :: Foldable t => (a -> a -> a) -> t a -> a -- | The sum function computes the sum of the numbers of a -- structure. sum :: (Foldable t, Num a) => t a -> a -- | The product function computes the product of the numbers of a -- structure. product :: (Foldable t, Num a) => t a -> a -- | A variant of foldr that has no base case, and thus may only be -- applied to non-empty structures. -- --
-- foldr1 f = foldr1 f . toList --foldr1 :: Foldable t => (a -> a -> a) -> t a -> a -- | The largest element of a non-empty structure. maximum :: (Foldable t, Ord a) => t a -> a -- | The least element of a non-empty structure. minimum :: (Foldable t, Ord a) => t a -> a -- | Does the element occur in the structure? elem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `elem` -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | An associative operation. (<>) :: Semigroup a => a -> a -> a infixr 6 <> -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following laws: -- --
x <> mempty = x
mempty <> x = x
mconcat = foldr '(<>)' -- mempty
-- >>> unlines ["Hello", "World", "!"] -- "Hello\nWorld\n!\n" --unlines :: [String] -> String -- | lines breaks a string up into a list of strings at newline -- characters. The resulting strings do not contain newlines. -- -- Note that after splitting the string at newline characters, the last -- part of the string is considered a line even if it doesn't end with a -- newline. For example, -- --
-- >>> lines "" -- [] ---- --
-- >>> lines "\n" -- [""] ---- --
-- >>> lines "one" -- ["one"] ---- --
-- >>> lines "one\n" -- ["one"] ---- --
-- >>> lines "one\n\n" -- ["one",""] ---- --
-- >>> lines "one\ntwo" -- ["one","two"] ---- --
-- >>> lines "one\ntwo\n" -- ["one","two"] ---- -- Thus lines s contains at least as many elements as -- newlines in s. lines :: String -> [String] -- | The isInfixOf function takes two lists and returns True -- iff the first list is contained, wholly and intact, anywhere within -- the second. -- --
-- >>> isInfixOf "Haskell" "I really like Haskell." -- True ---- --
-- >>> isInfixOf "Ial" "I really like Haskell." -- False --isInfixOf :: Eq a => [a] -> [a] -> Bool -- | delete x removes the first occurrence of x -- from its list argument. For example, -- --
-- >>> delete 'a' "banana" -- "bnana" ---- -- It is a special case of deleteBy, which allows the programmer -- to supply their own equality test. delete :: Eq a => a -> [a] -> [a] -- | A Version represents the version of a software entity. -- -- An instance of Eq is provided, which implements exact equality -- modulo reordering of the tags in the versionTags field. -- -- An instance of Ord is also provided, which gives lexicographic -- ordering on the versionBranch fields (i.e. 2.1 > 2.0, 1.2.3 -- > 1.2.2, etc.). This is expected to be sufficient for many uses, -- but note that you may need to use a more specific ordering for your -- versioning scheme. For example, some versioning schemes may include -- pre-releases which have tags "pre1", "pre2", and so -- on, and these would need to be taken into account when determining -- ordering. In some cases, date ordering may be more appropriate, so the -- application would have to look for date tags in the -- versionTags field and compare those. The bottom line is, don't -- always assume that compare and other Ord operations are -- the right thing for every Version. -- -- Similarly, concrete representations of versions may differ. One -- possible concrete representation is provided (see showVersion -- and parseVersion), but depending on the application a different -- concrete representation may be more appropriate. data Version Version :: [Int] -> [String] -> Version -- | The numeric branch for this version. This reflects the fact that most -- software versions are tree-structured; there is a main trunk which is -- tagged with versions at various points (1,2,3...), and the first -- branch off the trunk after version 3 is 3.1, the second branch off the -- trunk after version 3 is 3.2, and so on. The tree can be branched -- arbitrarily, just by adding more digits. -- -- We represent the branch as a list of Int, so version 3.2.1 -- becomes [3,2,1]. Lexicographic ordering (i.e. the default instance of -- Ord for [Int]) gives the natural ordering of branches. [versionBranch] :: Version -> [Int] -- | A version can be tagged with an arbitrary list of strings. The -- interpretation of the list of tags is entirely dependent on the entity -- that this version applies to. [versionTags] :: Version -> [String] -- | Promote a function to a monad. liftM :: Monad m => (a1 -> r) -> m a1 -> m r -- | Executes a computation in a modified environment. local :: MonadReader r m => (r -> r) -> m a -> m a -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data ByteString -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
-- ($) :: (a -> b) -> a -> b -- (<$>) :: Functor f => (a -> b) -> f a -> f b ---- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --
-- >>> show <$> Nothing -- Nothing -- -- >>> show <$> Just 3 -- Just "3" ---- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
-- >>> show <$> Left 17 -- Left 17 -- -- >>> show <$> Right 17 -- Right "17" ---- -- Double each element of a list: -- --
-- >>> (*2) <$> [1,2,3] -- [2,4,6] ---- -- Apply even to the second element of a pair: -- --
-- >>> even <$> (2,2) -- (2,True) --(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | A space efficient, packed, unboxed Unicode text type. data Text -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | One or more. some :: Alternative f => f a -> f [a] -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | The identity of mplus. It should also satisfy the equations -- --
-- mzero >>= f = mzero -- v >> mzero = mzero ---- -- The default definition is -- --
-- mzero = empty --mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
-- mplus = (<|>) --mplus :: MonadPlus m => m a -> m a -> m a -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Computation exitWith code throws ExitCode -- code. Normally this terminates the program, returning -- code to the program's caller. -- -- On program termination, the standard Handles stdout and -- stderr are flushed automatically; any other buffered -- Handles need to be flushed manually, otherwise the buffered -- data will be discarded. -- -- A program that fails in any other way is treated as if it had called -- exitFailure. A program that terminates successfully without -- calling exitWith explicitly is treated as if it had called -- exitWith ExitSuccess. -- -- As an ExitCode is not an IOException, exitWith -- bypasses the error handling in the IO monad and cannot be -- intercepted by catch from the Prelude. However it is a -- SomeException, and can be caught using the functions of -- Control.Exception. This means that cleanup computations added -- with bracket (from Control.Exception) are also executed -- properly on exitWith. -- -- Note: in GHC, exitWith should be called from the main program -- thread in order to exit the process. When called from another thread, -- exitWith will throw an ExitException as normal, but -- the exception will not cause the process itself to exit. exitWith :: () => ExitCode -> IO a -- | Format a variable number of arguments with the C-style formatting -- string. -- --
-- >>> printf "%s, %d, %.4f" "hello" 123 pi -- hello, 123, 3.1416 ---- -- The return value is either String or (IO a) -- (which should be (IO '()'), but Haskell's type system -- makes this hard). -- -- The format string consists of ordinary characters and conversion -- specifications, which specify how to format one of the arguments -- to printf in the output string. A format specification is -- introduced by the % character; this character can be -- self-escaped into the format string using %%. A format -- specification ends with a /format character/ that provides the primary -- information about how to format the value. The rest of the conversion -- specification is optional. In order, one may have flag characters, a -- width specifier, a precision specifier, and type-specific modifier -- characters. -- -- Unlike C printf(3), the formatting of this printf is -- driven by the argument type; formatting is type specific. The types -- formatted by printf "out of the box" are: -- -- -- -- printf is also extensible to support other types: see below. -- -- A conversion specification begins with the character %, -- followed by zero or more of the following flags: -- --
-- - left adjust (default is right adjust) -- + always use a sign (+ or -) for signed conversions -- space leading space for positive numbers in signed conversions -- 0 pad with zeros rather than spaces -- # use an \"alternate form\": see below ---- -- When both flags are given, - overrides 0 and -- + overrides space. A negative width specifier in a * -- conversion is treated as positive but implies the left adjust flag. -- -- The "alternate form" for unsigned radix conversions is as in C -- printf(3): -- --
-- %o prefix with a leading 0 if needed -- %x prefix with a leading 0x if nonzero -- %X prefix with a leading 0X if nonzero -- %b prefix with a leading 0b if nonzero -- %[eEfFgG] ensure that the number contains a decimal point ---- -- Any flags are followed optionally by a field width: -- --
-- num field width -- * as num, but taken from argument list ---- -- The field width is a minimum, not a maximum: it will be expanded as -- needed to avoid mutilating a value. -- -- Any field width is followed optionally by a precision: -- --
-- .num precision -- . same as .0 -- .* as num, but taken from argument list ---- -- Negative precision is taken as 0. The meaning of the precision depends -- on the conversion type. -- --
-- Integral minimum number of digits to show -- RealFloat number of digits after the decimal point -- String maximum number of characters ---- -- The precision for Integral types is accomplished by zero-padding. If -- both precision and zero-pad are given for an Integral field, the -- zero-pad is ignored. -- -- Any precision is followed optionally for Integral types by a width -- modifier; the only use of this modifier being to set the implicit size -- of the operand for conversion of a negative operand to unsigned: -- --
-- hh Int8 -- h Int16 -- l Int32 -- ll Int64 -- L Int64 ---- -- The specification ends with a format character: -- --
-- c character Integral -- d decimal Integral -- o octal Integral -- x hexadecimal Integral -- X hexadecimal Integral -- b binary Integral -- u unsigned decimal Integral -- f floating point RealFloat -- F floating point RealFloat -- g general format float RealFloat -- G general format float RealFloat -- e exponent format float RealFloat -- E exponent format float RealFloat -- s string String -- v default format any type ---- -- The "%v" specifier is provided for all built-in types, and should be -- provided for user-defined type formatters as well. It picks a "best" -- representation for the given type. For the built-in types the "%v" -- specifier is converted as follows: -- --
-- c Char -- u other unsigned Integral -- d other signed Integral -- g RealFloat -- s String ---- -- Mismatch between the argument types and the format string, as well as -- any other syntactic or semantic errors in the format string, will -- cause an exception to be thrown at runtime. -- -- Note that the formatting for RealFloat types is currently a bit -- different from that of C printf(3), conforming instead to -- showEFloat, showFFloat and showGFloat (and their -- alternate versions showFFloatAlt and showGFloatAlt). -- This is hard to fix: the fixed versions would format in a -- backward-incompatible way. In any case the Haskell behavior is -- generally more sensible than the C behavior. A brief summary of some -- key differences: -- --
-- filter = ( mfilter :: (a -> Bool) -> [a] -> [a] ) ---- -- An example using mfilter with the Maybe monad: -- --
-- >>> mfilter odd (Just 1) -- Just 1 -- >>> mfilter odd (Just 2) -- Nothing --mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | Strict version of <$>. (<$!>) :: Monad m => (a -> b) -> m a -> m b infixl 4 <$!> -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | replicateM n act performs the action n times, -- gathering the results. replicateM :: Applicative m => Int -> m a -> m [a] -- | Like foldM, but discards the result. foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () -- | The foldM function is analogous to foldl, except that -- its result is encapsulated in a monad. Note that foldM works -- from left-to-right over the list arguments. This could be an issue -- where (>>) and the `folded function' are not -- commutative. -- --
-- foldM f a1 [x1, x2, ..., xm] -- -- == -- -- do -- a2 <- f a1 x1 -- a3 <- f a2 x2 -- ... -- f am xm ---- -- If right-to-left evaluation is required, the input list should be -- reversed. -- -- Note: foldM is the same as foldlM foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b -- | zipWithM_ is the extension of zipWithM which ignores the -- final result. zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () -- | The zipWithM function generalizes zipWith to arbitrary -- applicative functors. zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] -- | The mapAndUnzipM function maps its first argument over a list, -- returning the result as a pair of lists. This function is mainly used -- with complicated data structures or a state-transforming monad. mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) -- | Repeat an action indefinitely. -- --
-- echoServer :: Socket -> IO () -- echoServer socket = forever $ do -- client <- accept socket -- forkFinally (echo client) (\_ -> hClose client) -- where -- echo :: Handle -> IO () -- echo client = forever $ -- hGetLine client >>= hPutStrLn client --forever :: Applicative f => f a -> f b -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
-- (.) :: (b -> c) -> (a -> b) -> a -> c -- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c --(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Left-to-right composition of Kleisli arrows. (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | This generalizes the list-based filter function. filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] -- | Construct tag-less Version makeVersion :: [Int] -> Version -- | A parser for versions in the format produced by showVersion. parseVersion :: ReadP Version -- | Provides one possible concrete representation for Version. For -- a version with versionBranch = [1,2,3] and -- versionTags = ["tag1","tag2"], the output will be -- 1.2.3-tag1-tag2. showVersion :: Version -> String -- | The isSubsequenceOf function takes two lists and returns -- True if all the elements of the first list occur, in order, in -- the second. The elements do not have to occur consecutively. -- -- isSubsequenceOf x y is equivalent to elem x -- (subsequences y). -- --
-- >>> isSubsequenceOf "GHC" "The Glorious Haskell Compiler" -- True -- -- >>> isSubsequenceOf ['a','d'..'z'] ['a'..'z'] -- True -- -- >>> isSubsequenceOf [1..10] [10,9..0] -- False --isSubsequenceOf :: Eq a => [a] -> [a] -> Bool -- | The mapAccumR function behaves like a combination of -- fmap and foldr; it applies a function to each element -- of a structure, passing an accumulating parameter from right to left, -- and returning a final value of this accumulator together with the new -- structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | The mapAccumL function behaves like a combination of -- fmap and foldl; it applies a function to each element -- of a structure, passing an accumulating parameter from left to right, -- and returning a final value of this accumulator together with the new -- structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | One or none. optional :: Alternative f => f a -> f (Maybe a) newtype WrappedMonad (m :: Type -> Type) a WrapMonad :: m a -> WrappedMonad a [unwrapMonad] :: WrappedMonad a -> m a newtype WrappedArrow (a :: Type -> Type -> Type) b c WrapArrow :: a b c -> WrappedArrow b c [unwrapArrow] :: WrappedArrow b c -> a b c -- | Lists, but with an Applicative functor based on zipping. newtype ZipList a ZipList :: [a] -> ZipList a [getZipList] :: ZipList a -> [a] -- | Defines the exit codes that a program can return. data ExitCode -- | indicates successful termination; ExitSuccess :: ExitCode -- | indicates program failure with an exit code. The exact interpretation -- of the code is operating-system dependent. In particular, some values -- may be prohibited (e.g. 0 on a POSIX-compliant system). ExitFailure :: Int -> ExitCode -- | The Const functor. newtype Const a (b :: k) :: forall k. () => Type -> k -> Type Const :: a -> Const a [getConst] :: Const a -> a -- | The find function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- Nothing if there is no such element. find :: Foldable t => (a -> Bool) -> t a -> Maybe a -- | notElem is the negation of elem. notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 `notElem` -- | The least element of a non-empty structure with respect to the given -- comparison function. minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | The largest element of a non-empty structure with respect to the given -- comparison function. maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a -- | Determines whether all elements of the structure satisfy the -- predicate. all :: Foldable t => (a -> Bool) -> t a -> Bool -- | Determines whether any element of the structure satisfies the -- predicate. any :: Foldable t => (a -> Bool) -> t a -> Bool -- | or returns the disjunction of a container of Bools. For the -- result to be False, the container must be finite; True, -- however, results from a True value finitely far from the left -- end. or :: Foldable t => t Bool -> Bool -- | and returns the conjunction of a container of Bools. For the -- result to be True, the container must be finite; False, -- however, results from a False value finitely far from the left -- end. and :: Foldable t => t Bool -> Bool -- | Map a function over all the elements of a container and concatenate -- the resulting lists. concatMap :: Foldable t => (a -> [b]) -> t a -> [b] -- | The concatenation of all the elements of a container of lists. concat :: Foldable t => t [a] -> [a] -- | The sum of a collection of actions, generalizing concat. As of -- base 4.8.0.0, msum is just asum, specialized to -- MonadPlus. msum :: (Foldable t, MonadPlus m) => t (m a) -> m a -- | Evaluate each monadic action in the structure from left to right, and -- ignore the results. For a version that doesn't ignore the results see -- sequence. -- -- As of base 4.8.0.0, sequence_ is just sequenceA_, -- specialized to Monad. sequence_ :: (Foldable t, Monad m) => t (m a) -> m () -- | forM_ is mapM_ with its arguments flipped. For a version -- that doesn't ignore the results see forM. -- -- As of base 4.8.0.0, forM_ is just for_, specialized to -- Monad. forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m () -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and ignore the results. For a version that -- doesn't ignore the results see mapM. -- -- As of base 4.8.0.0, mapM_ is just traverse_, specialized -- to Monad. mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () -- | Maybe monoid returning the leftmost non-Nothing value. -- -- First a is isomorphic to Alt Maybe -- a, but precedes it historically. -- --
-- >>> getFirst (First (Just "hello") <> First Nothing <> First (Just "world")) -- Just "hello" ---- -- Use of this type is discouraged. Note the following equivalence: -- --
-- Data.Monoid.First x === Maybe (Data.Semigroup.First x) ---- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype First a First :: Maybe a -> First a [getFirst] :: First a -> Maybe a -- | Maybe monoid returning the rightmost non-Nothing value. -- -- Last a is isomorphic to Dual (First -- a), and thus to Dual (Alt Maybe a) -- --
-- >>> getLast (Last (Just "hello") <> Last Nothing <> Last (Just "world")) -- Just "world" ---- -- Use of this type is discouraged. Note the following equivalence: -- --
-- Data.Monoid.Last x === Maybe (Data.Semigroup.Last x) ---- -- In addition to being equivalent in the structural sense, the two also -- have Monoid instances that behave the same. This type will be -- marked deprecated in GHC 8.8, and removed in GHC 8.10. Users are -- advised to use the variant from Data.Semigroup and wrap it in -- Maybe. newtype Last a Last :: Maybe a -> Last a [getLast] :: Last a -> Maybe a -- | This data type witnesses the lifting of a Monoid into an -- Applicative pointwise. newtype Ap (f :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type Ap :: f a -> Ap [getAp] :: Ap -> f a -- | The dual of a Monoid, obtained by swapping the arguments of -- mappend. -- --
-- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" --newtype Dual a Dual :: a -> Dual a [getDual] :: Dual a -> a -- | The monoid of endomorphisms under composition. -- --
-- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
--
-- >>> appEndo computation "Haskell"
-- "Hello, Haskell!"
--
newtype Endo a
Endo :: (a -> a) -> Endo a
[appEndo] :: Endo a -> a -> a
-- | Boolean monoid under conjunction (&&).
--
-- -- >>> getAll (All True <> mempty <> All False) -- False ---- --
-- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False --newtype All All :: Bool -> All [getAll] :: All -> Bool -- | Boolean monoid under disjunction (||). -- --
-- >>> getAny (Any True <> mempty <> Any False) -- True ---- --
-- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True --newtype Any Any :: Bool -> Any [getAny] :: Any -> Bool -- | Monoid under addition. -- --
-- >>> getSum (Sum 1 <> Sum 2 <> mempty) -- 3 --newtype Sum a Sum :: a -> Sum a [getSum] :: Sum a -> a -- | Monoid under multiplication. -- --
-- >>> getProduct (Product 3 <> Product 4 <> mempty) -- 12 --newtype Product a Product :: a -> Product a [getProduct] :: Product a -> a -- | Monoid under <|>. newtype Alt (f :: k -> Type) (a :: k) :: forall k. () => k -> Type -> k -> Type Alt :: f a -> Alt [getAlt] :: Alt -> f a -- | unwords is an inverse operation to words. It joins words -- with separating spaces. -- --
-- >>> unwords ["Lorem", "ipsum", "dolor"] -- "Lorem ipsum dolor" --unwords :: [String] -> String -- | words breaks a string up into a list of words, which were -- delimited by white space. -- --
-- >>> words "Lorem ipsum\ndolor" -- ["Lorem","ipsum","dolor"] --words :: String -> [String] -- | The unfoldr function is a `dual' to foldr: while -- foldr reduces a list to a summary value, unfoldr builds -- a list from a seed value. The function takes the element and returns -- Nothing if it is done producing the list or returns Just -- (a,b), in which case, a is a prepended to the list -- and b is used as the next element in a recursive call. For -- example, -- --
-- iterate f == unfoldr (\x -> Just (x, f x)) ---- -- In some cases, unfoldr can undo a foldr operation: -- --
-- unfoldr f' (foldr f z xs) == xs ---- -- if the following holds: -- --
-- f' (f x y) = Just (x,y) -- f' z = Nothing ---- -- A simple use of unfoldr: -- --
-- >>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 -- [10,9,8,7,6,5,4,3,2,1] --unfoldr :: () => (b -> Maybe (a, b)) -> b -> [a] -- | Sort a list by comparing the results of a key function applied to each -- element. sortOn f is equivalent to sortBy (comparing -- f), but has the performance advantage of only evaluating -- f once for each element in the input list. This is called the -- decorate-sort-undecorate paradigm, or Schwartzian transform. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
-- >>> sortOn fst [(2, "world"), (4, "!"), (1, "Hello")] -- [(1,"Hello"),(2,"world"),(4,"!")] --sortOn :: Ord b => (a -> b) -> [a] -> [a] -- | The sortBy function is the non-overloaded version of -- sort. -- --
-- >>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")] -- [(1,"Hello"),(2,"world"),(4,"!")] --sortBy :: () => (a -> a -> Ordering) -> [a] -> [a] -- | The sort function implements a stable sorting algorithm. It is -- a special case of sortBy, which allows the programmer to supply -- their own comparison function. -- -- Elements are arranged from from lowest to highest, keeping duplicates -- in the order they appeared in the input. -- --
-- >>> sort [1,6,4,3,2,5] -- [1,2,3,4,5,6] --sort :: Ord a => [a] -> [a] -- | The permutations function returns the list of all permutations -- of the argument. -- --
-- >>> permutations "abc" -- ["abc","bac","cba","bca","cab","acb"] --permutations :: () => [a] -> [[a]] -- | The subsequences function returns the list of all subsequences -- of the argument. -- --
-- >>> subsequences "abc" -- ["","a","b","ab","c","ac","bc","abc"] --subsequences :: () => [a] -> [[a]] -- | The tails function returns all final segments of the argument, -- longest first. For example, -- --
-- >>> tails "abc" -- ["abc","bc","c",""] ---- -- Note that tails has the following strictness property: -- tails _|_ = _|_ : _|_ tails :: () => [a] -> [[a]] -- | The inits function returns all initial segments of the -- argument, shortest first. For example, -- --
-- >>> inits "abc" -- ["","a","ab","abc"] ---- -- Note that inits has the following strictness property: -- inits (xs ++ _|_) = inits xs ++ _|_ -- -- In particular, inits _|_ = [] : _|_ inits :: () => [a] -> [[a]] -- | The groupBy function is the non-overloaded version of -- group. groupBy :: () => (a -> a -> Bool) -> [a] -> [[a]] -- | The group function takes a list and returns a list of lists -- such that the concatenation of the result is equal to the argument. -- Moreover, each sublist in the result contains only equal elements. For -- example, -- --
-- >>> group "Mississippi" -- ["M","i","ss","i","ss","i","pp","i"] ---- -- It is a special case of groupBy, which allows the programmer to -- supply their own equality test. group :: Eq a => [a] -> [[a]] -- | The deleteFirstsBy function takes a predicate and two lists and -- returns the first list with the first occurrence of each element of -- the second list removed. deleteFirstsBy :: () => (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The unzip7 function takes a list of seven-tuples and returns -- seven lists, analogous to unzip. unzip7 :: () => [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g]) -- | The unzip6 function takes a list of six-tuples and returns six -- lists, analogous to unzip. unzip6 :: () => [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) -- | The unzip5 function takes a list of five-tuples and returns -- five lists, analogous to unzip. unzip5 :: () => [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e]) -- | The unzip4 function takes a list of quadruples and returns four -- lists, analogous to unzip. unzip4 :: () => [(a, b, c, d)] -> ([a], [b], [c], [d]) -- | The zipWith7 function takes a function which combines seven -- elements, as well as seven lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith7 :: () => (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] -- | The zipWith6 function takes a function which combines six -- elements, as well as six lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith6 :: () => (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -- | The zipWith5 function takes a function which combines five -- elements, as well as five lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith5 :: () => (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -- | The zipWith4 function takes a function which combines four -- elements, as well as four lists and returns a list of their point-wise -- combination, analogous to zipWith. zipWith4 :: () => (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e] -- | The zip7 function takes seven lists and returns a list of -- seven-tuples, analogous to zip. zip7 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)] -- | The zip6 function takes six lists and returns a list of -- six-tuples, analogous to zip. zip6 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)] -- | The zip5 function takes five lists and returns a list of -- five-tuples, analogous to zip. zip5 :: () => [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)] -- | The zip4 function takes four lists and returns a list of -- quadruples, analogous to zip. zip4 :: () => [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)] -- | The genericReplicate function is an overloaded version of -- replicate, which accepts any Integral value as the -- number of repetitions to make. genericReplicate :: Integral i => i -> a -> [a] -- | The genericIndex function is an overloaded version of -- !!, which accepts any Integral value as the index. genericIndex :: Integral i => [a] -> i -> a -- | The genericSplitAt function is an overloaded version of -- splitAt, which accepts any Integral value as the -- position at which to split. genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) -- | The genericDrop function is an overloaded version of -- drop, which accepts any Integral value as the number of -- elements to drop. genericDrop :: Integral i => i -> [a] -> [a] -- | The genericTake function is an overloaded version of -- take, which accepts any Integral value as the number of -- elements to take. genericTake :: Integral i => i -> [a] -> [a] -- | The genericLength function is an overloaded version of -- length. In particular, instead of returning an Int, it -- returns any type which is an instance of Num. It is, however, -- less efficient than length. genericLength :: Num i => [a] -> i -- | The non-overloaded version of insert. insertBy :: () => (a -> a -> Ordering) -> a -> [a] -> [a] -- | The insert function takes an element and a list and inserts the -- element into the list at the first position where it is less than or -- equal to the next element. In particular, if the list is sorted before -- the call, the result will also be sorted. It is a special case of -- insertBy, which allows the programmer to supply their own -- comparison function. -- --
-- >>> insert 4 [1,2,3,5,6,7] -- [1,2,3,4,5,6,7] --insert :: Ord a => a -> [a] -> [a] -- | The partition function takes a predicate a list and returns the -- pair of lists of elements which do and do not satisfy the predicate, -- respectively; i.e., -- --
-- partition p xs == (filter p xs, filter (not . p) xs) ---- --
-- >>> partition (`elem` "aeiou") "Hello World!"
-- ("eoo","Hll Wrld!")
--
partition :: () => (a -> Bool) -> [a] -> ([a], [a])
-- | The transpose function transposes the rows and columns of its
-- argument. For example,
--
-- -- >>> transpose [[1,2,3],[4,5,6]] -- [[1,4],[2,5],[3,6]] ---- -- If some of the rows are shorter than the following rows, their -- elements are skipped: -- --
-- >>> transpose [[10,11],[20],[],[30,31,32]] -- [[10,20,30],[11,31],[32]] --transpose :: () => [[a]] -> [[a]] -- | intercalate xs xss is equivalent to (concat -- (intersperse xs xss)). It inserts the list xs in -- between the lists in xss and concatenates the result. -- --
-- >>> intercalate ", " ["Lorem", "ipsum", "dolor"] -- "Lorem, ipsum, dolor" --intercalate :: () => [a] -> [[a]] -> [a] -- | The intersperse function takes an element and a list and -- `intersperses' that element between the elements of the list. For -- example, -- --
-- >>> intersperse ',' "abcde" -- "a,b,c,d,e" --intersperse :: () => a -> [a] -> [a] -- | The intersectBy function is the non-overloaded version of -- intersect. intersectBy :: () => (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The intersect function takes the list intersection of two -- lists. For example, -- --
-- >>> [1,2,3,4] `intersect` [2,4,6,8] -- [2,4] ---- -- If the first list contains duplicates, so will the result. -- --
-- >>> [1,2,2,3,4] `intersect` [6,4,4,2] -- [2,2,4] ---- -- It is a special case of intersectBy, which allows the -- programmer to supply their own equality test. If the element is found -- in both the first and the second list, the element from the first list -- will be used. intersect :: Eq a => [a] -> [a] -> [a] -- | The unionBy function is the non-overloaded version of -- union. unionBy :: () => (a -> a -> Bool) -> [a] -> [a] -> [a] -- | The union function returns the list union of the two lists. For -- example, -- --
-- >>> "dog" `union` "cow" -- "dogcw" ---- -- Duplicates, and elements of the first list, are removed from the the -- second list, but if the first list contains duplicates, so will the -- result. It is a special case of unionBy, which allows the -- programmer to supply their own equality test. union :: Eq a => [a] -> [a] -> [a] -- | The \\ function is list difference (non-associative). In the -- result of xs \\ ys, the first occurrence of -- each element of ys in turn (if any) has been removed from -- xs. Thus -- --
-- (xs ++ ys) \\ xs == ys. ---- --
-- >>> "Hello World!" \\ "ell W" -- "Hoorld!" ---- -- It is a special case of deleteFirstsBy, which allows the -- programmer to supply their own equality test. (\\) :: Eq a => [a] -> [a] -> [a] infix 5 \\ -- | The deleteBy function behaves like delete, but takes a -- user-supplied equality predicate. -- --
-- >>> deleteBy (<=) 4 [1..10] -- [1,2,3,5,6,7,8,9,10] --deleteBy :: () => (a -> a -> Bool) -> a -> [a] -> [a] -- | The nubBy function behaves just like nub, except it uses -- a user-supplied equality predicate instead of the overloaded == -- function. -- --
-- >>> nubBy (\x y -> mod x 3 == mod y 3) [1,2,4,5,6] -- [1,2,6] --nubBy :: () => (a -> a -> Bool) -> [a] -> [a] -- | O(n^2). The nub function removes duplicate elements from -- a list. In particular, it keeps only the first occurrence of each -- element. (The name nub means `essence'.) It is a special case -- of nubBy, which allows the programmer to supply their own -- equality test. -- --
-- >>> nub [1,2,3,4,3,2,1,2,4,3,5] -- [1,2,3,4,5] --nub :: Eq a => [a] -> [a] -- | The isSuffixOf function takes two lists and returns True -- iff the first list is a suffix of the second. The second list must be -- finite. -- --
-- >>> "ld!" `isSuffixOf` "Hello World!" -- True ---- --
-- >>> "World" `isSuffixOf` "Hello World!" -- False --isSuffixOf :: Eq a => [a] -> [a] -> Bool -- | The isPrefixOf function takes two lists and returns True -- iff the first list is a prefix of the second. -- --
-- >>> "Hello" `isPrefixOf` "Hello World!" -- True ---- --
-- >>> "Hello" `isPrefixOf` "Wello Horld!" -- False --isPrefixOf :: Eq a => [a] -> [a] -> Bool -- | The findIndices function extends findIndex, by returning -- the indices of all elements satisfying the predicate, in ascending -- order. -- --
-- >>> findIndices (`elem` "aeiou") "Hello World!" -- [1,4,7] --findIndices :: () => (a -> Bool) -> [a] -> [Int] -- | The findIndex function takes a predicate and a list and returns -- the index of the first element in the list satisfying the predicate, -- or Nothing if there is no such element. -- --
-- >>> findIndex isSpace "Hello World!" -- Just 5 --findIndex :: () => (a -> Bool) -> [a] -> Maybe Int -- | The elemIndices function extends elemIndex, by returning -- the indices of all elements equal to the query element, in ascending -- order. -- --
-- >>> elemIndices 'o' "Hello World" -- [4,7] --elemIndices :: Eq a => a -> [a] -> [Int] -- | The elemIndex function returns the index of the first element -- in the given list which is equal (by ==) to the query element, -- or Nothing if there is no such element. -- --
-- >>> elemIndex 4 [0..] -- Just 4 --elemIndex :: Eq a => a -> [a] -> Maybe Int -- | The stripPrefix function drops the given prefix from a list. It -- returns Nothing if the list did not start with the prefix -- given, or Just the list after the prefix, if it does. -- --
-- >>> stripPrefix "foo" "foobar" -- Just "bar" ---- --
-- >>> stripPrefix "foo" "foo" -- Just "" ---- --
-- >>> stripPrefix "foo" "barfoo" -- Nothing ---- --
-- >>> stripPrefix "foo" "barfoobaz" -- Nothing --stripPrefix :: Eq a => [a] -> [a] -> Maybe [a] -- | The dropWhileEnd function drops the largest suffix of a list in -- which the given predicate holds for all elements. For example: -- --
-- >>> dropWhileEnd isSpace "foo\n" -- "foo" ---- --
-- >>> dropWhileEnd isSpace "foo bar" -- "foo bar" ---- --
-- dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
--
dropWhileEnd :: () => (a -> Bool) -> [a] -> [a]
-- | & is a reverse application operator. This provides
-- notational convenience. Its precedence is one higher than that of the
-- forward application operator $, which allows & to be
-- nested in $.
--
-- -- >>> 5 & (+1) & show -- "6" --(&) :: () => a -> (a -> b) -> b infixl 1 & -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --
-- >>> void Nothing -- Nothing -- -- >>> void (Just 3) -- Just () ---- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int '()': -- --
-- >>> void (Left 8675309) -- Left 8675309 -- -- >>> void (Right 8675309) -- Right () ---- -- Replace every element of a list with unit: -- --
-- >>> void [1,2,3] -- [(),(),()] ---- -- Replace the second element of a pair with unit: -- --
-- >>> void (1,2) -- (1,()) ---- -- Discard the result of an IO action: -- --
-- >>> mapM print [1,2] -- 1 -- 2 -- [(),()] -- -- >>> void $ mapM print [1,2] -- 1 -- 2 --void :: Functor f => f a -> f () -- | The unzip3 function takes a list of triples and returns three -- lists, analogous to unzip. unzip3 :: () => [(a, b, c)] -> ([a], [b], [c]) -- | unzip transforms a list of pairs into a list of first -- components and a list of second components. unzip :: () => [(a, b)] -> ([a], [b]) -- | The zipWith3 function takes a function which combines three -- elements, as well as three lists and returns a list of their -- point-wise combination, analogous to zipWith. zipWith3 :: () => (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] -- | zipWith generalises zip by zipping with the function -- given as the first argument, instead of a tupling function. For -- example, zipWith (+) is applied to two lists to -- produce the list of corresponding sums. -- -- zipWith is right-lazy: -- --
-- zipWith f [] _|_ = [] --zipWith :: () => (a -> b -> c) -> [a] -> [b] -> [c] -- | zip3 takes three lists and returns a list of triples, analogous -- to zip. zip3 :: () => [a] -> [b] -> [c] -> [(a, b, c)] -- | List index (subscript) operator, starting from 0. It is an instance of -- the more general genericIndex, which takes an index of any -- integral type. (!!) :: () => [a] -> Int -> a infixl 9 !! -- | lookup key assocs looks up a key in an association -- list. lookup :: Eq a => a -> [(a, b)] -> Maybe b -- | reverse xs returns the elements of xs in -- reverse order. xs must be finite. reverse :: () => [a] -> [a] -- | break, applied to a predicate p and a list -- xs, returns a tuple where first element is longest prefix -- (possibly empty) of xs of elements that do not satisfy -- p and second element is the remainder of the list: -- --
-- break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4]) -- break (< 9) [1,2,3] == ([],[1,2,3]) -- break (> 9) [1,2,3] == ([1,2,3],[]) ---- -- break p is equivalent to span (not . -- p). break :: () => (a -> Bool) -> [a] -> ([a], [a]) -- | span, applied to a predicate p and a list xs, -- returns a tuple where first element is longest prefix (possibly empty) -- of xs of elements that satisfy p and second element -- is the remainder of the list: -- --
-- span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4]) -- span (< 9) [1,2,3] == ([1,2,3],[]) -- span (< 0) [1,2,3] == ([],[1,2,3]) ---- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) span :: () => (a -> Bool) -> [a] -> ([a], [a]) -- | splitAt n xs returns a tuple where first element is -- xs prefix of length n and second element is the -- remainder of the list: -- --
-- splitAt 6 "Hello World!" == ("Hello ","World!")
-- splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
-- splitAt 1 [1,2,3] == ([1],[2,3])
-- splitAt 3 [1,2,3] == ([1,2,3],[])
-- splitAt 4 [1,2,3] == ([1,2,3],[])
-- splitAt 0 [1,2,3] == ([],[1,2,3])
-- splitAt (-1) [1,2,3] == ([],[1,2,3])
--
--
-- It is equivalent to (take n xs, drop n xs) when
-- n is not _|_ (splitAt _|_ xs = _|_).
-- splitAt is an instance of the more general
-- genericSplitAt, in which n may be of any integral
-- type.
splitAt :: () => Int -> [a] -> ([a], [a])
-- | drop n xs returns the suffix of xs after the
-- first n elements, or [] if n > length
-- xs:
--
-- -- drop 6 "Hello World!" == "World!" -- drop 3 [1,2,3,4,5] == [4,5] -- drop 3 [1,2] == [] -- drop 3 [] == [] -- drop (-1) [1,2] == [1,2] -- drop 0 [1,2] == [1,2] ---- -- It is an instance of the more general genericDrop, in which -- n may be of any integral type. drop :: () => Int -> [a] -> [a] -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
-- take 5 "Hello World!" == "Hello" -- take 3 [1,2,3,4,5] == [1,2,3] -- take 3 [1,2] == [1,2] -- take 3 [] == [] -- take (-1) [1,2] == [] -- take 0 [1,2] == [] ---- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: () => Int -> [a] -> [a] -- | dropWhile p xs returns the suffix remaining after -- takeWhile p xs: -- --
-- dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3] -- dropWhile (< 9) [1,2,3] == [] -- dropWhile (< 0) [1,2,3] == [1,2,3] --dropWhile :: () => (a -> Bool) -> [a] -> [a] -- | takeWhile, applied to a predicate p and a list -- xs, returns the longest prefix (possibly empty) of -- xs of elements that satisfy p: -- --
-- takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2] -- takeWhile (< 9) [1,2,3] == [1,2,3] -- takeWhile (< 0) [1,2,3] == [] --takeWhile :: () => (a -> Bool) -> [a] -> [a] -- | cycle ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity on -- infinite lists. cycle :: () => [a] -> [a] -- | replicate n x is a list of length n with -- x the value of every element. It is an instance of the more -- general genericReplicate, in which n may be of any -- integral type. replicate :: () => Int -> a -> [a] -- | repeat x is an infinite list, with x the -- value of every element. repeat :: () => a -> [a] -- | 'iterate\'' is the strict version of iterate. -- -- It ensures that the result of each application of force to weak head -- normal form before proceeding. iterate' :: () => (a -> a) -> a -> [a] -- | iterate f x returns an infinite list of repeated -- applications of f to x: -- --
-- iterate f x == [x, f x, f (f x), ...] ---- -- Note that iterate is lazy, potentially leading to thunk -- build-up if the consumer doesn't force each iterate. See 'iterate\'' -- for a strict variant of this function. iterate :: () => (a -> a) -> a -> [a] -- | scanr1 is a variant of scanr that has no starting value -- argument. scanr1 :: () => (a -> a -> a) -> [a] -> [a] -- | scanr is the right-to-left dual of scanl. Note that -- --
-- head (scanr f z xs) == foldr f z xs. --scanr :: () => (a -> b -> b) -> b -> [a] -> [b] -- | A strictly accumulating version of scanl scanl' :: () => (b -> a -> b) -> b -> [a] -> [b] -- | scanl1 is a variant of scanl that has no starting value -- argument: -- --
-- scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] --scanl1 :: () => (a -> a -> a) -> [a] -> [a] -- | scanl is similar to foldl, but returns a list of -- successive reduced values from the left: -- --
-- scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] ---- -- Note that -- --
-- last (scanl f z xs) == foldl f z xs. --scanl :: () => (b -> a -> b) -> b -> [a] -> [b] -- | A strict version of foldl1 foldl1' :: () => (a -> a -> a) -> [a] -> a -- | Return all the elements of a list except the last one. The list must -- be non-empty. init :: () => [a] -> [a] -- | Extract the last element of a list, which must be finite and -- non-empty. last :: () => [a] -> a -- | Extract the elements after the head of a list, which must be -- non-empty. tail :: () => [a] -> [a] -- | Decompose a list into its head and tail. If the list is empty, returns -- Nothing. If the list is non-empty, returns Just (x, -- xs), where x is the head of the list and xs its -- tail. uncons :: () => [a] -> Maybe (a, [a]) -- | Extract the first element of a list, which must be non-empty. head :: () => [a] -> a -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> let readMaybeInt = readMaybe :: String -> Maybe Int -- -- >>> mapMaybe readMaybeInt ["1", "Foo", "3"] -- [1,3] -- -- >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"] -- [1,3] ---- -- If we map the Just constructor, the entire list should be -- returned: -- --
-- >>> mapMaybe Just [1,2,3] -- [1,2,3] --mapMaybe :: () => (a -> Maybe b) -> [a] -> [b] -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --
-- >>> catMaybes [Just 1, Nothing, Just 3] -- [1,3] ---- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] -- [Just 1,Nothing,Just 3] -- -- >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] -- [1,3] --catMaybes :: () => [Maybe a] -> [a] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --
-- >>> listToMaybe [] -- Nothing ---- --
-- >>> listToMaybe [9] -- Just 9 ---- --
-- >>> listToMaybe [1,2,3] -- Just 1 ---- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
-- >>> maybeToList $ listToMaybe [5] -- [5] -- -- >>> maybeToList $ listToMaybe [] -- [] ---- -- But not on lists with more than one element: -- --
-- >>> maybeToList $ listToMaybe [1,2,3] -- [1] --listToMaybe :: () => [a] -> Maybe a -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when not given Nothing. -- --
-- >>> maybeToList (Just 7) -- [7] ---- --
-- >>> maybeToList Nothing -- [] ---- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> sum $ maybeToList (readMaybe "3") -- 3 -- -- >>> sum $ maybeToList (readMaybe "") -- 0 --maybeToList :: () => Maybe a -> [a] -- | The fromMaybe function takes a default value and and -- Maybe value. If the Maybe is Nothing, it returns -- the default values; otherwise, it returns the value contained in the -- Maybe. -- --
-- >>> fromMaybe "" (Just "Hello, World!") -- "Hello, World!" ---- --
-- >>> fromMaybe "" Nothing -- "" ---- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> fromMaybe 0 (readMaybe "5") -- 5 -- -- >>> fromMaybe 0 (readMaybe "") -- 0 --fromMaybe :: () => a -> Maybe a -> a -- | The fromJust function extracts the element out of a Just -- and throws an error if its argument is Nothing. -- --
-- >>> fromJust (Just 1) -- 1 ---- --
-- >>> 2 * (fromJust (Just 10)) -- 20 ---- --
-- >>> 2 * (fromJust Nothing) -- *** Exception: Maybe.fromJust: Nothing --fromJust :: () => Maybe a -> a -- | The isNothing function returns True iff its argument is -- Nothing. -- --
-- >>> isNothing (Just 3) -- False ---- --
-- >>> isNothing (Just ()) -- False ---- --
-- >>> isNothing Nothing -- True ---- -- Only the outer constructor is taken into consideration: -- --
-- >>> isNothing (Just Nothing) -- False --isNothing :: () => Maybe a -> Bool -- | The isJust function returns True iff its argument is of -- the form Just _. -- --
-- >>> isJust (Just 3) -- True ---- --
-- >>> isJust (Just ()) -- True ---- --
-- >>> isJust Nothing -- False ---- -- Only the outer constructor is taken into consideration: -- --
-- >>> isJust (Just Nothing) -- True --isJust :: () => Maybe a -> Bool -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --
-- >>> maybe False odd (Just 3) -- True ---- --
-- >>> maybe False odd Nothing -- False ---- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
-- >>> import Text.Read ( readMaybe ) -- -- >>> maybe 0 (*2) (readMaybe "5") -- 10 -- -- >>> maybe 0 (*2) (readMaybe "") -- 0 ---- -- Apply show to a Maybe Int. If we have Just -- n, we want to show the underlying Int n. But if -- we have Nothing, we return the empty string instead of (for -- example) "Nothing": -- --
-- >>> maybe "" show (Just 5) -- "5" -- -- >>> maybe "" show Nothing -- "" --maybe :: () => b -> (a -> b) -> Maybe a -> b -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
-- return f `ap` x1 `ap` ... `ap` xn ---- -- is equivalent to -- --
-- liftMn f x1 x2 ... xn --ap :: Monad m => m (a -> b) -> m a -> m b -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
-- liftM2 (+) [0,1] [0,2] = [0,2,1,3] -- liftM2 (+) (Just 1) Nothing = Nothing --liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | Conditional execution of Applicative expressions. For example, -- --
-- when debug (putStrLn "Debugging") ---- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | Lift a function to actions. This function may be used as a value for -- fmap in a Functor instance. liftA :: Applicative f => (a -> b) -> f a -> f b -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. data ReaderT r (m :: k -> Type) (a :: k) :: forall k. () => Type -> k -> Type -> k -> Type -- | Combine two paths with a path separator. If the second path starts -- with a path separator or a drive letter, then it returns the second. -- The intention is that readFile (dir </> file) -- will access the same file as setCurrentDirectory dir; readFile -- file. -- --
-- Posix: "/directory" </> "file.ext" == "/directory/file.ext" -- Windows: "/directory" </> "file.ext" == "/directory\\file.ext" -- "directory" </> "/file.ext" == "/file.ext" -- Valid x => (takeDirectory x </> takeFileName x) `equalFilePath` x ---- -- Combined: -- --
-- Posix: "/" </> "test" == "/test" -- Posix: "home" </> "bob" == "home/bob" -- Posix: "x:" </> "foo" == "x:/foo" -- Windows: "C:\\foo" </> "bar" == "C:\\foo\\bar" -- Windows: "home" </> "bob" == "home\\bob" ---- -- Not combined: -- --
-- Posix: "home" </> "/bob" == "/bob" -- Windows: "home" </> "C:\\bob" == "C:\\bob" ---- -- Not combined (tricky): -- -- On Windows, if a filepath starts with a single slash, it is relative -- to the root of the current drive. In [1], this is (confusingly) -- referred to as an absolute path. The current behavior of -- </> is to never combine these forms. -- --
-- Windows: "home" </> "/bob" == "/bob" -- Windows: "home" </> "\\bob" == "\\bob" -- Windows: "C:\\home" </> "\\bob" == "\\bob" ---- -- On Windows, from [1]: "If a file name begins with only a disk -- designator but not the backslash after the colon, it is interpreted as -- a relative path to the current directory on the drive with the -- specified letter." The current behavior of </> is to -- never combine these forms. -- --
-- Windows: "D:\\foo" </> "C:bar" == "C:bar" -- Windows: "C:\\foo" </> "C:bar" == "C:bar" --(>) :: FilePath -> FilePath -> FilePath infixr 5 > -- | Get the directory name, move up one level. -- --
-- takeDirectory "/directory/other.ext" == "/directory" -- takeDirectory x `isPrefixOf` x || takeDirectory x == "." -- takeDirectory "foo" == "." -- takeDirectory "/" == "/" -- takeDirectory "/foo" == "/" -- takeDirectory "/foo/bar/baz" == "/foo/bar" -- takeDirectory "/foo/bar/baz/" == "/foo/bar/baz" -- takeDirectory "foo/bar/baz" == "foo/bar" -- Windows: takeDirectory "foo\\bar" == "foo" -- Windows: takeDirectory "foo\\bar\\\\" == "foo\\bar" -- Windows: takeDirectory "C:\\" == "C:\\" --takeDirectory :: FilePath -> FilePath -- | Get the file name. -- --
-- takeFileName "/directory/file.ext" == "file.ext" -- takeFileName "test/" == "" -- takeFileName x `isSuffixOf` x -- takeFileName x == snd (splitFileName x) -- Valid x => takeFileName (replaceFileName x "fred") == "fred" -- Valid x => takeFileName (x </> "fred") == "fred" -- Valid x => isRelative (takeFileName x) --takeFileName :: FilePath -> FilePath -- | Add an extension, even if there is already one there, equivalent to -- addExtension. -- --
-- "/directory/path" <.> "ext" == "/directory/path.ext" -- "/directory/path" <.> ".ext" == "/directory/path.ext" --(<.>) :: FilePath -> String -> FilePath infixr 7 <.> -- | Set the extension of a file, overwriting one if already present, -- equivalent to -<.>. -- --
-- replaceExtension "/directory/path.txt" "ext" == "/directory/path.ext" -- replaceExtension "/directory/path.txt" ".ext" == "/directory/path.ext" -- replaceExtension "file.txt" ".bob" == "file.bob" -- replaceExtension "file.txt" "bob" == "file.bob" -- replaceExtension "file" ".bob" == "file.bob" -- replaceExtension "file.txt" "" == "file" -- replaceExtension "file.fred.bob" "txt" == "file.fred.txt" -- replaceExtension x y == addExtension (dropExtension x) y --replaceExtension :: FilePath -> String -> FilePath -- | View the value pointed to by a Getter or Lens or the -- result of folding over all the results of a Fold or -- Traversal that points at a monoidal values. -- -- This is the same operation as view with the arguments flipped. -- -- The fixity and semantics are such that subsequent field accesses can -- be performed with (.). -- --
-- >>> (a,b)^._2 -- b ---- --
-- >>> ("hello","world")^._2
-- "world"
--
--
-- -- >>> import Data.Complex -- -- >>> ((0, 1 :+ 2), 3)^._1._2.to magnitude -- 2.23606797749979 ---- --
-- (^.) :: s -> Getter s a -> a -- (^.) :: Monoid m => s -> Fold s m -> m -- (^.) :: s -> Iso' s a -> a -- (^.) :: s -> Lens' s a -> a -- (^.) :: Monoid m => s -> Traversal' s m -> m --(^.) :: () => s -> Getting a s a -> a infixl 8 ^. -- | Replace the target of a Lens or all of the targets of a -- Setter or Traversal with a constant value. -- -- This is an infix version of set, provided for consistency with -- (.=). -- --
-- f <$ a ≡ mapped .~ f $ a ---- --
-- >>> (a,b,c,d) & _4 .~ e -- (a,b,c,e) ---- --
-- >>> (42,"world") & _1 .~ "hello"
-- ("hello","world")
--
--
-- -- >>> (a,b) & both .~ c -- (c,c) ---- --
-- (.~) :: Setter s t a b -> b -> s -> t -- (.~) :: Iso s t a b -> b -> s -> t -- (.~) :: Lens s t a b -> b -> s -> t -- (.~) :: Traversal s t a b -> b -> s -> t --(.~) :: () => ASetter s t a b -> b -> s -> t infixr 4 .~ -- | Modifies the target of a Lens or all of the targets of a -- Setter or Traversal with a user supplied function. -- -- This is an infix version of over. -- --
-- fmap f ≡ mapped %~ f -- fmapDefault f ≡ traverse %~ f ---- --
-- >>> (a,b,c) & _3 %~ f -- (a,b,f c) ---- --
-- >>> (a,b) & both %~ f -- (f a,f b) ---- --
-- >>> _2 %~ length $ (1,"hello") -- (1,5) ---- --
-- >>> traverse %~ f $ [a,b,c] -- [f a,f b,f c] ---- --
-- >>> traverse %~ even $ [1,2,3] -- [False,True,False] ---- --
-- >>> traverse.traverse %~ length $ [["hello","world"],["!!!"]] -- [[5,5],[3]] ---- --
-- (%~) :: Setter s t a b -> (a -> b) -> s -> t -- (%~) :: Iso s t a b -> (a -> b) -> s -> t -- (%~) :: Lens s t a b -> (a -> b) -> s -> t -- (%~) :: Traversal s t a b -> (a -> b) -> s -> t --(%~) :: () => ASetter s t a b -> (a -> b) -> s -> t infixr 4 %~ -- | A Lens is actually a lens family as described in -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- With great power comes great responsibility and a Lens is -- subject to the three common sense Lens laws: -- -- 1) You get back what you put in: -- --
-- view l (set l v s) ≡ v ---- -- 2) Putting back what you got doesn't change anything: -- --
-- set l (view l s) s ≡ s ---- -- 3) Setting twice is the same as setting once: -- --
-- set l v' (set l v s) ≡ set l v' s ---- -- These laws are strong enough that the 4 type parameters of a -- Lens cannot vary fully independently. For more on how they -- interact, read the "Why is it a Lens Family?" section of -- http://comonad.com/reader/2012/mirrored-lenses/. -- -- There are some emergent properties of these laws: -- -- 1) set l s must be injective for every s This -- is a consequence of law #1 -- -- 2) set l must be surjective, because of law #2, which -- indicates that it is possible to obtain any v from some -- s such that set s v = s -- -- 3) Given just the first two laws you can prove a weaker form of law #3 -- where the values v that you are setting match: -- --
-- set l v (set l v s) ≡ set l v s ---- -- Every Lens can be used directly as a Setter or -- Traversal. -- -- You can also use a Lens for Getting as if it were a -- Fold or Getter. -- -- Since every Lens is a valid Traversal, the -- Traversal laws are required of any Lens you create: -- --
-- l pure ≡ pure -- fmap (l f) . l g ≡ getCompose . l (Compose . fmap f . g) ---- --
-- type Lens s t a b = forall f. Functor f => LensLike f s t a b --type Lens s t a b = forall (f :: Type -> Type). Functor f => a -> f b -> s -> f t -- | Convert a generic value into a pretty Value, if possible. ppShow :: Show a => a -> String -- | This is a simple runtime exception to indicate that B9 code -- encountered some exceptional event. newtype B9Error MkB9Error :: String -> B9Error [fromB9Error] :: B9Error -> String -- | Constraint alias for the exception effect that allows to throw -- SomeException. type WithIoExceptions e = SetMember Exc (Exc SomeException) e -- | The exception effect used in most places in B9. This is Exc -- specialized with SomeException. type ExcB9 = Exc SomeException -- | Run an ExcB9. runExcB9 :: Eff (ExcB9 : e) a -> Eff e (Either SomeException a) -- | Run an ExcB9 and rethrow the exception with error. errorOnException :: Lifted IO e => Eff (ExcB9 : e) a -> Eff e a -- | SomeException wrapped into Excecption Effects throwSomeException :: (Member ExcB9 e, Exception x) => x -> Eff e a -- | SomeException wrapped into Excecption Effects throwSomeException_ :: (Member ExcB9 e, Exception x) => x -> Eff e () -- | SomeException wrapped into Excecption Effects throwB9Error :: Member ExcB9 e => String -> Eff e a -- | SomeException wrapped into Excecption Effects throwB9Error_ :: Member ExcB9 e => String -> Eff e () -- | Catch exceptions. catchB9Error :: Member ExcB9 e => Eff e a -> (SomeException -> Eff e a) -> Eff e a -- | Catch exceptions and return them via Either. catchB9ErrorAsEither :: Member ExcB9 e => Eff e a -> Eff e (Either SomeException a) -- | Always execute an action and rethrow any exceptions caught. finallyB9 :: Member ExcB9 e => Eff e a -> Eff e () -> Eff e a arbitraryEnv :: Arbitrary a => Gen [(String, a)] halfSize :: Gen a -> Gen a smaller :: Gen a -> Gen a arbitraryFilePath :: Gen FilePath arbitraryLetter :: Gen Char arbitraryLetterUpper :: Gen Char arbitraryLetterLower :: Gen Char arbitraryDigit :: Gen Char -- | Every B9 build running in a B9Monad contains a random unique -- id that is generated once per build (no matter how many artifacts are -- created in that build) This field contains the build id of the build -- that created the shared image instance. This is A wrapper around a -- string contains the build id of a SharedImage; this is purely -- additional convenience and typesafety newtype SharedImageBuildId SharedImageBuildId :: String -> SharedImageBuildId -- | The exact time that build job started. This is a wrapper around -- a string contains the build date of a SharedImage; this is -- purely additional convenience and typesafety newtype SharedImageDate SharedImageDate :: String -> SharedImageDate -- | The name of the image is the de-facto identifier for push, pull, -- From and Share. B9 always selects the newest version the -- shared image identified by that name when using a shared image as an -- ImageSource. This is a wrapper around a string that identifies -- a SharedImage newtype SharedImageName SharedImageName :: String -> SharedImageName -- | SharedImage holds all data necessary to describe an -- instance of a shared image identified by a -- SharedImageName. Shared images are stored in -- Repositorys. data SharedImage SharedImage :: SharedImageName -> SharedImageDate -> SharedImageBuildId -> ImageType -> FileSystem -> SharedImage -- | A type alias that indicates that something of type a is mount -- at a MountPoint type Mounted a = (a, MountPoint) -- | How to resize an image file. data ImageResize -- | Resize the image but not the file system. Note that a file -- system contained in the image file might be corrupted by this -- operation. To not only resize the image file but also the fil system -- contained in it, use Resize. ResizeImage :: ImageSize -> ImageResize -- | Resize an image and the contained file system. Resize :: ImageSize -> ImageResize -- | Shrink to minimum size needed and increase by the amount given. ShrinkToMinimumAndIncrease :: ImageSize -> ImageResize -- | Resize an image and the contained file system to the smallest size to -- fit the contents of the file system. ShrinkToMinimum :: ImageResize -- | Do not change the image size. KeepSize :: ImageResize -- | Enumeration of size multipliers. The exact semantics may vary -- depending on what external tools look at these. E.g. the size unit is -- convert to a size parameter of the qemu-img command line -- tool. data SizeUnit KB :: SizeUnit MB :: SizeUnit GB :: SizeUnit -- | A data type for image file or file system size; instead of passing -- Ints around this also captures a size unit so that the -- Int can be kept small data ImageSize ImageSize :: Int -> SizeUnit -> ImageSize -- | The file systems that b9 can use and convert. data FileSystem NoFileSystem :: FileSystem Ext4 :: FileSystem Ext4_64 :: FileSystem ISO9660 :: FileSystem VFAT :: FileSystem -- | An image type defines the actual file format of a file -- containing file systems. These are like virtual harddrives data ImageType Raw :: ImageType QCow2 :: ImageType Vmdk :: ImageType -- | A vm disk image file consisting of a path to the image file, and the -- type and file system. data Image Image :: FilePath -> ImageType -> FileSystem -> Image -- | The partition to extract. data Partition -- | There is no partition table on the image NoPT :: Partition -- | Extract partition n n must be in 0..3 Partition :: Int -> Partition -- | Specification of how the image to build is obtained. data ImageSource -- | Create an empty image file having a file system label (first -- parameter), a file system type (e.g. Ext4) and an -- ImageSize EmptyImage :: String -> FileSystem -> ImageType -> ImageSize -> ImageSource -- | DEPRECATED CopyOnWrite :: Image -> ImageSource -- | Clone an existing image file; if the image file contains partitions, -- select the partition to use, b9 will extract that partition by reading -- the offset of the partition from the partition table and extract it -- using dd. SourceImage :: Image -> Partition -> ImageResize -> ImageSource -- | Use an image previously shared by via Share. From :: String -> ImageResize -> ImageSource -- | The destination of an image. data ImageDestination -- | Create the image and some meta data so that other builds can use them -- as ImageSources via From. Share :: String -> ImageType -> ImageResize -> ImageDestination -- | DEPRECATED Export a raw image that can directly be booted. LiveInstallerImage :: String -> FilePath -> ImageResize -> ImageDestination -- | Write an image file to the path in the first argument., possible -- resizing it, LocalFile :: Image -> ImageResize -> ImageDestination -- | Do not export the image. Usefule if the main objective of the b9 build -- is not an image file, but rather some artifact produced by executing -- by a containerize build. Transient :: ImageDestination -- | A mount point or NotMounted data MountPoint MountPoint :: FilePath -> MountPoint NotMounted :: MountPoint -- | Build target for disk images; the destination, format and size of the -- image to generate, as well as how to create or obtain the image before -- a VmScript is executed with the image mounted at a -- MountPoint. data ImageTarget ImageTarget :: ImageDestination -> ImageSource -> MountPoint -> ImageTarget -- | Convert a size in bytes to an ImageSize bytesToKiloBytes :: Int -> ImageSize -- | Convert an ImageSize to kibi bytes. imageSizeToKiB :: ImageSize -> Int -- | Convert a SizeUnit to the number of kibi bytes one element -- represents. sizeUnitKiB :: SizeUnit -> Int -- | Choose the greatest unit possible to exactly represent an -- ImageSize. normalizeSize :: ImageSize -> ImageSize -- | Return the sum of two ImageSizes. addImageSize :: ImageSize -> ImageSize -> ImageSize -- | Get the String representation of a SharedImageName. fromSharedImageName :: SharedImageName -> String -- | Get the String representation of a SharedImageBuildId. fromSharedImageBuildId :: SharedImageBuildId -> String -- | Transform a list of SharedImage values into a Map that -- associates each SharedImageName with a Set of the actual -- images with that name. -- -- The Set contains values of type SharedImage. -- -- The Ord instance of SharedImage sorts by name first and -- then by sharedImageDate, since the values in a Set share -- the same sharedImageName, they are effectively orderd by build -- date, which is useful the shared image cleanup. sharedImagesToMap :: [SharedImage] -> Map SharedImageName (Set SharedImage) -- | Return the SharedImage with the highest sharedImageDate. takeLatestSharedImage :: [SharedImage] -> Maybe SharedImage -- | Return the name of the file corresponding to an Image imageFileName :: Image -> FilePath -- | Return the ImageType of an Image imageImageType :: Image -> ImageType -- | Return the files generated for a LocalFile or a -- LiveInstallerImage; SharedImage and Transient are -- treated like they have no output files because the output files are -- manged by B9. getImageDestinationOutputFiles :: ImageTarget -> [FilePath] -- | Return the name of a shared image, if the ImageDestination is a -- Share destination imageDestinationSharedImageName :: ImageDestination -> Maybe SharedImageName -- | Return the name of a shared source image, if the ImageSource is -- a From source imageSourceSharedImageName :: ImageSource -> Maybe SharedImageName -- | Get the ImageDestination of an ImageTarget itImageDestination :: ImageTarget -> ImageDestination -- | Get the ImageSource of an ImageTarget itImageSource :: ImageTarget -> ImageSource -- | Get the MountPoint of an ImageTarget itImageMountPoint :: ImageTarget -> MountPoint -- | Return true if a Partition parameter is actually referring to a -- partition, false if it is NoPT isPartitioned :: Partition -> Bool -- | Return the Partition index or throw a runtime error if applied -- to NoPT getPartition :: Partition -> Int -- | Return the file name extension of an image file with a specific image -- format. imageFileExtension :: ImageType -> String -- | Change the image file format and also rename the image file name to -- have the appropriate file name extension. See -- imageFileExtension and replaceExtension changeImageFormat :: ImageType -> Image -> Image changeImageDirectory :: FilePath -> Image -> Image getImageSourceImageType :: ImageSource -> Maybe ImageType -- | Return the name of a shared image. sharedImageName :: SharedImage -> SharedImageName -- | Return the build date of a shared image. sharedImageDate :: SharedImage -> SharedImageDate -- | Return the build id of a shared image. sharedImageBuildId :: SharedImage -> SharedImageBuildId -- | Print the contents of the shared image in one line prettyPrintSharedImages :: Set SharedImage -> String -- | Return the disk image of an sharedImage sharedImageImage :: SharedImage -> Image -- | Calculate the path to the text file holding the serialized -- SharedImage relative to the directory of shared images in a -- repository. sharedImageFileName :: SharedImage -> FilePath sharedImagesRootDirectory :: FilePath sharedImageFileExtension :: String -- | The internal image type to use as best guess when dealing with a -- From value. sharedImageDefaultImageType :: ImageType -- | Use a QCow2 image with an Ext4 file system transientCOWImage :: FilePath -> FilePath -> ImageTarget -- | Use a shared image transientSharedImage :: SharedImageName -> FilePath -> ImageTarget -- | Use a shared image transientLocalImage :: FilePath -> FilePath -> ImageTarget -- | Share a QCow2 image with Ext4 fs shareCOWImage :: FilePath -> SharedImageName -> FilePath -> ImageTarget -- | Share an image based on a shared image shareSharedImage :: SharedImageName -> SharedImageName -> FilePath -> ImageTarget -- | Share a QCow2 image with Ext4 fs shareLocalImage :: FilePath -> SharedImageName -> FilePath -> ImageTarget -- | Export a QCow2 image with Ext4 fs cowToliveInstallerImage :: String -> FilePath -> FilePath -> FilePath -> ImageTarget -- | Export a QCow2 image file with Ext4 fs as a local file cowToLocalImage :: FilePath -> FilePath -> FilePath -> ImageTarget -- | Export a QCow2 image file with Ext4 fs as a local file localToLocalImage :: FilePath -> FilePath -> FilePath -> ImageTarget -- | Create a local image file from the contents of the first partition of -- a local QCow2 image. partition1ToLocalImage :: FilePath -> FilePath -> FilePath -> ImageTarget -- | Split any image target into two image targets, one for creating an -- intermediate shared image and one from the intermediate shared image -- to the output image. splitToIntermediateSharedImage :: ImageTarget -> SharedImageName -> (ImageTarget, ImageTarget) arbitrarySharedImageName :: Gen String unitTests :: Spec data RamSize RamSize :: Int -> SizeUnit -> RamSize AutomaticRamSize :: RamSize data CPUArch X86_64 :: CPUArch I386 :: CPUArch data Resources Resources :: RamSize -> Int -> CPUArch -> Resources [maxMemory] :: Resources -> RamSize [cpuCount] :: Resources -> Int [cpuArch] :: Resources -> CPUArch data SharedDirectory SharedDirectory :: FilePath -> MountPoint -> SharedDirectory SharedDirectoryRO :: FilePath -> MountPoint -> SharedDirectory SharedSources :: MountPoint -> SharedDirectory -- | The environment for the execution of Scripts inside a -- Container data ExecEnv ExecEnv :: String -> [Mounted Image] -> [SharedDirectory] -> Resources -> ExecEnv [envName] :: ExecEnv -> String [envImageMounts] :: ExecEnv -> [Mounted Image] [envSharedDirectories] :: ExecEnv -> [SharedDirectory] [envResources] :: ExecEnv -> Resources noResources :: Resources data User User :: String -> User NoUser :: User data Cwd Cwd :: FilePath -> Cwd NoCwd :: Cwd data CmdVerbosity Debug :: CmdVerbosity Verbose :: CmdVerbosity OnlyStdErr :: CmdVerbosity Quiet :: CmdVerbosity data Script In :: FilePath -> [Script] -> Script As :: String -> [Script] -> Script IgnoreErrors :: Bool -> [Script] -> Script Verbosity :: CmdVerbosity -> [Script] -> Script Begin :: [Script] -> Script Run :: FilePath -> [String] -> Script NoOP :: Script -- | Convert script to bash-shell-script written to file -- and make file executable. writeSh :: FilePath -> Script -> IO () -- | Check if a script has the same effect as NoOP emptyScript :: Script -> Bool renderScript :: Script -> String -- | A class for values that can be converted to/from Text. class Textual a -- | Convert a String to Text If an error occured, return -- Left with the error message. renderToText :: (Textual a, HasCallStack) => a -> Either String Text -- | Convert a Text to String parseFromText :: (Textual a, HasCallStack) => Text -> Either String a -- | Lazy texts. -- -- A type alias to Text that can be used everywhere such that -- references don't need to be qualified with the complete module name -- everywere. type LazyText = Text -- | Lazy byte strings. -- -- A type alias to ByteString that can be used everywhere such -- that references don't need to be qualified with the complete module -- name everywere. type LazyByteString = ByteString -- | Render a Text to a file. writeTextFile :: (HasCallStack, MonadIO m) => FilePath -> Text -> m () -- | Render a Text via renderToText and throw a runtime -- exception when rendering fails. unsafeRenderToText :: (Textual a, HasCallStack) => a -> Text -- | Parse a Text via parseFromText and throw a runtime -- exception when parsing fails. unsafeParseFromText :: (Textual a, HasCallStack) => Text -> a -- | Encode a String as UTF-8 encoded into a LazyByteString. encodeAsUtf8LazyByteString :: HasCallStack => String -> LazyByteString -- | Parse the given Text. -- Return Left errorMessage or -- Right a. parseFromTextWithErrorMessage :: (HasCallStack, Textual a) => String -> Text -> Either String a -- | An Exception thrown by lookupOrThrow indicating that a -- key does not exist. -- -- @Since 0.5.62 data KeyNotFound MkKeyNotFound :: Text -> Environment -> KeyNotFound -- | An Exception thrown by addBinding indicating that a key -- already exists. -- -- @Since 0.5.62 data DuplicateKey MkDuplicateKey :: Text -> Text -> Text -> DuplicateKey [duplicateKey] :: DuplicateKey -> Text [duplicateKeyOldValue] :: DuplicateKey -> Text [duplicateKeyNewValue] :: DuplicateKey -> Text -- | A monad transformer providing a MonadReader instance for -- Environment type EnvironmentReader = Reader Environment -- | A map of textual keys to textual values. data Environment -- | If environment variables arg_1 .. arg_n are bound and a list -- of k additional values are passed to this function, store -- them with keys arg_(n+1) .. arg_(n+k). -- -- Note that the Environment contains an index of the next position. addPositionalArguments :: [Text] -> Environment -> Environment -- | Convenient wrapper around addPositionalArguments and -- localEnvironment. addLocalPositionalArguments :: Member EnvironmentReader e => [String] -> Eff e a -> Eff e a -- | Create an Environment from a list of pairs (Strings). -- Duplicated entries are ignored. fromStringPairs :: [(String, String)] -> Environment -- | Insert a key value binding to the Environment. -- -- Throw DuplicateKey if the key already exists, but the value is -- not equal to the given value. addBinding :: Member ExcB9 e => (Text, Text) -> Environment -> Eff e Environment -- | Insert Strings into the Environment, see -- addBinding. addStringBinding :: Member ExcB9 e => (String, String) -> Environment -> Eff e Environment -- | Insert a value into an Environment like -- addStringBinding, but add it to the environment of the given -- effect, as in localEnvironment. addLocalStringBinding :: (Member EnvironmentReader e, Member ExcB9 e) => (String, String) -> Eff e a -> Eff e a -- | Run a ReaderT of Environment. runEnvironmentReader :: Environment -> Eff (EnvironmentReader : e) a -> Eff e a -- | Get the current Environment askEnvironment :: Member EnvironmentReader e => Eff e Environment -- | Run a computation with a modified Environment localEnvironment :: Member EnvironmentReader e => (Environment -> Environment) -> Eff e a -> Eff e a -- | Lookup a key for a value. -- -- throwM a KeyNotFound Exception if no value with -- the given key exists in the Environment. -- -- @Since 0.5.62 lookupOrThrow :: '[ExcB9, EnvironmentReader] <:: e => Text -> Eff e Text -- | Lookup a key for a value. -- -- Return Either Left KeyNotFound, if no value with -- the given key exists in the Environment, or Right the -- value. -- -- @Since 0.5.62 lookupEither :: Member EnvironmentReader e => Text -> Eff e (Either KeyNotFound Text) -- | A predicate that is satisfied when a key exists in the environment. hasKey :: Member EnvironmentReader e => Text -> Eff e Bool -- | Simplified Erlang term representation. data SimpleErlangTerm ErlString :: String -> SimpleErlangTerm ErlFloat :: Double -> SimpleErlangTerm ErlNatural :: Integer -> SimpleErlangTerm ErlAtom :: String -> SimpleErlangTerm ErlChar :: Char -> SimpleErlangTerm ErlBinary :: String -> SimpleErlangTerm ErlList :: [SimpleErlangTerm] -> SimpleErlangTerm ErlTuple :: [SimpleErlangTerm] -> SimpleErlangTerm -- | Parse a subset of valid Erlang terms. It parses no maps and binaries -- are restricted to either empty binaries or binaries with a string. The -- input encoding must be restricted to ascii compatible 8-bit characters -- (e.g. latin-1 or UTF8). parseErlTerm :: String -> Text -> Either String SimpleErlangTerm -- | Convert an abstract Erlang term to a pretty byte string preserving the -- encoding. renderErlTerm :: SimpleErlangTerm -> Text erlTermParser :: Parser SimpleErlangTerm arbitraryErlSimpleAtom :: Gen SimpleErlangTerm arbitraryErlString :: Gen SimpleErlangTerm arbitraryErlNumber :: Gen SimpleErlangTerm arbitraryErlNatural :: Gen SimpleErlangTerm arbitraryErlFloat :: Gen SimpleErlangTerm arbitraryErlNameChar :: Gen Char -- | A bunch of numbers, enough to make globally unique IDs. Create one of -- these using randomUUID. data UUID -- | An Exception thrown by consult to indicate the file does -- not contain a readable String data ConsultException ConsultException :: FilePath -> String -> ConsultException -- | A data type encapsulating different kinds of relative or absolute -- paths. data SystemPath -- | A path that will just be passed through Path :: FilePath -> SystemPath -- | A OS specific path relative to the home directory of a user. InHomeDir :: FilePath -> SystemPath -- | A path relative to the b9 sub of the users application -- configuration directory getAppUserDataDirectory InB9UserDir :: FilePath -> SystemPath -- | A path relative to the systems temporary directory. InTempDir :: FilePath -> SystemPath -- | Transform a SystemPath overSystemPath :: (FilePath -> FilePath) -> SystemPath -> SystemPath -- | Convert a SystemPath to a FilePath. resolve :: MonadIO m => SystemPath -> m FilePath -- | Get all files from dir that is get ONLY files not directories getDirectoryFiles :: MonadIO m => FilePath -> m [FilePath] -- | Create all missing parent directories of a file path. ensureSystemPath :: MonadIO m => SystemPath -> m () -- | Create all missing parent directories of a file path. Note that the -- file path is assumed to be of a regular file, and takeDirectory -- is applied before creating the directory. ensureDir :: MonadIO m => FilePath -> m () -- | Write a value of a type that is an instance of Show to file. -- This function uses ppShow instead of the given Show -- instance. prettyPrintToFile :: (MonadIO m, Show a) => FilePath -> a -> m () -- | Read a value of a type that is an instance of Read from a file. -- This function throws a ConsultException when the read the file -- failed. consult :: (MonadIO m, Read a) => FilePath -> m a -- | Generate a random UUID. randomUUID :: MonadIO m => m UUID removeIfExists :: FilePath -> IO () newtype SshRemoteUser SshRemoteUser :: String -> SshRemoteUser newtype SshRemoteHost SshRemoteHost :: (String, Int) -> SshRemoteHost newtype SshPrivKey SshPrivKey :: FilePath -> SshPrivKey data RemoteRepo RemoteRepo :: String -> FilePath -> SshPrivKey -> SshRemoteHost -> SshRemoteUser -> RemoteRepo newtype RepoCache RepoCache :: FilePath -> RepoCache remoteRepoRepoId :: RemoteRepo -> String -- | Persist a repo to a configuration file. remoteRepoToCPDocument :: RemoteRepo -> CPDocument -> Either CPError CPDocument -- | Load a repository from a configuration file that has been written by -- writeRepositoryToB9Config. parseRemoteRepos :: CPDocument -> Either CPError [RemoteRepo] -- | Available capabilities for Linux containers. This maps directly to the -- capabilities defined in 'man 7 capabilities'. data ContainerCapability CAP_MKNOD :: ContainerCapability CAP_AUDIT_CONTROL :: ContainerCapability CAP_AUDIT_READ :: ContainerCapability CAP_AUDIT_WRITE :: ContainerCapability CAP_BLOCK_SUSPEND :: ContainerCapability CAP_CHOWN :: ContainerCapability CAP_DAC_OVERRIDE :: ContainerCapability CAP_DAC_READ_SEARCH :: ContainerCapability CAP_FOWNER :: ContainerCapability CAP_FSETID :: ContainerCapability CAP_IPC_LOCK :: ContainerCapability CAP_IPC_OWNER :: ContainerCapability CAP_KILL :: ContainerCapability CAP_LEASE :: ContainerCapability CAP_LINUX_IMMUTABLE :: ContainerCapability CAP_MAC_ADMIN :: ContainerCapability CAP_MAC_OVERRIDE :: ContainerCapability CAP_NET_ADMIN :: ContainerCapability CAP_NET_BIND_SERVICE :: ContainerCapability CAP_NET_BROADCAST :: ContainerCapability CAP_NET_RAW :: ContainerCapability CAP_SETGID :: ContainerCapability CAP_SETFCAP :: ContainerCapability CAP_SETPCAP :: ContainerCapability CAP_SETUID :: ContainerCapability CAP_SYS_ADMIN :: ContainerCapability CAP_SYS_BOOT :: ContainerCapability CAP_SYS_CHROOT :: ContainerCapability CAP_SYS_MODULE :: ContainerCapability CAP_SYS_NICE :: ContainerCapability CAP_SYS_PACCT :: ContainerCapability CAP_SYS_PTRACE :: ContainerCapability CAP_SYS_RAWIO :: ContainerCapability CAP_SYS_RESOURCE :: ContainerCapability CAP_SYS_TIME :: ContainerCapability CAP_SYS_TTY_CONFIG :: ContainerCapability CAP_SYSLOG :: ContainerCapability CAP_WAKE_ALARM :: ContainerCapability containerCapsToCPDocument :: CPDocument -> CPSectionSpec -> [ContainerCapability] -> Either CPError CPDocument parseContainerCapabilities :: CPDocument -> CPSectionSpec -> Either CPError [ContainerCapability] data SystemdNspawnConsole SystemdNspawnInteractive :: SystemdNspawnConsole SystemdNspawnReadOnly :: SystemdNspawnConsole SystemdNspawnPassive :: SystemdNspawnConsole SystemdNspawnPipe :: SystemdNspawnConsole data SystemdNspawnConfig SystemdNspawnConfig :: [ContainerCapability] -> Bool -> Maybe Int -> Maybe String -> Maybe FilePath -> SystemdNspawnConsole -> SystemdNspawnConfig [_systemdNspawnCapabilities] :: SystemdNspawnConfig -> [ContainerCapability] [_systemdNspawnUseSudo] :: SystemdNspawnConfig -> Bool [_systemdNspawnMaxLifetimeSeconds] :: SystemdNspawnConfig -> Maybe Int [_systemdNspawnExtraArgs] :: SystemdNspawnConfig -> Maybe String [_systemdNspawnExecutable] :: SystemdNspawnConfig -> Maybe FilePath [_systemdNspawnConsole] :: SystemdNspawnConfig -> SystemdNspawnConsole systemdNspawnCapabilities :: Lens' SystemdNspawnConfig [ContainerCapability] systemdNspawnConsole :: Lens' SystemdNspawnConfig SystemdNspawnConsole systemdNspawnExecutable :: Lens' SystemdNspawnConfig (Maybe FilePath) systemdNspawnExtraArgs :: Lens' SystemdNspawnConfig (Maybe String) systemdNspawnMaxLifetimeSeconds :: Lens' SystemdNspawnConfig (Maybe Int) systemdNspawnUseSudo :: Lens' SystemdNspawnConfig Bool defaultSystemdNspawnConfig :: SystemdNspawnConfig systemdNspawnConfigToCPDocument :: SystemdNspawnConfig -> CPDocument -> Either CPError CPDocument parseSystemdNspawnConfig :: CPDocument -> Either CPError SystemdNspawnConfig data PodmanConfig PodmanConfig :: Maybe String -> [ContainerCapability] -> PodmanConfig [_podmanNetworkId] :: PodmanConfig -> Maybe String [_podmanCapabilities] :: PodmanConfig -> [ContainerCapability] podmanCapabilities :: Lens' PodmanConfig [ContainerCapability] podmanNetworkId :: Lens' PodmanConfig (Maybe String) defaultPodmanConfig :: PodmanConfig podmanConfigToCPDocument :: PodmanConfig -> CPDocument -> Either CPError CPDocument parsePodmanConfig :: CPDocument -> Either CPError PodmanConfig data LibVirtLXCConfig LibVirtLXCConfig :: Bool -> Maybe FilePath -> FilePath -> Maybe String -> [ContainerCapability] -> RamSize -> LibVirtLXCConfig [useSudo] :: LibVirtLXCConfig -> Bool [emulator] :: LibVirtLXCConfig -> Maybe FilePath [virshURI] :: LibVirtLXCConfig -> FilePath [_networkId] :: LibVirtLXCConfig -> Maybe String [guestCapabilities] :: LibVirtLXCConfig -> [ContainerCapability] [guestRamSize] :: LibVirtLXCConfig -> RamSize networkId :: Lens' LibVirtLXCConfig (Maybe String) defaultLibVirtLXCConfig :: LibVirtLXCConfig libVirtLXCConfigToCPDocument :: LibVirtLXCConfig -> CPDocument -> Either CPError CPDocument parseLibVirtLXCConfig :: CPDocument -> Either CPError LibVirtLXCConfig -- | Return the path to -- usrliblibvirtlibexec/libvirt_lxc the -- emulatorK field from the config file, or set the path in the -- environment variable named like the value in emulatorEnvVar -- dictates. getEmulatorPath :: MonadIO m => LibVirtLXCConfig -> m FilePath data DockerConfig DockerConfig :: Maybe String -> [ContainerCapability] -> DockerConfig [_dockerNetworkId] :: DockerConfig -> Maybe String [_dockerCapabilities] :: DockerConfig -> [ContainerCapability] dockerCapabilities :: Lens' DockerConfig [ContainerCapability] dockerNetworkId :: Lens' DockerConfig (Maybe String) defaultDockerConfig :: DockerConfig dockerConfigToCPDocument :: DockerConfig -> CPDocument -> Either CPError CPDocument parseDockerConfig :: CPDocument -> Either CPError DockerConfig -- | Override b9 configuration items and/or the path of the b9 -- configuration file. This is useful, i.e. when dealing with command -- line parameters. data B9ConfigOverride B9ConfigOverride :: [SystemPath] -> Endo B9Config -> Environment -> Maybe SystemPath -> B9ConfigOverride [_customB9ConfigPath] :: B9ConfigOverride -> [SystemPath] [_customB9Config] :: B9ConfigOverride -> Endo B9Config [_customEnvironment] :: B9ConfigOverride -> Environment [_customDefaulB9ConfigPath] :: B9ConfigOverride -> Maybe SystemPath -- | Reader for B9Config. See getB9Config and -- localB9Config. type B9ConfigReader = Reader B9Config data B9Config B9Config :: Maybe LogLevel -> Maybe FilePath -> Maybe FilePath -> Bool -> Bool -> Maybe SystemPath -> Maybe String -> Maybe Int -> Maybe SystemdNspawnConfig -> Maybe PodmanConfig -> Maybe DockerConfig -> Maybe LibVirtLXCConfig -> Set RemoteRepo -> Maybe Timeout -> Maybe Int -> [String] -> B9Config [_verbosity] :: B9Config -> Maybe LogLevel [_logFile] :: B9Config -> Maybe FilePath [_projectRoot] :: B9Config -> Maybe FilePath [_keepTempDirs] :: B9Config -> Bool [_uniqueBuildDirs] :: B9Config -> Bool [_repositoryCache] :: B9Config -> Maybe SystemPath [_repository] :: B9Config -> Maybe String [_maxLocalSharedImageRevisions] :: B9Config -> Maybe Int [_systemdNspawnConfigs] :: B9Config -> Maybe SystemdNspawnConfig [_podmanConfigs] :: B9Config -> Maybe PodmanConfig [_dockerConfigs] :: B9Config -> Maybe DockerConfig [_libVirtLXCConfigs] :: B9Config -> Maybe LibVirtLXCConfig [_remoteRepos] :: B9Config -> Set RemoteRepo [_defaultTimeout] :: B9Config -> Maybe Timeout [_timeoutFactor] :: B9Config -> Maybe Int [_ext4Attributes] :: B9Config -> [String] data LogLevel LogTrace :: LogLevel LogDebug :: LogLevel LogInfo :: LogLevel LogError :: LogLevel LogNothing :: LogLevel -- | A way to specify a time intervall for example for the timeouts of -- system commands. newtype Timeout TimeoutMicros :: Int -> Timeout -- | Run a B9ConfigReader. runB9ConfigReader :: HasCallStack => B9Config -> Eff (B9ConfigReader : e) a -> Eff e a -- | Return the runtime configuration, that should be the configuration -- merged from all configuration sources. This is the configuration to be -- used during a VM image build. getB9Config :: Member B9ConfigReader e => Eff e B9Config -- | Run an action with an updated runtime configuration. localB9Config :: Member B9ConfigReader e => (B9Config -> B9Config) -> Eff e a -> Eff e a -- | An alias for getB9Config. -- -- @deprecated getConfig :: Member B9ConfigReader e => Eff e B9Config -- | Ask for the RemoteRepos. getRemoteRepos :: Member B9ConfigReader e => Eff e (Set RemoteRepo) -- | Ask for the LogLevel. getLogVerbosity :: Member B9ConfigReader e => Eff e (Maybe LogLevel) -- | Ask for the project root directory. getProjectRoot :: Member B9ConfigReader e => Eff e FilePath -- | An empty default B9ConfigOverride value, that will neither -- apply any additional B9Config nor change the path of the -- configuration file. noB9ConfigOverride :: B9ConfigOverride defaultTimeout :: Lens' B9Config (Maybe Timeout) dockerConfigs :: Lens' B9Config (Maybe DockerConfig) ext4Attributes :: Lens' B9Config [String] keepTempDirs :: Lens' B9Config Bool libVirtLXCConfigs :: Lens' B9Config (Maybe LibVirtLXCConfig) logFile :: Lens' B9Config (Maybe FilePath) maxLocalSharedImageRevisions :: Lens' B9Config (Maybe Int) podmanConfigs :: Lens' B9Config (Maybe PodmanConfig) projectRoot :: Lens' B9Config (Maybe FilePath) remoteRepos :: Lens' B9Config (Set RemoteRepo) repository :: Lens' B9Config (Maybe String) repositoryCache :: Lens' B9Config (Maybe SystemPath) systemdNspawnConfigs :: Lens' B9Config (Maybe SystemdNspawnConfig) timeoutFactor :: Lens' B9Config (Maybe Int) uniqueBuildDirs :: Lens' B9Config Bool verbosity :: Lens' B9Config (Maybe LogLevel) -- | Accumulate B9Config changes that go back to the config file. -- See B9ConfigAction and modifyPermanentConfig. type B9ConfigWriter = Writer (Endo B9Config) -- | A monad that gives access to the (transient) B9Config to be -- used at _runtime_ with getB9Config or localB9Config, and -- that allows to write permanent B9Config changes back to the -- configuration file using modifyPermanentConfig. This is the -- amalgamation of B9ConfigWriter B9ConfigReader and -- IO. type B9ConfigAction a = Eff '[B9ConfigWriter, B9ConfigReader, EnvironmentReader, Lift IO] a customB9Config :: Lens' B9ConfigOverride (Endo B9Config) customB9ConfigPath :: Lens' B9ConfigOverride [SystemPath] customDefaulB9ConfigPath :: Lens' B9ConfigOverride (Maybe SystemPath) customEnvironment :: Lens' B9ConfigOverride Environment -- | Convenience utility to override the B9 configuration file path. overrideB9ConfigPath :: SystemPath -> B9ConfigOverride -> B9ConfigOverride -- | Modify the runtime configuration. overrideB9Config :: (B9Config -> B9Config) -> B9ConfigOverride -> B9ConfigOverride -- | Convenience utility to override the *default* B9 configuration file -- path. overrideDefaultB9ConfigPath :: SystemPath -> B9ConfigOverride -> B9ConfigOverride -- | Define the current working directory to be used when building. overrideWorkingDirectory :: FilePath -> B9ConfigOverride -> B9ConfigOverride -- | Define the default timeout for external commands. overrideDefaultTimeout :: Maybe Timeout -> B9ConfigOverride -> B9ConfigOverride -- | Define the timeout factor for external commands. overrideTimeoutFactor :: Maybe Int -> B9ConfigOverride -> B9ConfigOverride -- | Overwrite the verbosity settings in the configuration with -- those given. overrideVerbosity :: LogLevel -> B9ConfigOverride -> B9ConfigOverride -- | Overwrite the keepTempDirs flag in the configuration with those -- given. overrideKeepBuildDirs :: Bool -> B9ConfigOverride -> B9ConfigOverride -- | Overwrite the ext4Attributes overrideExt4Attributes :: [String] -> B9ConfigOverride -> B9ConfigOverride -- | Add a modification to the permanent configuration file. modifyPermanentConfig :: (HasCallStack, Member B9ConfigWriter e) => Endo B9Config -> Eff e () -- | Execute a B9ConfigAction. It will take a -- B9ConfigOverride as input. The B9Config in that value is -- treated as the _runtime_ configuration, and the -- _customConfigPath is used as the alternative location of the -- configuration file. The configuration file is read from either the -- path in _customB9ConfigPath or from defaultB9ConfigFile. -- Every modification done via modifyPermanentConfig is applied to -- the **contents** of the configuration file and written back to that -- file, note that these changes are ONLY reflected in the configuration -- file and **not** in the _runtime configuration_. -- -- See also runB9ConfigAction, which does not need the -- B9ConfigOverride parameter. runB9ConfigActionWithOverrides :: HasCallStack => B9ConfigAction a -> B9ConfigOverride -> IO a -- | Run a B9ConfigAction using noB9ConfigOverride. See -- runB9ConfigActionWithOverrides for more details. runB9ConfigAction :: HasCallStack => B9ConfigAction a -> IO a -- | Open the configuration file that contains the B9Config. If the -- configuration does not exist, write a default configuration file, and -- create a all missing directories. openOrCreateB9Config :: (HasCallStack, MonadIO m) => FilePath -> m CPDocument -- | Write the configuration in the CPDocument to either the user -- supplied configuration file path or to defaultB9ConfigFile. -- Create all missing (parent) directories. writeB9CPDocument :: (HasCallStack, MonadIO m) => Maybe SystemPath -> CPDocument -> m () defaultB9Config :: B9Config defaultRepositoryCache :: SystemPath defaultB9ConfigFile :: SystemPath maxLocalSharedImageRevisionsK :: String -- | Parse a B9Config, modify it, and merge it back to the given -- CPDocument. modifyCPDocument :: CPDocument -> Endo B9Config -> Either CPError CPDocument -- | Append a config file section for the B9Config to an empty -- CPDocument. b9ConfigToCPDocument :: HasCallStack => B9Config -> Either CPError CPDocument readB9Config :: (HasCallStack, MonadIO m) => Maybe SystemPath -> m CPDocument parseB9Config :: HasCallStack => CPDocument -> Either CPError B9Config -- | A Map that maps Repositorys to the SharedImages -- they hold. type RepoImagesMap = Map Repository (Set SharedImage) -- | Alias for a Reader Effect that reads the -- RemoteRepo selected by the B9Config value -- _repository. See withSelectedRemoteRepo. type SelectedRemoteRepoReader = Reader SelectedRemoteRepo -- | Contains the Just the RemoteRepo selected by the -- B9Config value _repository, or Nothing of no -- RemoteRepo was selected in the B9Config. newtype SelectedRemoteRepo MkSelectedRemoteRepo :: Maybe RemoteRepo -> SelectedRemoteRepo [fromSelectedRemoteRepo] :: SelectedRemoteRepo -> Maybe RemoteRepo -- | Alias for a Reader Effect that reads a list of -- RemoteRepos. type RepoCacheReader = Reader RepoCache data Repository Cache :: Repository Remote :: String -> Repository -- | Convert a RemoteRepo down to a mere Repository toRemoteRepository :: RemoteRepo -> Repository -- | Ask for the RepoCache initialized by withRemoteRepos. getRepoCache :: Member RepoCacheReader e => Eff e RepoCache -- | Run a SelectedRemoteRepoReader with the -- SelectedRemoteRepo selected in the B9Config. -- -- If the selected repo does not exist, and exception is thrown. withSelectedRemoteRepo :: (Member B9ConfigReader e, Member ExcB9 e) => Eff (SelectedRemoteRepoReader : e) a -> Eff e a -- | Ask for the RemoteRepo selected by the B9Config value -- _repository. See withSelectedRemoteRepo. getSelectedRemoteRepo :: Member SelectedRemoteRepoReader e => Eff e SelectedRemoteRepo -- | Return the cache directory for a remote repository relative to the -- root cache dir. remoteRepoCacheDir :: RepoCache -> String -> FilePath -- | Return the local repository directory. localRepoDir :: RepoCache -> FilePath -- | Select the first RemoteRepo with a given repoId. lookupRemoteRepo :: Set RemoteRepo -> String -> Maybe RemoteRepo -- | Filter the SharedImages returned by getSharedImages -- using a Repository-, and a SharedImage predicate. filterRepoImagesMap :: (Repository -> Bool) -> (SharedImage -> Bool) -> RepoImagesMap -> RepoImagesMap -- | Return the versions of a shared image named name from the -- local cache. lookupCachedImages :: SharedImageName -> RepoImagesMap -> Set SharedImage -- | Return a Set of Repository names from a -- RepoImagesMap allRepositories :: RepoImagesMap -> Set Repository -- | Get a Set of all SharedImages in all Repositorys. allSharedImages :: RepoImagesMap -> Set SharedImage -- | Fetch all SharedImages like allSharedImages but attach -- the Repository that the image belongs to. -- -- Usage example: In combination with filterRepoImagesMap to find -- the latest version of a certain image in all known repositories. allSharedImagesWithRepo :: RepoImagesMap -> Set (SharedImage, Repository) -- | Return the maximum with regard to the Ord instance of -- SharedImage from an RepoImagesMap maxSharedImageOfAllRepos :: RepoImagesMap -> Maybe (SharedImage, Repository) -- | Return the SharedImages, that are contained in a -- Repository. allSharedImagesInRepo :: Repository -> RepoImagesMap -> Set SharedImage -- | Keep SharedImages that are in the Cache -- Repository. allCachedSharedImages :: RepoImagesMap -> Set SharedImage -- | Take a subset that contains the n latest versions of -- SharedImages with the same name. -- -- For example, if the input contains: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:31" , -- SharedImage "foo" "2020-07-07 13:34:32" , SharedImage "foo" -- "2020-07-07 13:34:33" , SharedImage "bar" "2020-07-07 13:34:34" , -- SharedImage "bar" "2020-07-07 13:34:35" , SharedImage "bar" -- "2020-07-07 13:34:36" ] @@ -- -- The output of keepNLatestSharedImages 2 will be: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:32" , -- SharedImage "foo" "2020-07-07 13:34:33" , SharedImage "bar" -- "2020-07-07 13:34:35" , SharedImage "bar" "2020-07-07 13:34:36" ] -- @@ keepNLatestSharedImages :: Int -> Set SharedImage -> Set SharedImage -- | Take a subset that contains obsolete images. -- -- Do the opposite of keepNLatestSharedImages, and return all -- **but** the n latest versions of SharedImages with the -- same name. -- -- For example, if the input contains: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:31" , -- SharedImage "foo" "2020-07-07 13:34:32" , SharedImage "foo" -- "2020-07-07 13:34:33" , SharedImage "bar" "2020-07-07 13:34:34" , -- SharedImage "bar" "2020-07-07 13:34:35" , SharedImage "bar" -- "2020-07-07 13:34:36" ] @@ -- -- The output of keepNLatestSharedImages 2 will be: -- -- @@ fromList [ SharedImage "foo" "2020-07-07 13:34:31" , -- SharedImage "bar" "2020-07-07 13:34:34" ] @@ dropAllButNLatestSharedImages :: Int -> Set SharedImage -> Set SharedImage -- | Group by SharedImageName. groupBySharedImageName :: Set SharedImage -> Map SharedImageName (Set SharedImage) -- | Convenience type alias for Effects that have a B9Config, -- a Logger, MonadIO and MonadBaseControl. type CommandIO e = (MonadBaseControl IO (Eff e), MonadIO (Eff e), Member LoggerReader e, Member B9ConfigReader e) -- | Effect that reads a Logger. type LoggerReader = Reader Logger -- | The logger to write log messages to. newtype Logger MkLogger :: Maybe Handle -> Logger [logFileHandle] :: Logger -> Maybe Handle -- | Lookup the selected getLogVerbosity and _logFile from -- the B9Config and open it. -- -- Then run the given action; if the action crashes, the log file will be -- closed. withLogger :: (MonadBaseControl IO (Eff e), MonadIO (Eff e), Member B9ConfigReader e) => Eff (LoggerReader : e) a -> Eff e a traceL :: CommandIO e => String -> Eff e () dbgL :: CommandIO e => String -> Eff e () infoL :: CommandIO e => String -> Eff e () errorL :: CommandIO e => String -> Eff e () errorExitL :: (CommandIO e, Member ExcB9 e) => String -> Eff e a b9Log :: CommandIO e => LogLevel -> String -> Eff e () printHash :: Hashable a => a -> String -- | Type alias for a BuildInfo Reader type BuildInfoReader = Reader BuildInfo -- | Create the build directories, generate (hash) the build-id and execute -- the given action. -- -- Bindings added to the text template parameter environment: -- --
-- Let [ ... bindings ... ] -- [ Sources -- [ ... list all input files ... ] -- [ Artifact ... -- , Artifact ... -- , Let [ ... ] [ ... ] -- ] -- ] ---- -- The reasons why Sources takes a list of -- ArtifactGenerators is that -- --
-- LetX [("x", ["1","2","3"]), ("y", ["a","b"])] [..]
--
--
-- Is equal to:
--
--
-- Let [] [
-- Let [("x", "1"), ("y", "a")] [..]
-- Let [("x", "1"), ("y", "b")] [..]
-- Let [("x", "2"), ("y", "a")] [..]
-- Let [("x", "2"), ("y", "b")] [..]
-- Let [("x", "3"), ("y", "a")] [..]
-- Let [("x", "3"), ("y", "b")] [..]
-- ]
--
--
-- @deprecated TODO remove this when switching to Dhall
LetX :: [(String, [String])] -> [ArtifactGenerator] -> ArtifactGenerator
-- | Bind each variable to their first value, then each variable to the
-- second value, etc ... and execute the nested generator in every step.
-- LetX represents a product of all variables, whereas Each
-- represents a sum of variable bindings - Each is more like a
-- zip whereas LetX is more like a list comprehension.
-- @deprecated TODO remove this when switching to Dhall
Each :: [(String, [String])] -> [ArtifactGenerator] -> ArtifactGenerator
-- | The transposed version of Each: Bind the variables in the first
-- list to each a set of values from the second argument; execute the
-- nested generators for each binding @deprecated TODO remove this when
-- switching to Dhall
EachT :: [String] -> [[String]] -> [ArtifactGenerator] -> ArtifactGenerator
-- | Generate an artifact defined by an ArtifactAssembly; the
-- assembly can access the files created from the Sources and
-- variables bound by Letish elements. An artifact has an instance
-- id, that is a unique, human readable string describing the artifact to
-- assemble.
Artifact :: InstanceId -> ArtifactAssembly -> ArtifactGenerator
EmptyArtifact :: ArtifactGenerator
-- | The variable containing the instance id. Deprecated
instanceIdKey :: String
-- | The variable containing the buildId that identifies each execution of
-- B9. For more info about variable substitution in source files see
-- StringTemplate
buildIdKey :: String
-- | The variable containing the date and time a build was started. For
-- more info about variable substitution in source files see
-- StringTemplate
buildDateKey :: String
-- | Return the files that the artifact assembly consist of.
getAssemblyOutput :: ArtifactAssembly -> [AssemblyOutput]
buildWithVm :: IsB9 e => InstanceId -> [ImageTarget] -> FilePath -> VmScript -> Eff e Bool
data InstanceGenerator e
IG :: InstanceId -> e -> ArtifactAssembly -> InstanceGenerator e
-- | Internal data structure. Only exposed for unit testing.
data InstanceSources
InstanceSources :: Environment -> [ArtifactSource] -> InstanceSources
[isEnv] :: InstanceSources -> Environment
[isSources] :: InstanceSources -> [ArtifactSource]
-- | Execute an ArtifactGenerator and return a B9Invocation
-- that returns the build id obtained by getBuildId.
buildArtifacts :: ArtifactGenerator -> B9 String
-- | Return a list of relative paths for the local files to be
-- generated by the ArtifactGenerator. This excludes Shared and
-- Transient image targets.
getArtifactOutputFiles :: ArtifactGenerator -> Either SomeException [FilePath]
-- | Run an artifact generator to produce the artifacts.
assemble :: ArtifactGenerator -> B9 [AssembledArtifact]
-- | Interpret an ArtifactGenerator into a list of simple commands,
-- i.e. InstanceGenerators
runArtifactGenerator :: Environment -> String -> String -> ArtifactGenerator -> Either SomeException [InstanceGenerator [TextFileWriter]]
-- | Run an
runInstanceGenerator :: IsB9 e => InstanceGenerator FilePath -> Eff e AssembledArtifact
-- | Create the ArtifactTarget from an ArtifactAssembly in
-- the directory instanceDir
runArtifactAssembly :: IsB9 e => InstanceId -> FilePath -> ArtifactAssembly -> Eff e [ArtifactTarget]
-- | A crude, unsafe and preliminary solution to building B9
-- SharedImages from Shake.
module B9.Shake.SharedImageRules
-- | Specify an arbitrary action that is supposed to build the given shared
-- image identified by a SharedImageName. NOTE: You must call
-- enableSharedImageRules before this action works.
customSharedImageAction :: HasCallStack => SharedImageName -> Action () -> Rules ()
-- | Add a dependency to the creation of a SharedImage. The build
-- action for the shared image must have been supplied by e.g.
-- customSharedImageAction. NOTE: You must call
-- enableSharedImageRules before this action works.
needSharedImage :: HasCallStack => SharedImageName -> Action SharedImageBuildId
-- | In order to use needSharedImage and
-- customSharedImageAction you need to call this action before
-- using any of the aforementioned Rules.
enableSharedImageRules :: HasCallStack => B9ConfigOverride -> Rules ()
-- | Convenient Shake Actions for B9 rules.
module B9.Shake.Actions
-- | Convert a B9ConfigAction action into a Shake Action.
-- This is just an alias for runB9ConfigActionWithOverrides since
-- Action is an instance of MonadIO and
-- runB9ConfigActionWithOverrides work on any .
b9InvocationAction :: HasCallStack => B9ConfigAction a -> B9ConfigOverride -> Action a
-- | An action that does the equivalent of b9c build -f b9file
-- -- (args !! 0) (args !! 1) ... (args !! (length args - 1)) with
-- the current working directory changed to b9Root. The return
-- value is the buildid, see getBuildId
buildB9File :: HasCallStack => FilePath -> FilePath -> [String] -> Action String
-- | A module that re-exports all B9 Shake integration. Which by the way is
-- crude and preliminary...
module B9.Shake