RuboCop caching and cache misses in a Bitbucket pipeline
Don’t you love a fast, smooth-running, and reliable CI? I do too. On our Ruby on Rails backend we run RuboCop and of course we had it running with cache because no CI should waste minutes on something that only affects the few files from the last commit. We had it set up nicely, it ran fast – after a few days it didn’t – then it did again. Let’s walk through the quirks and pitfalls of using RuboCop’s cache in a Bitbucket pipeline and what can cause cache misses.
First of all, caches live for just seven days in Bitbucket’s pipeline. After that, they are deleted. You’ll notice the Cache "rubocop: rubocop_cache": Not found message in the Build setup and the step will create new files that the pipeline will store in cache during the Build teardown. You can manually delete caches via the pipeline list view.
Now the thing with RuboCop – which you can try to figure out from their docs on Cache Validity – is that the cache creates subdirectories named after RuboCop’s current config signature. You can have hundreds of old subfolders in rubocop_cache/, but the signature must match. Hence the many misses we had! Sadly it doesn’t come with a list of filenames, which we need for Bitbucket’s cache key.
Bitbucket pipeline cache misses
- Most important on that list for the cache key files: they must be files from your code repository and not files created during runtime.
- Just because RuboCop on a second run adds another subdirectory to
rubocop_cache/doesn’t mean Bitbucket will help you: caches are created just once and never updated. - You can’t just create a file in the pipeline and use that for the key. So, we really do need a sensible list of files. The four paths in the snippet below covered it for us. If you don’t have custom cops, remove the
lib/rubocop/**/*.rbone.
Snippet for your bitbucket-pipeline.yml
I didn’t find a snippet for it anywhere on the internet, so here’s the one soaked in my sweat, tears, and blood.
caches:
rubocop:
path: rubocop_cache
key:
files:
- .rubocop.yml
- .ruby-version
- Gemfile.lock
- lib/rubocop/**/*.rb
In your steps, you might have to run it with --cache-root . as RuboCop likes to use funny directories like $HOME/.cache. Just run rubocop --cache --cache-root . to keep the directory names aligned.
A final note: Don’t forget to add rubocop_cache to the Exclude list under AllCops in your .rubocop.yml configuration.
