Cabal:如何在同一个项目中配置传递构建依赖

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

我有一个 cabal 项目。它有库和测试目标。

测试目标依赖于库,因为它测试库的功能。

问题是,每当我向库添加包依赖项时(例如,cryptohash-sha1

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

和运行测试,我得到错误

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

我在这种情况下所做的是将相同的包添加到测试目标

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,

只有这样测试才会 运行。

我希望测试目标自动依赖库目标中的所有包。我该怎么做?

您可以使用一个名为 common stanzas 的 cabal 功能。您可以在以下博客中阅读更多相关信息 post:

使用这种方法,您可以将所有公共依赖项放在一个单独的节中,然后将其导入库和测试套件中:

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