Cabal is something of a Swiss army knife in the Haskell ecosystem, and it serves several purposes, including: package and dependency management, building, and running your program. In this section, we’ll take a quick tour of these features and you’ll learn how to get started using cabal to define a new project, manage dependencies, and build the project.
| Your Output Might Look Different |
|---|
|
| This chapter contains some example output you might see when creating new projects with cabal. Since cabal is getting active updates to add new features, you might notice minor differences between the examples here and the output you see when you follow along. Don’t worry though, even though some things will change as cabal improves, the examples in this chapter should continue to work as expected for a long time, even if the output you see from the tool changes a bit. |
Using Cabal as a Haskell Package Manager
Cabal works as a package manager and you can use it to manage Haskell libraries and applications. You can install libraries and applications for your user with cabal by running cabal install . For example, let’s install the stylish-haskell that will let you automatically format your Haskell source files. Start by running cabal update to update the package cache. This tells cabal what packages and versions are available for you to install:
| | user@host$ cabal update |
| | Downloading the latest package list from hackage.haskell.org |
| | To revert to previous state run: |
| | cabal v2-update 'hackage.haskell.org,2020-10-13T23:04:28Z' |
| | user@host$ cabal install stylish-haskell |
When you run cabal install , cabal will download and compile the latest version of the application for you. The resulting binary will be available in ${HOME} /.cabal/bin . It’s a good idea to add that path to your environment’s default search path. For example, you can add the following to your .bashrc file if you are using bash on a *nix system:
| | export PATH= ${ HOME } /.cabal/bin: ${ PATH } |
You can also install Haskell libraries on your system with cabal by passing it the --lib flag. For example, you can install the very popular text library with cabal:
| | user@host$ cabal install --lib text |
Most of the time you’ll manage dependencies and install libraries on a per-project basis, and won’t need to install packages directly like this, however, it may be handy if you want to ensure some libraries are always available for quickly writing small scripts for doing ad hoc work in ghci .
Starting a Cabal Project
The way you’ll use cabal most of the time is for building and running projects that are managed using cabal. When you’re creating a new project, you can use cabal to initialize the project by running cabal init .
To see all the options available when running cabal init you can run:
| | user@host$ cabal help init |
There are a lot of options, but for now we’ll just pass in the --interactive flag. Let’s walk step by step through each prompt to understand what cabal is asking. These examples come from cabal version 3.2.0.0 . The text might look slightly different if you’re using a newer version of cabal.
| | user@host$ mkdir learn-cabal |
| | user@host$ cd learn-cabal |
| | user@host$ cabal init --interactive |
| | Should I generate a simple project with sensible defaults? [default: y] n |
| | What does the package build: |
| | 1) Executable |
| | 2) Library |
| | 3) Library and Executable |
| | Your choice? 3 |
This first prompt is asking you what kind of project you’d like to create. For libraries, pick the Library option. If you’re building an application, however, it’s common to use the Library and Executable project rather than just Executable . This supports the common Haskell idiom of creating a very small minimal executable application and putting most of the application logic in a library. Separating out the logic into a library makes testing easier.
| | What is the main module of the executable: |
| | * 1) Main.hs (does not yet exist, but will be created) |
| | 2) Main.lhs (does not yet exist, but will be created) |
| | 3) Other (specify) |
| | Your choice? [default: Main.hs (does not yet exist, but will be created)] 1 |
The next option you are presented with asks you what the name of the Main module should be for your application. By convention this is named Main and may be a regular Haskell source file called Main.hs or a literate Haskell file named Main.lhs . You can also select your own filename if you choose ( App.hs is a popular alternative). We won’t cover literate Haskell in this book, so go ahead and select the default option to create a file named Main.hs .
| | Please choose version of the Cabal specification to use: |
| | * 1) 1.10 (legacy) |
| | 2) 2.0 (+ support for Backpack, internal sub-libs, '^>=' operator) |
| | 3) 2.2 (+ support for 'common', 'elif', redundant commas, SPDX) |
| | 4) 2.4 (+ support for '**' globbing) |
| | Your choice? [default: 1.10 (legacy)] 4 |
Now you are given an option to select which type of cabal configuration file you want to use. The default option here is the legacy cabal file format, which is the most widely supported option and is a good choice if you don’t need newer features. In this chapter, you’ll be learning about newer cabal features, so go ahead and select the most recent option:
| | Package name? [default: learn-cabal] learn-cabal |
The next prompt gives you a chance to name your package. The default package name is the name of the current working directory. You can select the default here or pick a different package name:
| | Package version? [default: 0.1.0.0] 0.1.0.0 |
You can also pick an initial version number for your package. This should follow the Haskell Package Versioning Policy ( PVP ). The PVP uses a four-part numbering system, generation.major.minor.patch . Changes to the generation number indicate very large, perhaps philosophical, changes to the API design. Major version number changes indicate backwards-incompatible changes. Minor changes indicate backwards-compatible changes such as additions to the library or bugfixes. Patch level changes indicate that only bugfixes have been added. You can refer to the PVP documentation [3] for a detailed summary of the package versioning policy and how to use it when creating and publishing packages.
| | Please choose a license: |
| | 1) GPL-2.0-only |
| | 2) GPL-3.0-only |
| | 3) LGPL-2.1-only |
| | 4) LGPL-3.0-only |
| | 5) AGPL-3.0-only |
| | 6) BSD-2-Clause |
| | * 7) BSD-3-Clause |
| | 8) MIT |
| | 9) ISC |
| | 10) MPL-2.0 |
| | 11) Apache-2.0 |
| | 12) LicenseRef-PublicDomain |
| | 13) NONE |
| | 14) Other (specify) |
| | Your choice? [default: BSD-3-Clause] 7 |
After setting a version, you can choose a license for your application. You can choose one of the suggested options or pick your own. If you are picking your own license, cabal uses SPDX license identifiers. Most open source code in the Haskell community is released under the BSD-3 license. If you select a license that cabal knows about, it will automatically create a file named LICENSE that contains the text of the selected license.
| | Author name? [default: Haskell Programmer] Haskell Programmer |
| | Maintainer email? [default: [email protected]] [email protected] |
| | Project homepage URL? http://example.com |
| | Project synopsis? A sample project to learn how to use cabal |
The next several questions give you an opportunity provide your name and email address, along with a homepage for your project and a synopsis. If you don’t otherwise have a homepage for your project, it’s common to use a link to where the project is hosted, such as on github [4] or gitlab. [5] You can change these values later, so don’t worry if you don’t have a good synopsis or a homepage yet.
| | Project category: |
| | * 1) (none) |
| | 2) Codec |
| | 3) Concurrency |
| | 4) Control |
| | 5) Data |
| | 6) Database |
| | 7) Development |
| | 8) Distribution |
| | 9) Game |
| | 10) Graphics |
| | 11) Language |
| | 12) Math |
| | 13) Network |
| | 14) Sound |
| | 15) System |
| | 16) Testing |
| | 17) Text |
| | 18) Web |
| | 19) Other (specify) |
| | Your choice? [default: (none)] 1 |
The project category is used to help organize projects in Hackage. If any of the suggestions seem appropriate, select one, or you can choose none if nothing seems like a good fit.
| | Application (Main.hs) directory: |
| | * 1) (none) |
| | 2) src-exe |
| | 3) app |
| | 4) Other (specify) |
| | Your choice? [default: (none)] 3 |
| | Library source directory: |
| | * 1) (none) |
| | 2) src |
| | 3) lib |
| | 4) src-lib |
| | 5) Other (specify) |
| | Your choice? [default: (none)] 2 |
The next two questions will help cabal create the appropriate directories to organize your application. A common convention that you’ll see throughout the examples in this book is to use a directory called app to hold the source file for the executable portion of the application and a directory called src to hold the source code to the library portion of the application.
| | Should I generate a test suite for the library? [default: y] y |
Cabal can generate a test suite for you if you ask it to. This is a good way to make sure that there is less friction to writing tests as you start developing your application.
| | Test directory: |
| | * 1) test |
| | 2) Other (specify) |
| | Your choice? [default: test] 1 |
Just like the executable and library portions of your application, the directory where you store your test files is configurable. A directory named test is the most common choice.
| | What base language is the package written in: |
| | * 1) Haskell2010 |
| | 2) Haskell98 |
| | 3) Other (specify) |
| | Your choice? [default: Haskell2010] 1 |
Next you have the opportunity to select a language standard that should be used with your project. For all of the examples in this book you’ll want to select Haskell2010.
| | Add informative comments to each field in the cabal file (y/n)? [default: n] n |
| | |
| | Guessing dependencies... |
| | |
| | Generating LICENSE... |
| | Generating Setup.hs... |
| | Generating CHANGELOG.md... |
| | Generating src/MyLib.hs... |
| | Generating app/Main.hs... |
| | Generating test/MyLibTest.hs... |
| | Generating learn-cabal.cabal... |
| | |
| | You may want to edit the .cabal file and add a Description field. |
The final choice you’ll have to answer is whether or not you’d like the generated cabal configuration file to contain helpful comments. These comments can be a great way to learn more about the fields. In the example cabal file in the next section we’ll omit the comments, but you should try generating a file with the comments enabled to get a chance to read the documentation on what the fields are doing.
Understanding the Cabal File Format
Whether you are generating a file using cabal init or starting from scratch or an existing project, your cabal projects will need a cabal file. Cabal files use the .cabal extension, and by convention will share the name of your project.
In the last section, you should have generated a new cabal file named learn-cabal.cabal . It should look something like the example:
| | cabal-version: 2.4 |
| | -- Initial package description 'learn-cabal.cabal' generated by 'cabal |
| | -- init'. For further documentation, see |
| | -- http://haskell.org/cabal/users-guide/ |
| | |
| | name: learn-cabal |
| | version: 0.1.0.0 |
| | synopsis: A sample project to learn how to use cabal |
| | -- description: |
| | homepage: http://example.com |
| | -- bug-reports: |
| | license: BSD-3-Clause |
| | license-file: LICENSE |
| | author: Haskell Programmer |
| | maintainer: [email protected] |
| | -- copyright: |
| | -- category: |
| | extra-source-files: CHANGELOG.md |
| | |
| | library |
| | exposed-modules: MyLib |
| | -- other-modules: |
| | -- other-extensions: |
| | build-depends: base ^>=4.13.0.0 |
| | hs-source-dirs: src |
| | default-language: Haskell2010 |
| | |
| | executable learn-cabal |
| | main-is: Main.hs |
| | -- other-modules: |
| | -- other-extensions: |
| | build-depends: base ^>=4.13.0.0, learn-cabal |
| | hs-source-dirs: app |
| | default-language: Haskell2010 |
| | |
| | test-suite learn-cabal-test |
| | default-language: Haskell2010 |
| | type: exitcode-stdio-1.0 |
| | hs-source-dirs: test |
| | main-is: MyLibTest.hs |
| | build-depends: base ^>=4.13.0.0 |
In this section, you’ll learn about the syntax of cabal files and about some of the package properties and fields that are generated when you initialize a new cabal project. Most of the fields we’ll look at in this section relate to Haskell features you will learn about later in this book, so we’ll only touch briefly on them now, and we’ll revisit them later as the relevant features are introduced.
The generated cabal file is a good demonstration of the basic syntax of a cabal file. Most cabal files consist primarily of some top-level package properties along with some build target stanzas and target-level fields. The properties and fields are both key-value pairs separated by a colon:
| | key: value |
A cabal stanza, usually with a name, and some fields:
| | stanza-type name |
| | field-key-1: field-val-1 |
| | field-key-2: field-val-2 |
In most cases, the stanzas that you’ll see in a cabal file will refer to some build target. In our generated example, we have library , executable , and test-suite target stanzas. You’ll learn about some additional stanzas later in this book as you start to incorporate new features into your programs. You can refer to the cabal documentation [6] for a complete description of all of the stanzas and fields that are available.
Comments are also supported in cabal files. Like Haskell comments, cabal comments start with two dashes. A comment can start at the beginning of a line, or after indentation, but it can’t trail any other expressions:
| | -- This is a comment top level comment |
| | library |
| | -- this is an indented comment |
| | exposed-modules: MyLib -- This comment will cause an error |
At the top of the generated cabal file you’ll see several package-level properties that have been set based on the answers you gave during the initialization process. The name and version properties are the only two properties that are strictly required for all cabal files. For the generated example file, the cabal-version property is also required, since otherwise cabal will default to an earlier version of the cabal file format that doesn’t support all of the features used in the generated example.
Try running cabal init several times with different answers to the prompts, or generate the file with additional helpful comments, to get a complete description of all of the properties that are provided when you generate a new cabal file. Next we’ll turn our attention to the target stanzas and the fields that are set for them.
After the package-level properties, you can see we have three stanzas in the generated file, for each of the three targets that we can build. The first of these is the library stanza. The library target needs to be present when you’re building a library from your package. Unlike the other targets you’ll see later on in this section, the default library target doesn’t take a name parameter—the name of the library will always be the same as the name of your package. Newer versions of cabal do allow you to define some additional private libraries that can help you better organize your project, and those libraries must be named just like other targets.
Within the library target, you can see that we have a few fields already set, as well as a couple of optional fields that have been commented out.
| | library |
| | exposed-modules: MyLib |
| | -- other-modules: |
| | -- other-extensions: |
| | build-depends: base ^>=4.13.0.0 |
| | hs-source-dirs: src |
| | default-language: Haskell2010 |
The first two fields in the library target, exposed-modules and other-modules , are the only ones that are library specific. These fields are responsible for listing which parts of the library are public and available to all consumers of the library, and which parts are private to the library itself. The exposed-modules field is required and lists the publicly available parts of the library. other-modules is optional, and you can see that it’s been commented out in our example. This field will allow you to list parts of the library that are for internal use only. You’ll revisit these fields later on in this chapter once you’ve learned more about modules and added some to your example project.
other-extensions is another optional field that’s been added to the cabal file for us. It’s often used with another optional field, default-extensions . These fields let you configure language extensions you want to enable for an entire project. The default-extensions lists language features that you want to enable across the entire build target, and other-extensions lists the ones that you’ll want to enable on a case-by-case basis. Language extensions must be supported by a compatible compiler, and cabal may use these fields to solve for the minimal required compiler versions to build the package.
build-depends lists the libraries, internal or external, that the build target depends on. It’s a comma-separated list with an optional version restriction. For example, if you wanted to depend on any version of base along with the text and bytestring libraries you would set the field to:
| | build-depends: base |
| | , text |
| | , bytestring |
In some cases, you might not want to specify version dependencies in the cabal file. This might happen during active development when you want to make sure you’re always using the most up-to-date packages, when you’re using a freeze file to manage dependencies, or when an external tool is managing dependencies and versioning for you, for example, if you’re using nixpkgs to manage your build environment.
More often, especially for libraries that you’re going to publish, you’ll want to add version constraints to your dependencies. Version constraints help cabal download a compatible version of your dependencies when building your library and help make sure that all the dependencies in a project work together.
Cabal supports all of the usual equality and inequality operators for comparing versions: > , >= , \== , <= and < all work as you would expect, allowing you to require an exact version of a package, or depending on newer or older versions. For example to depend on base version 4.13.0.0 or newer you can write:
| | build-depends: base >=4.13.0.0 |
Hackage’s package versioning policy, the PVP, specifies that a change in the the two leftmost fields of a version number indicate backwards-incompatible changes. For example, going from version 1.0.0.0 to 2.0.0.0 would indicate a substantial redesign of the library, whereas going to version 1.1.0.0 would indicate that a small backwards-incompatible change has been introduced. Similarly, going to 1.0.1.0 or 1.0.0.1 should be a compatible change. This versioning policy means that it’s usual to depend on a range of compatible versions. You can combine version constraints using && or || , and so it’s common to see constraints like at least version 4.13.0.0, but less than 4.14 :
| | build-depends: base >=4.13.0.0 && < 4.14 |
This pattern is common enough in fact that cabal supports special syntax to express constraints like this. The so-called carrot operators limit a constraint to only the range of packages that should be compatible per the PVP guidelines. The constraint base ^>= 4.13.0.0 inequality in the example file is doing exactly that.
Changing How Your Program Gets Built
After adding dependencies and updating the list of modules you are providing, one of the most important things you’ll want to do in your cabal files is to configure the way ghc will build your programs. You can do this by adding options to the ghc-options field for each target in your cabal file. Here’s an example of a common set of compiler flags that you might enable by default in a library:
| | ghc-options: -O1 -Wall |
If you are compiling an executable program instead of a library, you might instead have this:
| | ghc-options: -O1 -threaded -rtsopts -with-rtsopts=-N |
The GHC manual [7] contains an extensive list of all of the flags that you can provide to fine-tune how your program is compiled. In this section, we’ll look at a couple of the most common options that you might want to configure for your programs. All of these flags can be set in the ghc-options field of your cabal file, or passed to GHC directly if you are compiling your program without cabal.
Optimizations
The most common option you’ll want to set when you compile your program is to turn on optimizations. Enabling optimizations will generally make your program run faster and possibly use less memory. You can control the level of optimization with the -O flag. If you don’t pass an optimization flag at all, or pass in -O0 , the compiler will not do any optimizations at all. The first optimization level, -O1 will turn on a number of individual optimization options. You can get even more optimizations, at the cost of slower compile times, by enabling -O2 . In most cases, you should enable -O1 when you start a new project. This will give you a good balance of performance and faster compile times. If you want better performance you should try -O2 and, then fine tune the specific set of optimizations later on a case-by-case basis if you have evidence that you need to enable or disable them.
Warnings and Errors
By default, Haskell is fairly conservative about the kinds of code that it will warn you about. The -Wall flag turns on many more warnings, making it easier to find potential bugs in your program. Although the “all” in -Wall might make you think this flag enables all warnings, it actually only enables common and safe warnings. You can enable every warning that GHC knows about by passing in -Weverything .
It’s a common practice in mature projects enable the -Werror flag. This flag will turn warnings into errors, meaning that your program will fail to compile if there are any warnings at all. Forcing yourself to fix any warnings before your program will compile can help improve the quality of your code in the long-run, but it can also slow you down enormously when you are actively developing code and find that you can’t load your code into ghci or run some tests until you fix all of the warnings in your project.
Profiling
Sometimes your program runs more slowly or requires more memory than you expect. In these situations, it can be helpful to profile your program to see how it’s being run. GHC supports profiling your programs at runtime, but to enable that feature you need to compile your program, and all of its dependencies, with profiling enabled. You can enable profiling for your particular target by adding the -prof option to GHC. If you want complete profiling information, you should also configure cabal to download the profiling information for all of your dependencies by running:
| | cabal configure --enable-profiling |
Building and Running Your Program
Once you have a cabal file written that defines what your project should look like, you can also use cabal to compile or run any target in your cabal file. For small projects like the ones you’ll build while working through this book, you can compile your applications by running cabal build . This is a quick way to compile all the targets in your cabal file to see if you have any errors. If you are missing any dependencies, cabal will download and install them for you when you compile your application.
For larger applications with long compile times, you can specify a single target from your cabal file. In some cases, like if you have an executable and library target with the same name, the name of the target by itself might be ambiguous, and so you need to give cabal some additional information by prefixing the target name with lib or exe :
| | user@host$ cabal build lib:learn-cabal |
| | Up to date |
| | user@host$ cabal build exe:learn-cabal |
| | Up to date |
After you’ve compiled an application you can run it with cabal exec . You’ll need to provide the name of an executable target to tell cabal which application you want to run. You can only run executable targets, so you don’t need to worry about prefixing your target names with exe :
| | user@host$ cabal exec learn-cabal |
| | Hello, Haskell! |
| | someFunc |
When you’re actively working on a project and iteratively testing your program, it’s inconvenient to have to compile and then run your program repeatedly. The cabal run command combines both compilation and execution into a single command, letting you easily run the latest version of your program:
| | user@host$ |
| | cabal run learn-cabal |
| | Up to date |
| | Hello, Haskell! |
| | someFunc |