1

I often find myself switching to a specific version of a package installed with homebrew when switching projects.

$ cd ~/Desktop/projects/project1
$ brew switch phantomjs 2.0.0
Cleaning /usr/local/Cellar/phantomjs/1.9.7_1
Cleaning /usr/local/Cellar/phantomjs/1.9.8
Cleaning /usr/local/Cellar/phantomjs/2.0.0
2 links created for /usr/local/Cellar/phantomjs/2.0.0

And then when changing project:

$ cd ~/Desktop/projects/project2
$ brew switch phantomjs 1.9.8
Cleaning /usr/local/Cellar/phantomjs/1.9.7_1
Cleaning /usr/local/Cellar/phantomjs/1.9.8
Cleaning /usr/local/Cellar/phantomjs/2.0.0
2 links created for /usr/local/Cellar/phantomjs/1.9.8

Is it somehow possible to automate this so that I can force brew to automatically switch to a specified version when inside a certain project?

Would be nice if one could create a file called something like .homebrewinside the target directory and from there specify required packages and versions.

1

To directly answer your question: take a look at ondir. I have not personally used it, but it appears to fit your use case.

ondir is a small program to automate tasks specific to certain directories. It works by executing scripts in directories when you enter and leave them.

To ruminate for a moment, though...

Swapping out package versions on enter/exit of dirs via the shell is, well, risky for a variety of reasons. (For starters, think about two terminal sessions, each in their own dir.)

What you're asking for (per-dir homebrew config) is effectively a virtual machine or container, since it goes beyond "virtualizing" a language (ex: Ruby via rbenv, Python via virtualenv`) and instead is for all system packages. You should consider setting up a Vagrant box for your projects to properly isolate them from your Mac and manage your dependencies better.

Anyway, back to your problem at hand...

PhantomJS is a standalone tool that happens to be helpfully available as a statically linked binary. We can use this to our advantage. Instead of swapping PhantomJS versions via brew switch, just download each statically linked version, stick the binary in ~/bin, name it appropriately (e.g. phantomjs-1.9.8), and adjust your scripts to call the desired version. If you can't adjust the scripts, you'll need to devise another scheme (project-specific symlinks, etc.)

Or, as suggested in your query on GitHub, you could also adjust your PATH, either via ondir or a wrapping script around whatever drives phantomjs.

(Yes, for the second time in one night I pointed someone to a tool I have not personally used.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.