www.eamoncaddigan.net

Content and configuration for https://www.eamoncaddigan.net
git clone https://git.eamoncaddigan.net/www.eamoncaddigan.net.git
Log | Files | Refs | Submodules | README

index.md (1902B)


      1 ---
      2 title: "2024, Day 4: Git pre-push hook for Hugo, part 2"
      3 date: 2024-12-04T14:48:25-08:00
      4 description: "Prevent pushing drafts to production"
      5 draft: false
      6 ---
      7 
      8 Well this is kludgey and frail, but I've worked out a pre-push hook that
      9 should stop me from pushing (most) drafts to my website (which is published
     10 when I push my repository to prod/main, hence the check on line 12).
     11 
     12 ```bash
     13 #!/bin/sh
     14 # Prevent a push to prod/main if a suspected draft post is found
     15 
     16 remote="$1"
     17 url="$2"
     18 
     19 z40=0000000000000000000000000000000000000000
     20 
     21 
     22 while read local_ref local_sha remote_ref remote_sha
     23 do
     24 	if [ "$remote $remote_ref" = "prod refs/heads/main" ]
     25 	then
     26 		if [ "$remote_sha" = $z40 ]
     27 		then
     28 			# New branch, examine all commits
     29 			range="$local_sha"
     30 		else
     31 			# Update to existing branch, examine new commits
     32 			range="$remote_sha..$local_sha"
     33 		fi
     34 
     35         git diff -U0 $range | grep -q '^\+draft: true'
     36         if  [ $? -eq 0 ]
     37         then
     38             echo >&2 "Found a possible draft, suppress with 'git push --no-verify'"
     39             exit 1
     40         fi
     41 
     42 	fi
     43 done
     44 
     45 exit 0
     46 ```
     47 
     48 This will allow a push if there are drafts in the commit history, but the
     49 final commit shouldn't have any draft posts. There are plenty of ways that
     50 this could break, but I expect it to suffice for now.
     51 
     52 I do welcome suggestions for improvement! A better script would only check
     53 Markdown files, and only inspect the YAML header, and would catch things
     54 like multiline parameters. TBH I probably wouldn't even share something like
     55 this if I wasn't working on #DecemberAdventure. But I suspect that I'll
     56 refine it if and when I'm annoyed by any misses (false positives and
     57 negatives alike), so maybe it'll become decent someday.
     58 
     59 ## Update: Day 7
     60 
     61 I edited the hook to check for the `prod` remote instead of `origin`. My
     62 `origin` repository still points to the version at
     63 <https://git.eamoncaddigan.net/www.eamoncaddigan.net>.