Skip to content

Instantly share code, notes, and snippets.

@MidnightLightning
Created July 30, 2018 23:00
Show Gist options
  • Save MidnightLightning/7676855cac2937671d2bf70b22fc53ea to your computer and use it in GitHub Desktop.
Save MidnightLightning/7676855cac2937671d2bf70b22fc53ea to your computer and use it in GitHub Desktop.
Add folder of content to IPFS
#!/bin/bash
DOCKERCMD="docker exec -it ipfs.service"
echo "Adding folder $1 to IPFS..."
HASHES=$($DOCKERCMD ipfs add -r -q "$1" | tr -s [:space:] ' ') # Add the folder, and strip out odd characters from result output
echo $HASHES
HASHES=($HASHES) # Convert into a set
FOLDERHASH=${HASHES[-1]} # The enclosing folder's hash is the last one in the list
echo "Adding folder $FOLDERHASH to IPFS MFS..."
$DOCKERCMD ipfs files cp /ipfs/$FOLDERHASH "/$1" || exit 1
echo "Successful! Removing explicit pin for $FOLDERHASH..."
$DOCKERCMD ipfs pin rm $FOLDERHASH
@MidnightLightning
Copy link
Author

MidnightLightning commented Jul 30, 2018

This script was created from the need as a developer to do iterative pushes to IPFS. If following the workflow of:

  1. Write code.
  2. Use ipfs add -r my-webapp to add MVP to IPFS.
  3. Browse result on local IPFS node.
  4. Make changes.
  5. Use ipfs add -r my-webapp to update with changes
  6. Browse result on local IPFS node.
  7. Happy with final result, announce final hash to the world.

That creates a lot of intermediary hashes of all the in-progress development work pinned on your local node, with no easy way to clean them up.

This process instead uses the IPFS mutable file store (MFS) to just keep "the most recent version" of the content around. The MFS acts like a shared/synced folder, and adding content to it causes your local node to keep that content around. If you overwrite content, then eventually the old is garbage-collected. So, with this script, the workflow becomes:

  1. Write code.
  2. Use add-folder-to-ipfs.sh my-webapp to add MVP to IPFS.
  3. Browse result on local IPFS node.
  4. Make changes.
  5. Use add-folder-to-ipfs.sh my-webapp to update with changes
  6. Browse result on local IPFS node.
  7. Happy with final result, announce final hash to the world.

Using the ipfs files stat /my-webapp command, you can get the current hash/ID of that folder at any time, and any old versions will be garbage-collected as needed by the server.

This script uses my development environment setup, which is a Docker container running under the name ipfs.service. Because the IPFS main Docker image is built on Alpine Linux, it doesn't have a Bash shell (it has a more stripped-down /bin/sh shell), which makes scripting more difficult. So, these commands work outside the Docker container, using docker run commands to execute IPFS commands in the appropriate container.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment