just icon indicating copy to clipboard operation
just copied to clipboard

How to compare numbers outside of recipe context?

Open zekefast opened this issue 1 year ago • 2 comments

I would like to do some numbers comparison, specifically comparing numbers of cpus returned by num_cpus() function, but really have troubles with that.

Here is an example of justfile:

DEFAULT_THREADS = 8

threads := env('THREADS', DEFAULT_THREADS)

run:
  RUSTFLAGS="-Z threads={{ threads }}" cargo build

What I would like to is to replace logic in env('THREADS', DEFAULT_THREADS) to something like

env('THREADS', if num_cpus() > DEFAULT_THREADS { DEFAULT_THREADS } else { num_cpus() })

Moving that check to recipe context isn't an option as there are many recipes to update and for some of them the call is complex already.

What I tried:

  • resort to shell context with ``, but then I can't interpolate DEFAULT_THREADS and use num_cpus().
  • use another private just recipe for calculation in shell context and call it then env('THREADS', `just _do_calculation`), but just falls into recursive loop I think and I haven't found how to avoid it without passing even more extra parameters of setting and checking some flags.

Is it possible to do this or we have to add new things to just for that?

Thank you in advance!

zekefast avatar May 24 '24 14:05 zekefast

If you can use just master you can use shell() function to do the comparison in an external program.

Otherwise, or alternatively, maybe semver_matches() with fake semantic versions constructed from the numbers?

But I agree that proper numeric comparison would be a useful feature. Since everything is a string in just, it would probably have to be new function(s) for numeric comparison?

laniakea64 avatar May 24 '24 16:05 laniakea64

@laniakea64 Thank you a lot! We are using 1.26.0, so shell() is not available, but server_matches() does the trick. But yeah! It DOES look wild!

threads := env('THREADS', \
  if semver_matches('0.0.' + num_cpus(), '> 0.0.' + DEFAULT_THREADS) == 'true' { \
    DEFAULT_THREADS \
  } else { \
    num_cpus() \
  } \
)

But I agree that proper numeric comparison would be a useful feature. Since everything is a string in just, it would probably have to be new function(s) for numeric comparison?

It seems like it. At least this what I've though about as well once I discovered that numeric comparison is hard thing to do in just.

zekefast avatar May 24 '24 22:05 zekefast