0

If I have a DUB-based project with an optional dependency, how to I make it so that some code (be it modules or a version(...){...} block) only gets compiled if the dependency is chosen? Is there a way I can make a version identifier defined based on whether the dependency is present or absent?

I have already read about the "optional" and "default" attributes of the "dependency" tag as documented here. This allows me to define a dependency as optional, but it lacks teeth if I can't version my code to reflect the dependencies chosen.

chadjoan
  • 485
  • 3
  • 11

2 Answers2

2

Maybe you can, I am not sure but it seems you can use something like this:

version(Have_name_of_dependency)

So if your optional dependency would be sdlang-d you could use

Have_sdlang_d

Same as here

This is based on this part of dub code

Kozzi11
  • 2,413
  • 12
  • 17
  • I think you nailed it. Thanks! I was able to build the project without the dependency by removing it from dub.selections.json and using the version(Have_*) code you suggested. Unfortunately other projects that depend on that project still insist on including the optional dependency (ex: sdlang-d) in their dependency graph, despite the default=false in the first project and sdlang-d being absent from every dub.selections.json file involved. But that seems like a different problem... maybe a bug or another question to be asked. – chadjoan Aug 16 '17 at 13:55
  • you should use optional=true – Kozzi11 Aug 16 '17 at 15:14
  • optional=true was (already) set as well; sorry I assumed it was implicit. – chadjoan Aug 16 '17 at 16:56
0

Besides using a version(foo) block and asking people to use versions: "foo" in their dub.sdl, you have one other option. It's cruddy, but it would work.

If your code is a template, you can wrap the relevant stuff in:

template HasVibe() 
{
    enum HasVibe = 
        is(typeof(() { import vibe.d; } ));
}

template Foo(T) if (HasVibe!())
{
    // your code here
}

If it's not a template, you can turn it into a template:

template log() if (HasVibe!())
{
    import vibe.core.log : logDebug;
    alias log = logDebug;
}

Untested, but it might help in a pinch.

dhasenan
  • 1,177
  • 7
  • 15