Search code examples
haskellcabal

Cabal: How to configure transitive build-dependencies in the same project


I have a cabal project. It has library and test targets.

Test target depends on library because it tests the library's functionalities.

The problem is, whenever I add a package dependency to library (say, cryptohash-sha1)

library Lib
  exposed-modules:     Lib
  other-extensions:    DeriveGeneric
  build-depends:       base >=4.13 && <4.14,
                       cryptohash-sha1,

and run the test, I get error

Could not load module ‘Crypto.Hash.SHA1’.
It is a member of the hidden package ‘cryptohash-sha1-0.11.100.1’.
Perhaps you need to add ‘cryptohash-sha1’ to the build-depends in your .cabal file

What I do in this situation is to add the same package to test target

test-suite json-generator-test
  hs-source-dirs:      test, src
  main-is:             Test.hs
  other-modules:       Lib
  build-depends:       base >=4.13 && <4.14
                       cryptohash-sha1,

Only then the test would run.

I want test target to automatically depend on all the packages from library target. How can I do that?


Solution

  • You can use a cabal feature called common stanzas. You can read more about it in the following blog post:

    With this approach, you can put all common dependencies in a separate stanza, and just import it in both the library and test suite:

    common common-dependencies
      build-depends: base >=4.13 && <4.14
                   , cryptohash-sha1
    
    library Lib
      import:              common-dependencies
      exposed-modules:     Lib
      other-extensions:    DeriveGeneric
    
    test-suite json-generator-test
      import:              common-dependencies
      hs-source-dirs:      test, src
      main-is:             Test.hs
      other-modules:       Lib