Today I Learned

hashrocket A Hashrocket project

225 posts about #workflow surprise

Easily connect to postgres via proxy with service

A client has their RDS postgresql databases locked down to only allow connection from their EC2 instances. I found an easy way to connect with my local clients.

Add a local forward to ssh config

In ~/.ssh/config add something like

Host prod.client
  User ubuntu
  Hostname prod-ec2-instance.example.com
  LocalForward localhost:5433 rds-gibberish.us-west-1.rds.amazonaws.com:5432
  IdentityFile ~/production-ec2-key.pem

Add the credentials to pg service

In ~/.pg_service.conf save the user, database name, and password

[client-prod]
host=localhost
port=5433
user=rds-user
dbname=client-production
password=blablabla

Now you can start your ssh tunnel in 1 terminal:

ssh prod.client

And connect with any postgres client tool (pg_dump, psql, etc.) in another:

psql service=client-prod

warning

Well you just saved a production password to a plain text file, and now you can easily connect and muck things up in production. Make sure your machine is secure and be careful and stuff.

Android crash logs

You can get android crash logs with adb

adb logcat --buffer=crash 

03-30 07:53:59.221 23769 23769 E AndroidRuntime: FATAL EXCEPTION: main
03-30 07:53:59.221 23769 23769 E AndroidRuntime: Process: expo.modules.mymodule.example, PID: 23769
03-30 07:53:59.221 23769 23769 E AndroidRuntime: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
03-30 07:53:59.221 23769 23769 E AndroidRuntime: 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:448)
03-30 07:53:59.221 23769 23769 E AndroidRuntime: 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
03-30 07:53:59.221 23769 23769 E AndroidRuntime: Caused by: java.lang.reflect.InvocationTargetE

Chrome has a command palette

I had no idea that Google Chrome had a command palette!

Once your dev tools are open, you can activate through the interface by clicking the 'more' icon and then 'Run command' like so:

or by cmd+shift+p (on a mac). Coincidentally this is the same keyboard shortcut as the command palette in Visual Studio Code

Now you'll see the palette which gives you direct access to a lot of Chrome's hidden functionality!

image

Duplicating tabs in iTerm

If you want to open a new tab in iTerm in your same working directory, you can use the following steps:

  1. Navigate to preferences or use (⌘,).
  2. Click on the Keys settings.
  3. Hit + in the bottom left corner to add a new shortcut.
  4. Record a shortcut of your choosing
  5. Using the dropdown menu for Action: select 'Duplicate Tab"

Now your new shortcut will open a new iTerm tab in whatever directory you have currently open.

Saving screenshots to clipboard on Mac

Have you ever needed to take a screenshot just to send it to somebody, but then you are left with the cumbersome chore of having to actually delete the screenshot before they pile up on your desktop like a pile of dirty laundry?

Well, I am here to save you those 5 seconds you've been missing out on so you can enjoy that next sip of coffee--guilt free.

When taking a screenshot with CMD + shift + 3, hold down control as well.

When taking a screenshot with CMD + shift + 4, hold down control while dragging the crosshairs to select a section of screen to capture.

Now, instead of saving to your default screenshot location, it will just copy it to your clipboard. You can now just paste the image into your message with no cleanup necessary.

TL;DR
Hold down control when taking a screenshot to copy it to the clipboard.

Use encrypted env vars with direnv

Direnv can execute shell scripts, so given that your env file is encrypted, you can automatically have it become decrypted for you:

───────┬──────────────────────
       │ File: .env
───────┼──────────────────────
   1   │ STRIPE_PK="123456789"
   2   │ API_KEY="qwertyuiop"
───────┴──────────────────────

Say is was encrypted:

ansible-vault encrypt --vault-password-file config/master.key .env
cat .env
───────┬─────────────────────────────────────────────────────────────────────────────────
       │ File: .env
───────┼─────────────────────────────────────────────────────────────────────────────────
   1   │ $ANSIBLE_VAULT;1.1;AES256
   2   │ 35306466356632363334643432343132356662376462333964366534393462366333623764336161
   3   │ 6131336435323834623539323462626235383330346562660a323534656133653237656634346235
   4   │ 30653635663438313931393966383266663535313361613339396234373164323830373262633661
   5   │ 6262356131306530350a643362623636323762656132326363323736633431396463616137343139
   6   │ 66666438623230333636373563393165333562633964616536663363323334343235386465346663
   7   │ 3365643263643766323835356230636539353034643034346136
───────┴─────────────────────────────────────────────────────────────────────────────────

Now that we have an encrypted .env file, we just need direnv to decrypt it whenever we're in our directory:

───────┬────────────────────────────────────────────────────────────────────────────────────────────────
       │ File: .envrc
