zk/work/gitea-3.md

15 KiB

How To Deploy a Static Website from Gitea Using Git Hooks

Introduction

The popular source code management system Git is quite flexible when it comes to allowing you to perform various tasks when actions are taken on a repository. For example, you might want to send an email when a feature branch is merged into your main branch, or log various Git actions to a file for tracking.

These actions are called hooks, and there are several that you can use for various steps along the way to perform additional work within your Git workflow. For example:

  • post-receive hooks can be used to perform actions when a commit is pushed to the repository and are useful for CI/CD.
  • post-merge hooks can be used to perform actions after a merge has been completed and are useful for logging and notifications.
  • post-checkout hooks can be used to perform actions after you run git checkout and are useful for setting up project environments.

For this tutorial, we will be looking at using the post-receive hook. A common usage for the hook is running some form of continuous integration or deployment. This might mean running tests or deploying a project. For this example, we will be automatically deploying changes to a static HTML site served by Nginx.

Prerequisites

Gitea is a lightweight and flexible source code management system that will be used for the examples here, so before beginning this tutorial, you should have the following:

Step 1 — Creating a Static HTML Project in Gitea

To begin with, you will need a repository set up in Gitea. Create a new repository using the + button in the upper right corner of the Gitea page. Name it something memorable such as the domain name that it will be deployed to. Fill out the rest of the new repository information and click Create Repository.

Creating a new repository

For this tutorial, you'll be setting up a static site at static.<^>your_domain<^>, but be sure to replace this with your final site's domain. Now, wherever you plan on developing, check out that repository using git clone:

git clone git@<^>your_domain<^>:<^>username<^>/static.<^>your_domain<^>

Move into that directory using cd:

cd static.<^>your_domain<^>

Now, create a file named index.html which will be served by Nginx. The following example uses nano. This file will contain a little bit of text that we can view in the browser.

nano index.html

Within that file, add a snippet of HTML that you will recognize:

[label index.html]
<html>
    <head>
        <title>Testing Gitea</title>
    </head>
    <body>
        <h1>It works!</h1>
    </body>
</html>

Save and close the file. If you used nano to edit the file, you can do so by pressing Ctrl + X, Y, and then Enter.

Now, add the file to the git working tree:

git add index.html

Now that the file is added, commit your changes:

git commit -m "Added index.html"

Push your changes up to your Gitea repository:

git push origin main

<$>[note] Note: In this example, we are working on the branch named main. Your default branch may be named something else such as master. In order to find out the name of your current branch, you can run git branch. <$>

Step 2 — Creating a Static HTML Site in Nginx

Now, let's set up Nginx to serve our static site. Create a new file in /etc/nginx/sites-available using your text editor:

sudo nano /etc/nginx/sites-available/static.<^>your_domain<^>

In this file, enter the following:

[label /etc/nginx/sites-available/static.<^>your_domain<^>]
server {
	server_name static.<^>your_domain<^>;
	listen 80;

	root /var/www/static.<^>your_domain<^>;

    index index.html;
    
	location / {
		try_files $uri $uri/ =404;
	}
    
    location /.git {
        return 404;
    }
}

This server block instructs Nginx to listen on the standard HTTP port 80 for requests to static.<^>your_domain<^>. When it receives a request, it tries to find a file matching that request in /var/www/static.<^>your_domain<^>. It will first try looking for the file named (for instance, if you visit static.<^>your_domain<^>/shark.jpg, it will try to find /var/www/static.<^>your_domain<^>/shark.jpg). If that does not exist, it will append a / to the end of the file name to serve a directory or the file named index.html. Finally, if none of those work, it will serve a 404 Not Found error.

We also don't want anyone accessing our .git directory, so the next location block instructs Nginx to return a 404 should someone try.

Now, link this file from sites-available to sites-enabled:

sudo ln -s /etc/nginx/sites-available/static.<^>your_domain<^> /etc/nginx/sites-enabled/static.<^>your_domain<^>

In order to make sure everything looks good, you can test the new configuration:

sudo nginx -t

If all has gone well, you should see something like the following:

[secondary_label Output]
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Restarting the server will make these changes live.

sudo systemctl restart nginx

We need to create the repository for there to be anything to serve, however. Move to /var/www where you can create the directory for hosting the site:

cd /var/www

Make the directory you specified in your server block above:

sudo mkdir static.<^>your_domain<^>

You will need to change the permissions on this directory so that both you and the git user have write access.

sudo chown <^>username<^>:git static.<^>your_domain<^>
sudo chmod g+x static.<^>your_domain<^>

Move to that directory:

cd static.<^>your_domain<^>

Now that you have the directory set up, you can clone the repository into it. Rather than using SSH, which would require a key, you can use the file:// protocol for Git. This works because Nginx is running on the same server that the repository lives on. If the repository is public, you can also use the https:// protocol.

git clone file:///<^>path_to_gitea_installation<^>/repositories/sammy/static.<^>your_domain<^>.git .

It's important to remember to add that . at the end of the git clone command, as this tells Git to check out the repository into the current directory rather than making a new one. Now, if you type ls, you should see the file index.html from your repository, and if you visit the domain you set up, you should see your page rendered.

The static webpage

Step 3 — Using Git Hooks to Publish Changes

Now that Nginx is serving the site from our checked out repository, we can set up the post-receive hook to update the site.

Creating the Hook Script

Git hooks for Gitea live in the repository that Gitea serves from. These are located in the data directory, predictably within the repositories subdirectory. Move to your data directory using cd, then move to your repository's hooks directory:

cd git/repositories/<^>username<^>/static.<^>your_domain<^>.git/hooks

If you list the files in this directory, you will see a whole host of sample scripts, plus a few directories:

[secondary_label Output]
total 92
drwxr-xr-x 6 git git 4096 Jun 27 17:29 ./
drwxr-xr-x 7 git git 4096 Jun 27 17:43 ../
-rwxr-xr-x 1 git git  478 Jun 27 17:29 applypatch-msg.sample*
-rwxr-xr-x 1 git git  896 Jun 27 17:29 commit-msg.sample*
-rwxr-xr-x 1 git git  376 Jun 27 17:29 post-receive*
drwxr-xr-x 2 git git 4096 Jun 27 17:29 post-receive.d/
-rwxr-xr-x 1 git git  189 Jun 27 17:29 post-update.sample*
-rwxr-xr-x 1 git git  424 Jun 27 17:29 pre-applypatch.sample*
-rwxr-xr-x 1 git git 1643 Jun 27 17:29 pre-commit.sample*
-rwxr-xr-x 1 git git  416 Jun 27 17:29 pre-merge-commit.sample*
-rwxr-xr-x 1 git git 1374 Jun 27 17:29 pre-push.sample*
-rwxr-xr-x 1 git git 4898 Jun 27 17:29 pre-rebase.sample*
-rwxr-xr-x 1 git git  376 Jun 27 17:29 pre-receive*
drwxr-xr-x 2 git git 4096 Jun 27 17:29 pre-receive.d/
-rwxr-xr-x 1 git git  544 Jun 27 17:29 pre-receive.sample*
-rwxr-xr-x 1 git git 1492 Jun 27 17:29 prepare-commit-msg.sample*
-rwxr-xr-x 1 git git  134 Jun 27 17:29 proc-receive*
drwxr-xr-x 2 git git 4096 Jun 27 17:29 proc-receive.d/
-rwxr-xr-x 1 git git 2783 Jun 27 17:29 push-to-checkout.sample*
-rwxr-xr-x 1 git git  356 Jun 27 17:29 update*
drwxr-xr-x 2 git git 4096 Jun 27 17:29 update.d/
-rwxr-xr-x 1 git git 3650 Jun 27 17:29 update.sample*

For our purposes, we will be creating a new script within the post-receive.d directory. On Linux, configuration and scripts are usually stored in a directory such as /etc/apt or our hooks directory. However, if there are multiple configuration files or scripts, they may be divided up and placed in a *.d directory, and the service which uses them will read all of those files in list order.

Open a new file in post-receive.d for editing named deploy:

nano post-receive.d/deploy

This file can be any executable script. In our case, since we'll just be running a simple git command, we'll use a Bash script. Enter the following into that file:

[label post-receive.d/deploy]
#!/bin/bash

set -eux

git --git-dir=/var/www/static.<^>your_domain<^>/.git --work-tree=/var/www/static.<^>your_domain<^>/ pull --ff-only

Let's break this script down into its parts to understand what's happening:

  • #!/bin/bash tells the shell to use the bash command to run the script.
  • set -eux specifies three options: e means that the script will exit on a failure, u means that unset variables will be an error, and x means that it will print the commands as it executes them. These options are good practice for preventing scripts from continuing to execute when there are errors.
  • The git command breaks down into git pull which pulls new changes from the repository, while the --work-tree and --git-dir options tell Git to use the .git directory within the checked out branch for all of its configuration. --ff-only instructs git pull to use fast-forward reconciliation when pulling new commits.

Once you're done editing the script and have saved and closed it, use chmod to make the script executable:

chmod a+x post-receive.d/deploy

For Gitea Running in Docker

If Gitea is running in a Docker container --- if, for instance, you deployed it using the Docker Compose method in the tutorial linked above --- you will need to make a few changes to make the repository accessible from within the container. First, edit the docker-compose.yml file and move to the volumes: entry. Add a new line to that list:

[label docker-compose.yml]
    volumes:
      ...
      <^>- /var/www/static.<^>your_domain<^>:/var/www/static.<^>your_domain<^><^>

This will mount that directory as a volume that the container can access. You will need to restart your Gitea containers:

docker-compose down
docker-compose up

Next, you will need to change the remote URL for the repository to the proper location for within the Docker container.

git remote set-url origin file:///data/git/repositories/sammy/static.<^>your_domain<^>.git

Here, we've changed the original URL we used to check out the branch from /<^>path_to_gitea_installation<^>/repositories/sammy/static.<^>your_domain<^>.git to use /data/git/ as the path to the installation, as that is how the volume is mapped in docker-compose.yml. As always, be sure to use the username and repository name appropriate to your project.

Testing the post-receive Hook

Now, after Gitea receives a new commit and it's written to disk, it will run this script to update the branch checked out in /var/www/static.<^>your_domain<^>. To test this out, change the index.html file on your local working directory to include a congratulations message. For example, change the file so that it resembles this:

[label index.html]
<html>
    <head>
        <title>Testing Gitea</title>
    </head>
    <body>
        <h1>It works!</h1>
        <p>Congratulations on setting up a <code>post-receive</code> hook!
    </body>
</html>

After saving and exiting the file, commit your changes:

git commit -am "Added congratulations message"

And push your changes:

git push origin main

This time, you should see some additional output from Git. Because you set the -x option in our deploy script, you'll see the output of that script during the process, prefixed with remote:.

[secondary_label Output]
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 312 bytes | 312.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
remote: + cd /var/www/static.<^>your_domain<^>
remote: + git --git-dir=/var/www/static.<^>your_domain<^>/.git pull --ff-only
remote: From file:///data/git/repositories/<^>username<^>/static.<^>your_domain<^>
remote:    28c52bf..95cde6f  main       -> origin/main
remote: Updating 28c52bf..95cde6f
remote: Fast-forward
remote: . Processing 1 references
remote: Processed 1 references in total
To <^>your_domain<^>:<^>username<^>/static.<^>your_domain<^>.git
   8eed10f..95cde6f  main -> main

When you visit your page in the browser, you should see your now congratulations message displayed.

Conclusion

In this tutorial, you learned how to use Git hooks in Gitea. While you used the post-receive hook to deploy a static website, there are many available hooks that can help you accomplish a wide variety of tasks during your Git workflow. For more information on these hooks, the Git manual has an in-depth chapter on using them.