neděle 3. července 2016

Tmux layout checksum

One of the things I was working on during Hackweek 14 was some simple tool used internally for building packages for customers with Level 3 support contract. That is not fun at all, but I needed to split terminal into smaller windows with different roles. I chose TMUX for that - to split the screen and show progress of the builds in its panes.

For some reason split-window command worked differently for session attached and detached. Yes, I specified window size, number of lines - all this and yet it was pain to use. The only working solution I found (without using frameworks for that) was using select-layout. Command list-windows can give you string representation of the layout which you can reuse later. Format is straightforward and let me specify all the things and then rearrange panes with one command. Beautiful.

In the beginning of the string there is also checksum of the layout so you can reuse just some valid layout which existed before. I don't like this approach as it only means that they were too lazy to implement layout validation. I'm not fan of preventing users from shooting into their leg so here you can have shell version of checksum calculation.

tmux_layout_checksum() {
    local layout="$1"
    local csum=0
    local i
    for i in $(seq 0 $((${#layout} - 1))); do
        let csum=$(((csum >> 1) + ((csum & 1) << 15)))
        let csum=$((csum + $(LC_CTYPE=C printf '%d' "'${layout:$i:1}")))
    done
    printf '%x' "$((csum & 0xffff))"
}
Now you can just create your $layout and call tmux set-layout "$(tmux_layout_checksum "$layout"),$layout".