───────┼────────────────────────────────────────────────────────────────────────────────────────────────
   1   │ export $(ansible-vault decrypt --vault-password-file config/master.key --output - .env | xargs)
───────┴────────────────────────────────────────────────────────────────────────────────────────────────

Output:

$ cd rails_app
direnv: loading ~/dev/rails_app/.envrc
direnv: export +API_KEY +STRIPE_PK
echo $API_KEY
qwertyuiop

Now whenever we enter the directory, we will have the unencrypted env vars, but the file remains encrypted on disk. For whatever that's worth.

Resize Window Keyboard Shortcuts in Windows 10

After using Magnet, a window manager in OSX, I remembered hearing that there was a similar facility built into Windows. Turns out, they are very easy-to-remember shortcuts for resizing windows.

  • Win + Right Arrow - Snap to right half of screen**
  • Win + Left Arrow - Snap to left half of screen**
  • Win + Up Arrow - Maximize current window
  • Win + Down Arrow - Minimize window if not currently maximized

**(will maximize the window if it is currently split on the opposite side of the screen)

There's a few others too, but these 4 I'm finding super useful. If you're interested in other Windows shortcuts, I found some other cool ones in this Lifewire article

Keep 5 most recent files in a directory

One can keep the most recent n files in a directory with just three shell programs: ls, tail, and xargs.

Here is an example to use in a nightly database backup cron job:

#!/bin/bash
# Keep last 5 files ending in .dump
# Don't forget to 

# Installation
# 1. cp pg-backups.sh /usr/local/bin/
# 2. chmod u+x /usr/local/bin/pg-backups.sh
# 3. Set the DB variable
# 4. Set the BACKUP_DIR variable

# Example usage for cron to run at 4:05 am every day:
# 5 4 * * * /usr/local/bin/pg-backups.sh

DB=mydatabase
BACKUP_DIR=/mnt/object/production/db-backups

DATE=$(date "+%Y-%m-%d_%H%M")
pg_dump -Fc $DB > $BACKUP_DIR/$DATE.dump

