gh-pages Deployment

Deploying a subfolder to GitHub Pages

Sometimes you want to have a subdirectory on the master branch be the root directory of a repository’s gh-pages branch.

For the sake of this example, let’s pretend the subfolder containing your site is named dist.

Step 1

Make sure no other changes in master branch.
Remove the dist directory from the project’s .gitignore file. That mean original dist is ignored in master branch.

Step 2

Make sure git knows about your subtree (the subfolder with your site).

1
git add dist && git commit -m "Initial dist subtree commit"

Step 3

Use subtree push to send it to the gh-pages branch on GitHub.

1
git subtree push --prefix dist origin gh-pages

Boom. If your folder isn’t called dist, then you’ll need to change that in each of the commands above.

If you do this on a regular basis, you could also create a script as following:

1
2
3
4
5
6
7
8
#!/bin/sh
if [ -z "$1" ]
then
echo "Which folder do you want to deploy to GitHub Pages?"
exit 1
fi
git add $1 && git commit -m "Initial folder as a subtree commit"
git subtree push --prefix $1 origin gh-pages

Run above shell as below:

1
2
# if file path is bin/git-deploy-gh-pages.sh
bash bin/git-deploy-gh-pages.sh dist

Better Approach

  1. git checkout master # you can avoid this line if you are in master…
  2. git subtree split --prefix dist -b gh-pages # create a local gh-pages branch containing the splitted output folder
  3. git push -f origin gh-pages:gh-pages # force the push of the gh-pages branch to the remote gh-pages branch at origin
  4. git branch -D gh-pages # delete the local gh-pages because you will need it: ref

or:

1
git push origin `git subtree split --prefix build_folder master`:gh-pages --force

or:

If you want to immediately push to gh-pages as soon as you’ve committed updates to the website, you can try this: (replace site with your own specific subdirectory)

1
2
3
4
5
6
7
8
#!/bin/bash

# if anything in the site/ subdirectory changed in the prior commit,
# push that directory to gh-pages for auto generation.
git diff-tree -r --name-only --no-commit-id master | grep '^site/' &> /dev/null
if [ $? == 0 ]; then
git push origin `git subtree split --prefix site master 2> /dev/null`:gh-pages --force
fi

GitHub Pages

感谢支持,让我安静的做蚂蚁梦!