casey / just

🤖 Just a command runner
https://just.systems
Creative Commons Zero v1.0 Universal
20.59k stars 453 forks source link

How to compare numbers outside of recipe context? #2080

Open zekefast opened 4 months ago

zekefast commented 4 months ago

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:

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

Thank you in advance!

laniakea64 commented 4 months ago

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?

zekefast commented 4 months ago

@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.