ARAVINDA VISHWANATHAPURA

Building Crystal Programs with Source File Hash baked in

Jul 30, 2021
1 minute read.
crystal go hash source

This post is inspired by the blog post written by Pradeep Gowda about embedding Source file Hash while building Go programs.

The one issue with checking in the binary with source code is, you can’t be sure if the binary is built with the latest source that is adjacent to it.

I adopted a similar technique while building Crystal programs. This is much simpler with Crystal because of the macros.

hello.cr file
SOURCE_HASH = {{ `sha256sum #{__FILE__} | cut -d' ' -f1`.chomp.stringify }}

puts SOURCE_HASH

Build step:

$ crystal build hello.cr

Verify:

$ ./hello
cdb9db6f5ac4a0df1ed06de118c569fa225785685849d533c1ba550854b8b4ab
$ sha256sum hello.cr
cdb9db6f5ac4a0df1ed06de118c569fa225785685849d533c1ba550854b8b4ab  hello.cr

Similarly, if shards is used as the package manager for your Crystal Programs, then you can include the VERSION automatically while compiling the program.

VERSION = {{ `shards version #{__DIR__}`.chomp.stringify }}

puts VERSION

About Aravinda Vishwanathapura

Co-Founder & CTO at Kadalu Technologies, Creator of Sanka, Creator of Chitra, GlusterFS core team member, Maintainer of Kadalu Storage
Contact: Linkedin | Twitter | Facebook | Github | mail@aravindavk.in