Create patches that you can deploy via FTP by using git

Posted by Harald Nezbeda on Sun 22 August 2021

Poeple don't often talk about this, but deploying via FTP is still a thing, even in 2021. There are various reasons why developers have to do this, most times it is related to the service provider for security reasons. In other cases, it really makes sense to stick to FTP or SFTP in order to reduce maintenance costs, as there is no other requirement for the application (think about WordPress or any static website). Anyway, if you have ssh access to your server you should consider using other methods such as rsync.

Create a local path for executables

Skip this step in case you already have something similar configured. Otherwise create a bin directory into you users $HOME directory

Linux now needs to know where the custom executables will be located. Make sure it is added to the global $PATH by adding the following line at the bottom of ~/.bashrc

export PATH="$HOME/bin:$PATH"

Creating the git-copy commands

Create a new file for the command and add executable right to it.

touch ~/bin/git-copy
chmod +x ~/bin/git-copy

Afterwards open the file and add the following bash script:

#!/bin/bash
set -e

git checkout $1
TARGET_DIR=$3
echo "Creating patch"
for i in $(git diff --name-only $1 $2)
    do
        mkdir -p "$TARGET_DIR/$(dirname $i)"
        cp "$i" "$TARGET_DIR/$i"
    done
git checkout -
echo "Patch available in $TARGET_DIR"

How to use the command

After the steps above are done, the command is ready to be used. Just make sure to open a new terminal window in order to load the new PATH configuration.

The script is using 3 parameters:

  • the first two arguments are the revisions used for the git diff commands. The first branch is the target from which to start and will be checkout during the execution.
  • the third argument is the target directory where the patch will be stored

The script is executing a git-diff with the --name-only function to get a list of all files that have been changed beetween the 2 revisions and loops over them in order to copy each file to the defined target directory.

Examples

Create a patch for a new feature
git-copy feature main ~/output/patch-1/
Patch beetween releases
git-copy tag2 tag1 ~/output/patch-2/
Create a patch for the last 5 new commits
git-copy main HEAD~5 ~/output/patch-3/

How to use the patches

A patch will be created by respecting the folder structure in git. Make sure to adapt this if required. In most cases they can be directly applied to the FTP/SFTP target.