/bin/ls -t $BACKUP_DIR/*.dump | tail +6 | xargs rm

How to install sqlite3 on heroku

Using sqlite to persist data is superfluous on heroku, duh, but sometimes a third party service wants my rails app to read configuration in a sqlite db file. In order to read the read-only database file, I need to install the sqlite3 gem. To get this to work on heroku I needed to do two things:

  1. Install the apt buildpack
  2. Add an Aptfile in the root of the project
heroku buildpacks:add --index 1 heroku-community/apt

Then create an apt file:

# Aptfile
libsqlite3-dev
libsqlite3-0

Enable key repeat in VSCode

Even if your operating system enables key repeat, VSCode will disable it. To turn it on you need to update a default value and restart vscode:

defaults write com.microsoft.VSCode ApplePressAndHoldEnabled -bool false
osascript -e 'tell application "Visual Studio Code" to quit'
osascript -e 'tell application "Visual Studio Code" to activate'

Disable broken VSCode feature

TL;DR in the command palette choose "Workspaces: Configure Workspace Trust" and change "Start Prompt" to "never"

VSCode has a nice security feature warning about the risks of unknown file authors, but it is too naive to be useful; it actually has the reverse effect of being insecure (due to the fact most of these folders have been used in vscode for years before this feature was introduced). For example, I have over 200 projects on my machine:

ls ~/dev | wc -l
     213

The start prompt is simply training me to continually click "Yes I trust this code" over and over again, not only does this have no effect, but actually has a negative effect of making VSCode think I gave careful consideration to the folder, when instead, I was just trying to open my files.

List cli xcodebuild archives in Xcode's organizer

When using a Makefile to build Xcode applications, it's nice to have the archives listed in the Organizer window, for easy distribution. This can be accomplished with the -archivePath flag, using a specific directory:

BOB_THE_BUILD_DIR="~/Library/Developer/Xcode/Archives/$(date +%Y-%m-%d)"
ARCHIVE_PATH="$BOB_THE_BUILD_DIR/MyApp-$(date|md5).xcarchive"

xcodebuild -scheme MyApp -workspace "MyApp.xcworkspace" archive -configuration release -archivePath "$ARCHIVE_PATH"

How using fzf in new places rocks

Thanks to joshbranchaud and gabrielreis for these:

Fuzzy git checkout (alias in git config):

[alias]
    fco = !git branch | fzf +m | awk '{print $1}' | xargs git checkout

Then just use git fco and get an interactive fzf session to look through the available branches!

Fuzzy rails routes:

rails routes | fzf

Fuzzy search your routes without needing to run rails routes multiple times!

About cool ways to use file marks

File marks in vim are just marks made with [A-Z]. They have the delightful property that they persist (via .viminfo) across sessions without needing a session (depending on your settings). I've known about them for a while, but I wasn't sure if there was really a way that I could come up with the use them. So I went out looking and found something that I like!

`T -> project todo file
`V -> .vimrc

I'll probably come up with some other ideas based on the invariant files that I frequently visit, but these two are definitely going into my rotation. I'm also thinking that at least one more should be added:

`L -> TIL file (ABT - always be TILin)

cReddit where credit is due

About nvim SHADA (Shared Data) file and Sessions

Ever stop your vim and get really depressed that you just lost your buffers? Cause I've done it twice today. The relevant details about sessions:

   The following command creates a session file:

	:mksession vimbook.vim

Later if you want to restore this session, you can use this command:

	:source vimbook.vim

If you want to start Vim and restore a specific session, you can use the
following command:

	vim -S vimbook.vim

This tells Vim to read a specific file on startup.  The 'S' stands for
session (actually, you can source any Vim script with -S, thus it might as
well stand for "source").

Your sessionoptions needs to include buffers. The SHADA file is like adding steroids. You can keep marks, register contents, and command line history.

Relevant documentation

🚯 Prevent development logs from bloating on macOS

I rarely need to refer to development.log or test.log when working on rails applications, but yet I end up keeping weeks or even years of records [gigabytes]. I'm used to working with logrotate, and I wanted to find a similar solution that was preinstalled with macOS. macOS comes preinstalled with a program called newsyslog that can keep file sizes in check. I just created a new file at /etc/newsyslog.d/rails.conf which limits all rail's log files to just 10MB

# /etc/newsyslog.d/rails.conf
# logfilename                       	                        [owner:group]      mode count size(KB)     when  flags [/pid_file] [sig_num]
/Users/<username>/dev/<rails projects>/*/log/*.log     		    <username>:staff   644  0     10000  		*     G
# Mono repos
/Users/<username>/dev/<rails projects>/*/*/log/*.log     	    <username>:staff   644  0     10000  		*     G
# Deeper mono repos
/Users/<username>/dev/<rails projects>/*/*/*/log/*.log          <username>:staff   644  0     10000  		*     G

You can also perform a dryrun of the config for testing:

sudo newsyslog -v -n -f /etc/newsyslog.d/rails.conf

Clean Paste 🧼

When you copy text from the internet, a bunch of formatting and HTML gets copied, too. Copy a link's text and paste it into Mac Notes, and there's some of the text formatting of the website, plus the link.

I almost never want this extra stuff, so I use an alternate paste dubbed the 'Clean Paste.' On MacOS, instead of CMD + V, try CMD + OPTION + SHIFT + V. You'll get just the text, minus all the extras.

Note: I learned this via the newsletter Recomendo, which I (pause for effect) recommend. It's so helpful me and I've looked it up so many times, that I'm re-sharing it here.

Automate Applescript via Accessibility Description

While automating a few tasks I do frequently it became apparent that many apps do not title their UI elements. This makes it more of a trial and error process to figure out which button is where.

This leads to script that is not very descriptive:

tell application "System Events"
	tell process "zoom.us"
		click button 3 of window 0
	end tell
end tell

I've always wanted to reference elements by their label or utilize accessibility attributes if they are available but could never figure out how.

I finally have!

tell application "System Events"
	tell process "zoom.us"
		click (first button where its accessibility description = "Copy Invite Link") of window 0
	end tell
end tell

This is obviously a bit more verbose but infinitly more descriptive when looking back at what a script is doing.

My future self is already thanking me.

Tmux not starting after an upgrade

Recently upgraded my version of Tmux and after could no longer start a session. After banging my head on tmux's config files it turned out that sessions that were currently in play were the problem.

So if you find yourself in this situation... make sure to stop all sessions and most likely you'll have Tmux working again.

An easy way to kill everything would be tmux kill-server.

10x Your Playback Rate

Consuming pre-recorded conference talks, video tutorials, and podcasts at accelerated speeds is possible and addictive. Each week I send a newsletter containing at least one recent conference talk I've watched, and I wouldn't be able to do this without the following hack:

Most videos players (YouTube, Vimeo, QuickTime) let you increase the playback rate, but often these controls are hard to find or have an arbitrary ceiling like 2x. If there's a video element in the DOM, I like to bump up the rate in the DevTools console like this:

document.querySelector('video').playbackRate = 3

'3' equals three-times the normal speed, and that seems to be my limit for the moment.

playbackRate MDN docs

Inline MD codeblock with double backticks

A pair of single backticks signify an inline code block in Markdown. But if you need to put a backtick in that code block the backtick ends the codeblock!

Another way to signify an inline codeblock is with double backticks, two backticks in sequence on either side of the codeblock.

When using double backticks for a codeblock, a single backtick within the codeblock will be interpreted as just that, not the end of the codeblock.