Skip to content

Instantly share code, notes, and snippets.

@Lukas238
Last active May 18, 2021 19:53
Show Gist options
  • Save Lukas238/ca8fae9accab8cf2984720032960636a to your computer and use it in GitHub Desktop.
Save Lukas238/ca8fae9accab8cf2984720032960636a to your computer and use it in GitHub Desktop.
Git shallow clone a repo to use as website root

How to git clone a repo to be used on a web server

Objective

I want to clone the repo of my site on my server, and configure the webserver to point to the subfolder ./public/, inside the repo.

This will allow me, for example, to update the site from the repo by means of running the commant git pull --forceon the server.

Repository structure

As reference, use this repo structure of the example project:

project/
├─ src/
│  ├─ scss/
│  │  ├─ styles.scss
│  ├─ parts/
│  │  ├─ header.twig
│  │  ├─ footer.twig
│  ├─ pages/
│  │  ├─ home.twig
│  ├─ layout/
│     ├─ default.twig
├─ public/
│  ├─ css/
│  │  ├─ styles.css
│  ├─ home.html
├─ .gitignore
├─ gulpfile.js
├─ package.json

The problem

I realy don´t need to clone the complete repository history on the web server. Nor I need to clone all the source files, as I only want to serve the content of the already compiled ./public/ folder.

Prerequisites

This make use of Git property sparse-checkout, and need Git version 2.26 or up.

Check this link for more info on how to update Git version on linux.

Update git to last version on Ubuntu

  1. Add Git repository to ubuntu apt: add-apt-repository ppa:git-core/ppa
  2. Update apt, and install git: apt update; apt install git

How to

Initial Clone

  1. Clone the repo, but without checking out the files yet, and as a shallow clone (last commit: git clone <your-repo-clone-URL> --no-checkout --depth 1
  2. Enter to the cloned folder: cd <cloned-folder>
  3. Initialize the sparse-checkout basic settings (this will include all files only in the root of the repo): git sparse-checkout init --cone
  4. Add the relative paths to the folders you want to include in the checkout (space separated), in this example public: git sparse-checkout set public
  5. Now, checkout the files: git checkout
  6. Done. You should now see the root files and only the public folder checked out.

Update

To update the repo, just run the pull command, but limit it to just the last commit: git fetch --depth 1 && git reset --hard @{upstream}

  • The --force command will ignore any local change and force theoverwrite of the local files.

Keep this in mind, depending on how your site works, this may result on the lost of information.

  • The @{upstream} git parameter will be automatically replaced by the origin/ currently in use.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment