git merge-tree → run_builtin() → cmd_merge_tree(argc, argv, prefix, repo)

Every Git command is a C function. Level 9 shows how the command line reaches it.

Learn C by reading Git

A zero-to-hero path through the C that Git is written in, aimed at people who want to contribute, especially to the work on reducing Git's global state (the_repository). If you've never written C, start with sections A–D. Every level after that teaches one idea from a real piece of git.git, with a small exercise.

Pinned to Git v2.56.0 (released 27 September 2026). Every file and line cited here links to that release, so the examples stay correct as Git moves on. To compare with today's code, run the same git grep on master.

Every C level has a practice box: edit the code, press ▶ Run to compile it with real gcc 14.2 through Compiler Explorer, and ✓ Check my answer to compare your output. Nothing to install. Your edits are saved in your browser.

Progress: 0 of 0 sections marked done (saved in this browser only).

Before you start

How to learn from this guide

Git's community says it plainly: they want to mentor humans, not AIs. Reviewers on the mailing list will ask you why you made each change, and you have to be able to answer. So learn it properly:

  • Type every example yourself and compile it. Don't copy and paste.
  • Guess before you run. Say what you expect the program to print. When you're wrong, that's the lesson.
  • Try each exercise for at least 15 minutes before opening the answer.
  • Read compiler warnings as errors. Build Git with make DEVELOPER=1, which turns on strict warnings, the same ones reviewers use.
  • Read the real code around every example. Each level names a file and line. Open it.
  • Read other people's patches. The mailing list archive at lore.kernel.org/git shows how experienced contributors write, explain and fix their changes. This is the best teacher you have.
  • Ask in public. When you're stuck for real, ask on the Git mailing list (start the subject with [Outreachy]) or on #git-devel (IRC or Discord, see git-scm.com/community). The mentors for the global-state project are Christian Couder and Usman Akinyemi. Say what you tried and what happened. Other applicants learn from the answer too.
  • Follow Git's AI guidelines. Everything you send must be your own work that you understand.
Start here · A no code yet

What C is, and why Git uses it

C is a programming language from 1972. It's small, fast, and very close to how the computer actually works: you manage memory yourself, and values are just bytes at addresses. Operating systems (Linux), databases (PostgreSQL, SQLite) and Git are written in it.

Three things to know

  • It's compiled. A compiler (gcc or clang) turns .c files into a native program. There's no interactive prompt like Python's.
  • It's statically typed, but not very strict. Every variable has a type (int, char *, struct repository *), but C will happily convert between many of them. Warnings matter.
  • You manage memory. If you ask for memory with malloc, you must give it back with free. Forget, and you have a leak. Free twice, or use it after freeing, and the program may crash or behave strangely.

What Git is made of

PartLanguageWhere
The commands and the core libraryCtop-level *.c/*.h, builtin/
The test suitePOSIX shellt/
DocumentationAsciiDocDocumentation/
BuildMake (also Meson)Makefile, meson.build

How it compares

If you know…C will feel…
JavaScript / PythonMuch more manual: no objects, no garbage collector, no built-in strings or lists. You build those from structs, pointers and arrays.
TypeScriptTypes exist, but they describe memory layout, not shapes of data. There are no generics.
Rust / OCamlThe same low-level control as Rust, with none of the safety checks. Nothing stops a null pointer or a leak except you and the reviewers.
Start here · B macOS · Linux · Windows (WSL)

Set up a compiler and get Git's source

You need a terminal, a C compiler, make, and a few libraries. Pick your system. Every package list below comes from a real source: Git's own INSTALL file and the packages Git's CI installs on Ubuntu every day (ci/install-dependencies.sh:61).

Only want to practise C? Skip this: the practice boxes in levels C–8 run in your browser.

Windows: use WSL (recommended)

WSL (Windows Subsystem for Linux) gives you a real Ubuntu inside Windows. The Outreachy page for Git says Windows users should be able to install a Linux virtual machine or WSL. These steps are from Microsoft's WSL guide:

  1. You need Windows 10 version 2004 or later (build 19041+), or Windows 11.
  2. Right-click PowerShell → Run as administrator, and run:
    wsl --install
    This installs WSL with the Ubuntu distribution.
  3. Restart your computer.
  4. Open Ubuntu from the Start menu. The first time, it unpacks files, then asks you to create a Linux username and password (this password is what sudo asks for later).
  5. From now on, type every command in this guide into that Ubuntu window, and follow the Linux steps below.
Keep Git's source inside Linux. Microsoft recommends storing project files in the Linux file system (/home/<you>/…), not on the Windows drive (/mnt/c/…), for speed. Building and testing Git touches thousands of files, so this matters. Run cd ~ before cloning.

Prefer native Windows? Git for Windows maintains its own build environment, the Git for Windows SDK. It's a different setup from this guide; WSL is the simpler path for contributing to git.git.

Linux (Ubuntu, Debian) and WSL

sudo apt-get update
sudo apt-get install make gcc gettext zlib1g-dev libssl-dev libcurl4-openssl-dev libexpat-dev git git-email gdb
  • make gcc gettext zlib1g-dev libssl-dev libcurl4-openssl-dev libexpat-dev: what Git's CI installs to build Git. Git's INSTALL says zlib is the one library Git won't build without.
  • git-email: on Debian and Ubuntu, git send-email is a separate package (Debian describes it as Git's "email add-on"). You need it in Lab 3.
  • gdb: the GNU Debugger, for the debugging lab.

macOS

xcode-select --install

This installs Apple's command-line tools: clang (the C compiler), make, git and the lldb debugger.

About Rust (all systems)

Git v2.56.0 builds some code in Rust by default, and that needs Rust's cargo tool. Git's Makefile says: Rust is still optional for now, define NO_RUST to leave it out, and with Git 3.0 Rust will always be enabled. As a beginner, simply add NO_RUST=1 to your make commands (Lab 1 shows how). If you want Rust later, install cargo (on Ubuntu it's the cargo package, which Git's CI also installs).

Your editor

Use one that can jump to a function's definition (VS Code with the C/C++ extension, or clangd). On WSL, VS Code can open your Linux folder directly: type code . in the Ubuntu window. From the terminal, git grep -n name finds anything quickly.

Start here · C a scratch folder, not git.git

Your first C program

Make a folder outside the Git source, create hello.c, and type this:

hello.c
#include <stdio.h>      /* gives us printf */

static int area(int width, int height)
{
	return width * height;
}

int main(void)
{
	int w = 256;
	int h = 128;

	if (area(w, h) > 10000)
		printf("big: %d\n", area(w, h));
	else
		printf("small\n");

	for (int i = 0; i < 3; i++)
		printf("line %d\n", i);

	return 0;           /* 0 means success */
}
cc -Wall -o hello hello.c
./hello
  • Every program starts at main. Its return value is the exit code: 0 is success.
  • Every statement ends with ;. Blocks use { }.
  • Every variable and parameter has its type written in front: int w.
  • printf fills in %d (an int), %s (a string), %lu (an unsigned long) and so on.
  • Git indents with tabs, puts a function's opening { on its own line, and uses /* */ comments only, never //. Get used to that style now.

Basic types

TypeHoldsExample in Git
intA whole number; also used for true/false (0 = false)int initialized;
unsigned long, size_tNon-negative numbers; size_t is for sizes and lengthssize_t len; in struct strbuf
booltrue/false (allowed in Git since 2023)bool warn_on_auto_comment_char;
charOne byte'#'
char *The address of some bytes: C's “string”char *gitdir;
void“Nothing”; a function that returns nothingvoid prepare_repo_settings(…)

Reading a compiler error

int n = "hello";
hello.c:5:6: error: incompatible pointer to integer conversion initializing
      'int' with an expression of type 'char[6]'

The shape is always file:line:column: what's wrong. Go to that line. Here you tried to put a string (an array of 6 chars, including the hidden end byte) into an int. Fix the first error first; later ones are often caused by it.

Exercise

Add a function static int is_tiff_magic(int magic) that returns 1 for 42 and 0 otherwise, and call it from main. Then remove the static int return type and read the warning.

Answer
static int is_tiff_magic(int magic)
{
	return magic == 42;
}

Comparisons give 1 or 0 in C, so you can return them directly. Without a return type, modern compilers refuse the code, because old C's “implicit int” rule is gone.

Practice in your browser · 1 of 9

Your first program

Print the area and the perimeter of a 256 × 128 image. Fill in the TODO so the output matches the expected lines.

Expected output:

area: 32768
perimeter: 768
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>

static int area(int width, int height)
{
	return width * height;
}

static int perimeter(int width, int height)
{
	return 2 * (width + height);
}

int main(void)
{
	int w = 256;
	int h = 128;

	printf("area: %d\n", area(w, h));
	printf("perimeter: %d\n", perimeter(w, h));
	return 0;
}
Start here · D what the code is managing

Git in one picture

Inside every repository is a .git folder. The C code reads and writes it. In memory, almost everything about one repository is collected in one struct, struct repository.

  your-project/.git/                    in memory (C)
  ├── objects/   blobs, trees,  ───►  struct repository
  │              commits              ├── char *gitdir        ".git"
  ├── refs/      branches, tags ───►  ├── objects  ─► struct object_database
  ├── index      staging area   ───►  ├── index    ─► struct index_state
  └── config     settings       ───►  ├── settings    struct repo_settings
                                      └── config ...

  the_repository  ──►  one global pointer to "the" repository
                       for the current command
WordMeaning
ObjectA stored item, named by its hash (struct object_id). Blob = file content, tree = folder, commit = snapshot plus message.
Object database (ODB)Where objects live: loose files and packfiles
RefA name pointing at a commit: refs/heads/main
IndexThe staging area, what git add fills
BuiltinA command implemented in C inside the git binary, like git add
Global stateData any function can reach without being given it, like the_repository
LibificationMaking Git's code usable as a library inside other programs, which global state gets in the way of
Level 0 the top folder

The map of git.git

Git's source is large (641 .c files in v2.56.0), but it's laid out simply.

WhereWhat
git.cThe main that reads git <command> and calls the right function
builtin/*.cOne file per command: builtin/add.c, builtin/merge-tree.c…
top-level *.c / *.hThe shared library code: repository.c, environment.c, merge-blobs.c, strbuf.c…
git-compat-util.hIncluded first in every .c file; smooths over platform differences
t/Shell test scripts, t0001-init.sh and so on
Documentation/Man pages, plus CodingGuidelines, SubmittingPatches and MyFirstContribution. Read all three.

Tools for finding your way

git grep -n "struct repository {"          # where is it defined?
git grep -n "merge_blobs("                   # who calls it?
git log --oneline -- merge-blobs.c           # history of a file
git log -S the_repository -- prune-packed.c  # commits that added/removed a word
git blame -L 60,90 merge-blobs.c             # who wrote each line, and in which commit
Exercise

Using only git grep, find which file defines cmd_merge_tree and which line of git.c lists the merge-tree command.

Answer

git grep -n "^int cmd_merge_tree" gives builtin/merge-tree.c. git grep -n '"merge-tree"' git.c gives the line { "merge-tree", cmd_merge_tree, RUN_SETUP },.

Lab 1 your terminal · about 15 minutes

Build Git and run one of its tests

This is the first real step every contributor takes. Each output below was produced by actually running the command on Git v2.56.0.

1. Get the source, pinned to v2.56.0

cd ~
git clone https://github.com/git/git.git
cd git && git switch --detach v2.56.0

Git's own tutorial clones from this GitHub mirror too (MyFirstContribution.adoc:75). --detach means "look at this release without making a branch", which is fine for learning.

2. Build it

make -j4 NO_RUST=1

-j4 builds 4 files at once (use the number of CPU cores you have). NO_RUST=1 skips the Rust parts (see section B). It takes a few minutes. Lines scroll past, like CC object-file.o; that's normal.

What you should see
    ...
    SUBDIR templates

If something failed, the last lines contain the word error. The most common cause is a missing library, so re-run the install command from section B.

3. Check you're running your Git

./git version
What you should see
git version 2.56.0

The ./ matters: it runs the Git you just built in this folder, not the one installed on your system.

4. Run one test script

cd t && ./t0001-init.sh
What you should see
ok 1 - plain
ok 2 - plain nested in bare
...
ok 103 - init honors GIT_OBJECT_DIRECTORY
# passed all 103 test(s)
1..103

Each ok line is one test. The last two lines are the summary.

5. Look inside a test

./t0001-init.sh --run=1 -v
What you should see
expecting success of 0001.1 'plain':
	git init plain &&
	check_config plain/.git false unset

Initialized empty Git repository in .../t/trash directory.t0001-init/plain/.git/
ok 1 - plain

--run=1 runs only test 1 (the rest show as skip), and -v ("verbose") shows the commands and their output. Every test works inside a temporary trash directory, so it can't damage your real files. These options are documented in t/README: -v, -i (stop at the first failure), -x (show every shell command), -d (keep the trash directory).

Exercise

Run ./t0001-init.sh --run=2 -v. What is test 2 called, and which git command does it start with?

Answer

"plain nested in bare". It starts by running git init --bare bare-ancestor.git.

Level 1 repository.h · merge-blobs.c

Headers, declarations and #include

C code is split in two. A header (.h) declares what exists: “there is a function called this, with these argument types”. A source file (.c) defines it: the actual code. Other files #include the header to use it.

void *merge_blobs(struct index_state *,
		  const char *,
		  struct blob *, struct blob *,
		  struct blob *, size_t *);
void *merge_blobs(struct index_state *istate,
		  const char *path, …)
{
	/* the real code */
}

Include guards

#ifndef REPOSITORY_H
#define REPOSITORY_H
…
#endif

#include literally pastes the file in. The guard makes sure that if a header is included twice, its contents only count once.

Forward declarations

struct index_state;
struct object_database;

This says “a struct with this name exists” without saying what's inside. That's enough to use a pointer to it (Level 3). It keeps headers from including each other in a huge web.

Git's include rule

Every .c file includes git-compat-util.h first. Then it includes exactly the headers it uses. A real patch removing the_repository from merge-blobs.c had to add #include "repository.h" and #include "read-cache-ll.h", because the code now looked inside struct repository and struct index_state directly.

Exercise

Split your hello.c into area.h (declaration with a guard), area.c (definition) and main.c. Compile with cc -Wall -o hello main.c area.c.

Answer
/* area.h */
#ifndef AREA_H
#define AREA_H
int area(int width, int height);
#endif

area.c includes "area.h" and defines the function (without static, so other files can see it). main.c includes "area.h" and calls it.

Practice in your browser · 2 of 9

Declare before you use

In C a function must be declared before it is called. main calls shout(), but shout() is defined below it. Add a one-line declaration above main (this is what a header file does for you).

Expected output:

hello!
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>

void shout(const char *word);

int main(void)
{
	shout("hello");
	return 0;
}

void shout(const char *word)
{
	printf("%s!\n", word);
}
Level 2 repository.h · repo-settings.h

Structs, enums and initializers

A struct groups named fields into one value. It's the closest thing C has to an object.

struct repo_settings {
	int initialized;
	int core_commit_graph;
	int index_version;
	enum untracked_cache_setting core_untracked_cache;
	size_t delta_base_cache_limit;
	char *hooks_path;
};

An enum gives names to a set of integer values:

enum ref_storage_format {
	REF_STORAGE_FORMAT_UNKNOWN,     /* 0 */
	REF_STORAGE_FORMAT_FILES,       /* 1 */
	REF_STORAGE_FORMAT_REFTABLE,    /* 2 */
};

Designated initializers and _INIT macros

#define REPO_SETTINGS_INIT { \
	.shared_repository = -1, \
	.index_version = -1, \
	.core_untracked_cache = UNTRACKED_CACHE_KEEP, \
	… \
}

.field = value sets fields by name; anything not mentioned becomes 0. Git defines a FOO_INIT macro for most structs, so you write struct strbuf sb = STRBUF_INIT; and get a correctly set-up value. You'll use this pattern constantly.

Exercise

Define struct window { int x, y, width, height; };, a WINDOW_INIT macro that sets width and height to 1, and print one created with it.

Answer
#define WINDOW_INIT { .width = 1, .height = 1 }
struct window w = WINDOW_INIT;
printf("%d %d %d %d\n", w.x, w.y, w.width, w.height);   /* 0 0 1 1 */
Practice in your browser · 3 of 9

Structs and an _INIT macro

Git gives most structs a FOO_INIT macro. Write WINDOW_INIT so a new window has width and height set to 1, and everything else 0.

Expected output:

0 0 1 1
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>

struct window {
	int x, y;
	int width, height;
};

#define WINDOW_INIT { .width = 1, .height = 1 }

int main(void)
{
	struct window w = WINDOW_INIT;

	printf("%d %d %d %d\n", w.x, w.y, w.width, w.height);
	return 0;
}
Level 3 merge-blobs.c

Pointers: the one idea you must get

A pointer is a variable that holds the address of something else. Almost every function in Git takes pointers.

SyntaxMeaning
struct repository *rr holds the address of a repository
&x“the address of x”
*p“the thing p points at”
p->fieldA field of the struct p points at; same as (*p).field
NULLA pointer to nothing. Using it crashes the program.

Following a chain

buf = odb_read_object(istate->repo->objects, &oid, &type, &sz);

Read it left to right: from the index (istate), go to its repository (->repo), then to that repository's object database (->objects). struct index_state has a struct repository *repo field (read-cache-ll.h:189), which is why this works.

Out-parameters

A C function can only return one value. To give back more, the caller passes addresses, and the function writes into them. Above, &type and &sz let odb_read_object fill in the object's type and size, while the return value is the data itself.

Why pointers matter for global state

The fix for global state is almost always: pass a pointer to the repository as a parameter, instead of reaching for the global the_repository. That's what this merged commit did. preload_index() already receives the index, and the index knows its repository, so index->repo replaces the global:

commit 1fde1c5daf · preload-index: stop depending on 'the_repository' (2025)
-#define USE_THE_REPOSITORY_VARIABLE
 #define DISABLE_SIGN_COMPARE_WARNINGS
 …
-	repo_config_get_bool(the_repository, "core.preloadindex", &core_preload_index);
+	repo_config_get_bool(index->repo, "core.preloadindex", &core_preload_index);
 …
-		pd.progress = start_delayed_progress(the_repository,
+		pd.progress = start_delayed_progress(index->repo,
Exercise

Write void swap(int *a, int *b) that swaps two ints, and call it as swap(&x, &y). Why can't void swap(int a, int b) work?

Answer
void swap(int *a, int *b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

C passes copies of arguments. With plain ints, the function swaps its own copies, and the caller's variables don't change. Passing addresses lets it change the originals.

Practice in your browser · 4 of 9

Pointers: swap two numbers

swap() must change the caller's variables. Fix the function (and the call) so the output says x=2 y=1.

Expected output:

x=2 y=1
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>

static void swap(int *a, int *b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

int main(void)
{
	int x = 1, y = 2;

	swap(&x, &y);
	printf("x=%d y=%d\n", x, y);
	return 0;
}
Level 4 strbuf.h · banned.h · git-compat-util.h

Strings and memory

A C string is a char *: the address of some bytes, ending in a zero byte ('\0'). There's no length stored anywhere and no automatic growth. That's why plain C string code is a common source of bugs.

Heap memory

char *copy = xstrdup("hello");   /* allocate and copy */
…
free(copy);                       /* give it back */

Git wraps malloc in xmalloc, xcalloc, xstrdup and friends. They never return NULL; they stop the program if memory runs out. Use them, not the raw versions.

strbuf: Git's growable string

struct strbuf {
	size_t alloc;
	size_t len;
	char *buf;
};
#define STRBUF_INIT  { .buf = strbuf_slopbuf }
struct strbuf sb = STRBUF_INIT;
strbuf_addstr(&sb, "refs/heads/");
strbuf_addf(&sb, "%s", branch);
use(sb.buf);
strbuf_release(&sb);              /* frees the memory */

strbuf tracks the length and grows as needed. Almost all string building in Git goes through it.

Banned functions

banned.h makes strcpy, strcat, sprintf and a few others fail to compile, because they can write past the end of a buffer. If you reach for one, use strbuf or xsnprintf instead.

Freeing safely

#define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)

Setting the pointer to NULL after freeing means a second free does nothing, instead of corrupting memory.

Exercise

In plain C (no Git helpers), what's wrong with this?

char name[8];
strcpy(name, "refs/heads/main");
Answer

The string needs 16 bytes (15 characters plus the zero byte), but name holds 8. strcpy writes past the end and overwrites whatever is next in memory. That's exactly why Git bans it.

Practice in your browser · 5 of 9

Strings and memory: write your own strdup

Write my_strdup(): allocate strlen(s) + 1 bytes (the +1 is for the zero byte at the end), copy the string in, and return it. Then free it in main.

Expected output:

refs/heads/main (15 chars)
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static char *my_strdup(const char *s)
{
	size_t len = strlen(s) + 1;
	char *copy = malloc(len);

	if (!copy)
		return NULL;
	memcpy(copy, s, len);
	return copy;
}

int main(void)
{
	char *copy = my_strdup("refs/heads/main");

	if (!copy)
		return 1;
	printf("%s (%zu chars)\n", copy, strlen(copy));
	free(copy);
	return 0;
}
Level 5 usage.c · merge-blobs.c

Errors, die() and goto cleanup

C has no exceptions. Git handles errors in two ways:

WayWhat happensWhen
return -1; or return error(_("…"));The function reports failure; the caller decides what to do. error() prints a message and returns -1.Library code that callers might recover from
die(_("…"));Prints a message and ends the whole processCommands that can't continue

die is declared NORETURN (git-compat-util.h:419), telling the compiler it never comes back. _("…") marks a message for translation.

This matters for libification. A library must never kill the program it's running inside. Part of the global-state work is changing library code from die() to returning an error the caller can handle.

goto for cleanup

if (fill_mmfile_blob(&f1, our) < 0)
	goto out_no_mmfile;
if (fill_mmfile_blob(&f2, their) < 0)
	goto out_free_f1;
…
out_free_f2_f1:
	free_mmfile(&f2);
out_free_f1:
	free_mmfile(&f1);
out_no_mmfile:
	return res;

goto jumps to a label. In Git it's used for one thing: when something fails halfway, jump to the right point in a list of cleanups so everything allocated so far is freed exactly once. The labels run top to bottom, so jumping to a later label skips cleanups for things not yet allocated.

Exercise

If the second fill_mmfile_blob fails, which buffers get freed, and why not f2?

Answer

It jumps to out_free_f1, so only f1 is freed with free_mmfile(&f1). The out_free_f2_f1 label above it is skipped. f2 was never filled, so there's nothing to free.

Practice in your browser · 6 of 9

goto cleanup

load() allocates two buffers. If the second allocation fails, it must free the first and return -1. Finish the cleanup labels so each buffer is freed exactly once. (The fake allocator fails on its 2nd call so you can see the error path.)

Expected output:

allocated 10 bytes
freed a
load returned -1
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>
#include <stdlib.h>

static int calls;

static void *fake_alloc(size_t n)
{
	if (++calls == 2)
		return NULL; /* pretend we ran out of memory */
	printf("allocated %zu bytes\n", n);
	return malloc(n);
}

static int load(void)
{
	char *a, *b;
	int ret = -1;

	a = fake_alloc(10);
	if (!a)
		goto out;
	b = fake_alloc(20);
	if (!b)
		goto out_free_a;

	ret = 0;
	free(b);
out_free_a:
	free(a);
	printf("freed a\n");
out:
	return ret;
}

int main(void)
{
	printf("load returned %d\n", load());
	return 0;
}
Level 6 environment.h · repository.h · compat/posix.h

The preprocessor and USE_THE_REPOSITORY_VARIABLE

Lines starting with # run before compiling. They paste files, define text replacements, and switch code on and off.

DirectiveDoes
#include "x.h"Paste the file in
#define NAME valueReplace NAME with value everywhere after
#define F(x) …A macro that takes arguments, like FREE_AND_NULL(p)
#ifdef NAME … #endifKeep the code in between only if NAME is defined

The switch at the heart of the project

#ifdef USE_THE_REPOSITORY_VARIABLE
extern struct repository *the_repository;
#endif

A file can only see the_repository if it defines USE_THE_REPOSITORY_VARIABLE at the very top, before any include. environment.h hides its remaining global config variables behind the same switch. So:

  • A file with #define USE_THE_REPOSITORY_VARIABLE still depends on global state.
  • When you remove that line and the file still compiles, the file is free of it. The compiler proves it for you.
git grep -l "^#define USE_THE_REPOSITORY_VARIABLE" -- "*.c" | wc -l

In Git v2.56.0 that prints 248 files, 109 of them outside builtin/ and t/. Each one is a possible piece of work. The number shrinks as people send patches.

Other macros you'll meet

  • UNUSED: marks a parameter the function ignores, to silence a warning. cmd_hash_object(…, struct repository *repo UNUSED) takes a repository but doesn't use it yet.
  • ARRAY_SIZE(x): the number of elements in a fixed array.
  • do { … } while (0): wraps a multi-statement macro so it behaves like one statement after an if.
Exercise

In a scratch copy of Git, delete the #define USE_THE_REPOSITORY_VARIABLE line from prune-packed.c and run make prune-packed.o. Read the errors. Then put the line back.

Answer

You get errors like “use of undeclared identifier 'the_repository'” at each place the file uses it. That list is exactly the work needed to free the file from the global.

Practice in your browser · 7 of 9

Macros from git-compat-util.h

Git defines ARRAY_SIZE and FREE_AND_NULL in git-compat-util.h. Write simple versions of both and use them.

Expected output:

samples: 4
buf is NULL
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>
#include <stdlib.h>

#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)

int main(void)
{
	int bits[] = { 8, 8, 8, 8 };
	char *buf = malloc(16);

	printf("samples: %zu\n", ARRAY_SIZE(bits));
	FREE_AND_NULL(buf);
	printf("buf is %s\n", buf ? "set" : "NULL");
	return 0;
}
Level 7 repository.c · prune-packed.c · environment.c

Scope, static and global variables

Where it's declaredLivesVisible to
Inside a functionUntil the function returnsThat function
static inside a functionThe whole program runThat function (keeps its value between calls)
static at file levelThe whole program runThat .c file only
File level, not staticThe whole program runAny file that declares it extern

The last two rows are global state: one copy for the whole process.

How the_repository is made

/* The main repository */
static struct repository the_repo;
struct repository *the_repository = &the_repo;

One struct, private to this file, and one global pointer to it that any file can use through the extern declaration from Level 6.

Why globals are a problem

  • Hidden inputs. You can't tell from a function's parameters which repository it works on. It might quietly use the global.
  • Only one repository. A program that wants to work with two repositories at once (a submodule, or a server hosting thousands) can't, because the global points at just one.
  • Threads. Two threads changing the same global can corrupt it.

A small real example

static struct progress *progress;            /* file-level global */

static int prune_object(const struct object_id *oid, const char *path,
			 void *data)
{
	…
	if (!has_object_pack(the_repository, oid))   /* the global repository */
		return 0;
	…
}
Exercise

Read all of prune-packed.c (it's about 50 lines). List every use of global state. Then find who calls prune_packed_objects() with git grep, and check whether those callers already have a repository they could pass in.

Hint

There are three uses of the_repository and one file-level static. The interesting question is the callers: if they already hold a struct repository *, the change could follow the same pattern as Level 3. Work it out yourself, and check the mailing list archive first in case someone is already doing it.

Practice in your browser · 8 of 9

Global state vs. passing it in

counter is a global, like the_repository. Remove the global: make bump() take a pointer to the counter it should change, and keep two separate counters in main.

Expected output:

a=2 b=1
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>

static int bump(int *count)
{
	return ++*count;
}

int main(void)
{
	int a = 0, b = 0;

	bump(&a);
	bump(&a);
	bump(&b);
	printf("a=%d b=%d\n", a, b);
	return 0;
}
Level 8 prune-packed.c

Function pointers, callbacks and void *data

In C you can pass a function to another function. Git uses this for “do something for each X” loops:

for_each_loose_file_in_source(the_repository->objects->sources,
			      prune_object, NULL, prune_subdir, &opts);

prune_object and prune_subdir are passed without (), so they aren't called here; their addresses are handed over, and the loop calls them for each file and folder.

The void *data trick

static int prune_object(const struct object_id *oid, const char *path,
			 void *data)
{
	int *opts = data;      /* we know it's really an int * */
	…
}

The loop doesn't know what extra information your callback needs, so it carries a void *, a pointer to anything. You pass &opts in, and the callback turns it back into the right type.

This is also how callbacks can get a repository without using the global: pack the repository into a small struct, and pass that struct as data. You'll see this pattern in many global-state patches.

Exercise

Write void for_each_int(int *xs, int n, void (*fn)(int, void *), void *data) and use it to sum an array into an int passed through data.

Answer
static void add_one(int x, void *data)
{
	int *sum = data;
	*sum += x;
}
…
int sum = 0;
for_each_int(xs, 3, add_one, &sum);
Practice in your browser · 9 of 9

Callbacks with void *data

Like Git's for_each_remote(), for_each_int() calls a function for every item and passes a void *data along. Write add_one() so it adds each number into the int that data points to.

Expected output:

sum=6
Press Run to compile and run this program with gcc.
Show a solution
#include <stdio.h>

typedef void (*each_int_fn)(int value, void *data);

static void for_each_int(const int *xs, int n, each_int_fn fn, void *data)
{
	for (int i = 0; i < n; i++)
		fn(xs[i], data);
}

static void add_one(int value, void *data)
{
	int *sum = data;
	*sum += value;
}

int main(void)
{
	int xs[] = { 1, 2, 3 };
	int sum = 0;

	for_each_int(xs, 3, add_one, &sum);
	printf("sum=%d\n", sum);
	return 0;
}
Level 9 git.c · builtin/*.c

How a command runs

{ "merge-tree", cmd_merge_tree, RUN_SETUP },

A table maps each command name to a function and some flags. RUN_SETUP means “find the repository first”. run_builtin() (git.c:470) then does roughly this:

if (run_setup & RUN_SETUP) {
	prefix = setup_git_directory(the_repository);
	no_repo = 0;
}
…
status = p->fn(argc, argv, prefix, no_repo ? NULL : repo);

Every builtin has the same signature:

int cmd_hash_object(int argc,
		    const char **argv,
		    const char *prefix,
		    struct repository *repo UNUSED)
  • argc and argv: the number of words on the command line and the words themselves. const char ** is a pointer to a list of strings.
  • prefix: where you ran the command, relative to the top of the work tree.
  • repo: the repository, passed explicitly. It's NULL when there's no repository.

So builtins already receive the repository. A lot of the global-state work is threading this repo parameter down into the functions the builtin calls, so they stop using the_repository. Options are read with the parse-options API (parse-options.h), which is another Outreachy project's topic.

Lab 2 browser + your terminal

Debugging: sanitizers and a debugger

Sooner or later your change will crash or leak memory. Git's developers use two kinds of tools for this, and so will you.

Part 1: sanitizers catch memory bugs for you

A sanitizer is a compiler option that adds checks to your program. AddressSanitizer stops the program the moment it touches memory it shouldn't, and LeakSanitizer reports memory that was never freed. Try both in your browser first:

Practice in your browser · debugging 1 of 2

Find a buffer overflow with AddressSanitizer

This program writes one element past the end of its array. Press ▶ Run and read the report: it names the bug (heap-buffer-overflow) and the exact line. Then fix the loop so Check passes with no report.

Expected output when fixed:

last: 20
Press Run to compile this program with AddressSanitizer turned on.
Show a solution
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	int count = 3;
	int *nums = malloc(count * sizeof(int));

	if (!nums)
		return 1;
	for (int i = 0; i < count; i++)
		nums[i] = i * 10;
	printf("last: %d\n", nums[count - 1]);
	free(nums);
	return 0;
}
Practice in your browser · debugging 2 of 2

Find a memory leak with LeakSanitizer

This program forgets to give memory back. Press ▶ Run: instead of the branch name you get a report that says LeakSanitizer: detected memory leaks and shows the line where the memory was allocated. Fix it so the program prints the branch and exits cleanly (exit code 0).

Expected output when fixed:

branch: refs/heads/main
Press Run to compile this program with AddressSanitizer turned on.
Show a solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
	char *copy = strdup("refs/heads/main");

	if (!copy)
		return 1;
	printf("branch: %s\n", copy);
	free(copy);
	return 0;
}

Part 2: build Git with a sanitizer

Git's Makefile has a SANITIZE option (Makefile:1618), and Git's CI uses it in two jobs: linux-leaks runs with SANITIZE=leak, and linux-asan-ubsan with SANITIZE=address,undefined (ci/lib.sh:380). If your patch leaks memory, those CI jobs will catch it, so it's better to catch it first yourself.

make -j4 NO_RUST=1 SANITIZE=address
cd t && ./t0001-init.sh
What you should see
# passed all 103 test(s)
1..103
On a Mac: SANITIZE=address works, but SANITIZE=leak doesn't. Apple's clang refuses it (unsupported option '-fsanitize=leak' for target 'arm64-apple-darwin…'). Use Linux or WSL for leak checks, which is also where Git's CI runs them.

A sanitizer build is slower, so build normally again afterwards: make -j4 NO_RUST=1.

Part 3: stop Git in a debugger

A debugger lets you pause a running program, look at its variables, and see which functions called which. By default Git is built with optimization (CFLAGS = -g -O2 -Wall, Makefile:978), which makes variables hard to inspect. Rebuild without optimization first:

make -j4 NO_RUST=1 CFLAGS="-g -O0 -Wall"

On Linux and WSL, use gdb. Git's own test wrapper starts gdb as gdb --args ./git … (see bin-wrappers/git after you build):

gdb --args ./git version

Then, at the (gdb) prompt, type break cmd_version, then run, then bt (backtrace), then quit.

On macOS, use lldb:

lldb -- ./git version

At the (lldb) prompt: breakpoint set -n cmd_version, then run, then bt, then quit. Here's real lldb output from Git v2.56.0:

What you should see
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: git`cmd_version(argc=1, argv=..., prefix=0x0000000000000000, ...) at help.c:835:16
    frame #1: git`run_builtin(p=..., argc=1, argv=..., repo=...) at git.c:510:11
    frame #2: git`handle_builtin(args=...) at git.c:786:9

Read the backtrace from the bottom up: handle_builtin called run_builtin (the line from Level 9: status = p->fn(…) at git.c:510), which called cmd_version (help.c:833). That's how you find out how Git reached any line of code.

Inside a test script, t/README documents the debug helper: put debug in front of a git command in a test (for example debug git init plain) to run that command under gdb. Use debug -d "lldb --" git init plain to pick lldb instead. Also test_pause stops a test and opens a shell in its trash directory. Remove both before sending a patch (t/README:909, t/README:1143).

Level 10 the project itself

Patterns for removing global state

Read past patches before writing your own. Find them with:

git log --oneline --grep="the_repository" | head -30

You'll see subjects like “refspec: stop depending on `the_repository`”, “copy: drop dependency on `the_repository`” and “refs: remove remaining uses of `the_repository`”. Read the full messages and diffs with git show <hash>. Most follow one of these patterns:

Pattern 1: pass the repository in

Add a struct repository *r parameter, use r instead of the global, and update every caller. If a caller already has a repository (a parameter, istate->repo, a field of some struct), use that. This is what the preload-index commit in Level 3 does.

Pattern 2: move global config into the repository

Old code kept settings in globals filled from config. Newer code keeps them in struct repo_settings or struct repo_config_values and reads them through a function that takes the repository:

int repo_trust_executable_bit(struct repository *repo)
{
	return repo->initialized
		? repo_config_values(repo)->trust_executable_bit
		: 1;
}

Notice the fallback: if the repository isn't set up yet, it returns the default (1). Edge cases like this are what reviewers look for.

Pattern 3: replace die() with a returned error

Where library code calls die(), change it to return error(…) and make callers handle the failure. Callers in builtin/ can still die if that's right for the command.

How to keep it reviewable

  • One small, focused change per commit. Changing a function's signature and updating its callers is one commit; a separate cleanup is another.
  • No change in behaviour. Say so in the commit message, and prove it: the existing tests must still pass.
  • Check lore before you start, in case someone is already working on the same file.
Level 11 t/

Reading and running Git's tests

#!/bin/sh

test_description='git init'

. ./test-lib.sh

test_expect_success 'plain' '
	git init plain &&
	check_config plain/.git false unset
'
  • . ./test-lib.sh loads the test framework.
  • test_expect_success 'name' '…commands…' runs the commands and passes if they all succeed.
  • Commands are joined with && so that one failure fails the test. A missing && silently hides failures, and Git checks for that.
  • Helpers like test_cmp expect actual, test_path_is_file and test_must_fail git … do the checking.
cd t
./t0001-init.sh -v -i       # -v verbose, -i stop at first failure
./t0001-init.sh -x          # show every shell command as it runs
make test                   # everything (slow)

Refactoring patches usually add no tests; the existing ones prove nothing changed. Find which tests cover your file: git grep -l "merge-tree" t/.

Lab 3 your terminal · needs Lab 1

Write your first Git test

Many patches need a test. Here you'll add one, watch it fail, then make it pass. Do this in the Git folder from Lab 1, on a practice branch:

cd ~/git && git switch -c practice-first-test

1. Add the test

Open t/t0001-init.sh in your editor. Scroll to the very end: the last line is test_done. Add this just above it (indent with a tab):

test_expect_success 'init creates HEAD' '
	git init head-check &&
	test_path_is_file head-check/.git/HEAD
'
  • test_expect_success 'name' '…' defines one test, which passes if every command succeeds.
  • The commands are joined with &&, so any failure fails the test.
  • test_path_is_file is a helper from t/README:1080. Unlike plain test -f, it prints a message when it fails.

2. Run just your test

cd t && ./t0001-init.sh --run=104 -v
What you should see
...
ok 103 # skip init honors GIT_OBJECT_DIRECTORY (--run)

expecting success of 0001.104 'init creates HEAD':
	git init head-check &&
	test_path_is_file head-check/.git/HEAD

Initialized empty Git repository in .../trash directory.t0001-init/head-check/.git/
ok 104 - init creates HEAD

# passed all 104 test(s)
1..104

Your test is number 104, because t0001 already has 103.

3. Break it on purpose

Change HEAD to HEADD in your test and run it again with -v -i:

./t0001-init.sh --run=104 -v -i
What you should see
...
Initialized empty Git repository in .../trash directory.t0001-init/head-check/.git/
File head-check/.git/HEADD doesn't exist
not ok 104 - init creates HEAD
#
#		git init head-check &&
#		test_path_is_file head-check/.git/HEADD
#

That first line is the helper telling you exactly what was wrong. Learning to read failures like this is most of the work. Change it back to HEAD and run the whole file: it should say passed all 104.

4. Commit it (practice only)

Git needs to know who you are, once:

git config --global user.name "Your Name"
git config --global user.email "you@example.com"
cd .. && git add t/t0001-init.sh && git commit -s -m "t0001: check that init creates HEAD"

This is a practice commit only: don't send it to the list. Lab 4 uses it to practise sending, safely.

Level 12 Documentation/SubmittingPatches

From commit to the mailing list

Git doesn't use pull requests. Patches go to git@vger.kernel.org as plain-text emails, and review happens by reply.

The commit message

This is the message of the merged commit from Level 3, exactly as it is in Git's history:

preload-index: stop depending on 'the_repository'

Refactor "preload-index.c" to remove the dependency on the global
'the_repository'. Replace the occurrences of 'the_repository' with
'index->repo' and thus remove the definition '#define
USE_THE_REPOSITORY_VARIABLE'.

Mentored-by: Christian Couder <christian.couder@gmail.com>
Mentored-by: Ghanshyam Thakkar <shyamthakkar001@gmail.com>
Signed-off-by: Ayush Chandekar <ayu.chandekar@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
  • Subject: area: what changes, lowercase after the colon, no full stop, under about 50 characters.
  • Body: explain why, in the present tense, as orders to the code (“Pass it…”, “Remove…”). Wrap at about 72 characters.
  • Signed-off-by: added with git commit -s. It certifies you wrote the change and may submit it (the Developer's Certificate of Origin, described in Documentation/SubmittingPatches). The second one is the maintainer's, added when he applied the patch.
  • Mentored-by: a trailer crediting the mentors who guided the work, common on GSoC and Outreachy patches.

Sending

git format-patch -1 -o outgoing/                    # one commit → one email file
git send-email --dry-run --to=git@vger.kernel.org outgoing/*
git send-email --to=git@vger.kernel.org outgoing/*  # for real

Always do the dry run first and read what will be sent. Put mentors on Cc as the project asks.

After sending

  • Find your email on lore.kernel.org/git and watch for replies.
  • Reply inline, below the text you're answering. Thank reviewers, and explain or fix every point.
  • Send a new version with git format-patch -v2. Say what changed since v1 (the cover letter or below the --- line), and git range-diff shows the difference.
  • The maintainer's “What's cooking” emails show where accepted patches are: seen, next, then master.
Lab 4 your terminal · needs Lab 3

Practise sending a patch, safely

Sending your first email to the Git list is scary. Here you go through every step without anything leaving your computer, using the practice commit from Lab 3.

1. Turn the commit into a patch file

git format-patch -1 -o ~/outgoing
What you should see
/home/you/outgoing/0001-t0001-check-that-init-creates-HEAD.patch

Open that file in your editor. It's a plain email: From:, Subject: [PATCH] …, your message, a --- line, then the diff. Anything you write between --- and the diff is seen by reviewers but not saved in history. That's where "Changes since v1" notes go.

2. Dry run: see exactly what would be sent

git send-email --dry-run --to=you@example.com ~/outgoing/*.patch

--dry-run does everything except send, so it's safe even before you've set up email. Here's real output from a fresh setup with no email settings:

What you should see
Dry-OK. Log says:
...
From: Your Name <you@example.com>
To: you@example.com
Subject: [PATCH] t0001: check that init creates HEAD
...
Result: OK

Check three things every time: To (the list: git@vger.kernel.org), Cc (the people who should see it), and Subject. On Linux/WSL, if Git says send-email is not a git command, install the git-email package (section B).

3. Before the real thing: set up email

Git's own send-email documentation has a "Use Gmail as the SMTP Server" example (git-send-email.adoc:571). Put this in ~/.gitconfig:

[sendemail]
	smtpEncryption = ssl
	smtpServer = smtp.gmail.com
	smtpUser = yourname@gmail.com
	smtpServerPort = 465

The same page notes Gmail doesn't accept your normal password here: you need an app password (with two-factor sign-in turned on) or OAuth. The list also drops HTML email, so use git send-email rather than pasting into a mail app.

4. Practise for real, to yourself only

Once email is set up, send the practice patch to your own address (not the list), and open it in your inbox to see what reviewers will see:

git send-email --to=you@example.com ~/outgoing/*.patch

Don't want to set up email?

Git's SubmittingPatches says you can send patches with GitGitGadget or b4 instead of send-email (SubmittingPatches:673). GitGitGadget turns a GitHub pull request into mailing-list email, which many Windows users find easier.

Clean up

git switch --detach v2.56.0 && git branch -D practice-first-test
Beyond the levels t/README · CodingGuidelines · po/README.md

Microproject patterns in Git's own rules

Git's microprojects are small fixes that bring old code in line with rules Git already documents. Each pattern below comes from one of those documents, with the command that finds the places that don't follow it yet, and a real example line from v2.56.0.

Before you pick one:

  • The counts are search hits, not confirmed bugs. Read every hit; some are deliberate (for example, t/t0000-basic.sh tests test_must_fail itself).
  • Run the same command on master: someone may already have fixed it since v2.56.0.
  • Search lore.kernel.org/git for the file name. Other applicants may be working on the same file.
  • Git's applicant guide asks for one microproject per applicant: see General Microproject Information.
  • Fix one file (or one small group of the same mistake) per patch, and run that file's tests: cd t && ./t0081-find-pack.sh -v.

Check files with the test helpers

The rule: t/README:1080: test_path_is_file, test_path_is_dir, test_path_is_missing.

Plain test -f fails silently. The helpers print what was wrong, which makes failures easier to debug.

git grep -n -E '^[[:space:]]+test -[fde] ' v2.56.0 -- 't/t[0-9]*.sh'

In v2.56.0: 132 lines in 61 files. For example, t/t0081-find-pack.sh:35:

test -f "$head_commit_pack" &&

Use test_must_fail for git

The rule: t/README:723: don't use ! git cmd.

! git also passes when git crashes (a segfault). test_must_fail only accepts a controlled failure. The same section says not to use it for non-git commands.

git grep -n -E '^[[:space:]]+! git ' v2.56.0 -- 't/t[0-9]*.sh'

In v2.56.0: 40 lines in 15 files. For example, t/t1467-refs-rename.sh:91:

! git refs rename refs/heads/symref refs/heads/renamed 2>err &&

Don't pipe git's output

The rule: t/README:732: don't feed git's output to a pipe.

In a pipe, only the last command's exit code counts, so a crashing git goes unnoticed. Write to a file first, then process the file.

git grep -n -E '^[[:space:]]+git [^|]*[^|]\|[^|]' v2.56.0 -- 't/t[0-9]*.sh'

In v2.56.0: 375 lines in 113 files. For example, t/t0001-init.sh:671:

git version --build-options | sed -ne "s/^default-ref-format: //p" >expect &&

Split one-line if …; then

The rule: CodingGuidelines:120: then goes on the next line.

A pure style fix. Group all the instances in one test file into one patch.

git grep -n -E '^[[:space:]]+if .*; then[[:space:]]*$' v2.56.0 -- 't/t[0-9]*.sh'

In v2.56.0: 48 lines in 24 files. For example, t/t0600-reffiles-backend.sh:322:

if test $i = 75; then

Plural messages with Q_()

The rule: po/README.md:312: Q_("%d commit", "%d commits", n).

With _(), a count of 1 still says "islands". Many hits are fine: already inside a Q_() on the line before, or the number can never be 1. Check each one by hand.

git grep -n -E '_\("[^"]*%d[^"]* [a-z]+s[ .,]' v2.56.0 -- '*.c'

In v2.56.0: a few dozen hits; most are not bugs. For example, delta-islands.c:499:

fprintf(stderr, _("Marked %d islands, done.\n"), island_counter);

Stop using the_repository

The rule: repository.h:228: the global is only visible with USE_THE_REPOSITORY_VARIABLE.

Levels 6, 7 and 10. Start with small files whose callers already have a repository. Some are much harder than they look.

git grep -l '^#define USE_THE_REPOSITORY_VARIABLE' v2.56.0 -- '*.c' ':!builtin' ':!t'

In v2.56.0: 109 library files (101 more in builtin/). For example, prune-packed.c:1:

#define USE_THE_REPOSITORY_VARIABLE

Replace strbuf_split*()

The rule: commit 2ab72a16d9: "gpg-interface: do not use misdesigned strbuf_split*()".

These return an array of strbufs that callers must free one by one. That commit replaced them with string_list_split(); read it before trying another call site.

git grep -n -E 'strbuf_split(_buf|_str|_max)?\(' v2.56.0 -- '*.c' ':!strbuf.c' ':!t'

In v2.56.0: 3 calls in 3 files. For example, mailinfo.c:1105:

lines = strbuf_split(line, '\n');
Exercise

Run the test -f search on master instead of v2.56.0. Is the count different? Pick one hit, read the whole test it's in, and decide which helper (test_path_is_file, _dir or _missing) matches what the test means.

Hint

Look at the flag: -f is a file, -d a directory, -e "exists". ! test -f x usually means the path must be missing. If the code is inside an if (a condition, not a check), it may be correct as it is.

Hero every level in one path

Trace a repository from the command line to merge_blobs

Open the files side by side and follow the repository as it travels.

  1. You type git merge-tree …. main in git.c finds { "merge-tree", cmd_merge_tree, RUN_SETUP } in the command table (L0, L9).
  2. run_builtin() sees RUN_SETUP and calls setup_git_directory(the_repository), which fills in the global struct from repository.c (L7).
  3. It calls the builtin through a function pointer: p->fn(argc, argv, prefix, repo) (L8, L9).
  4. Inside builtin/merge-tree.c, which still defines USE_THE_REPOSITORY_VARIABLE (L6), the code calls merge_blobs(the_repository->index, path, base, our, their, size) (builtin/merge-tree.c:95).
  5. merge_blobs() (merge-blobs.c:62) gets the index as struct index_state *istate, a pointer (L3).
  6. It calls fill_mmfile_blob(&f1, our) (merge-blobs.c:86); the &f1 is an out-parameter (L3).
  7. fill_mmfile_blob reads the object with odb_read_object(the_repository->objects, …) (merge-blobs.c:15), because merge-blobs.c still defines USE_THE_REPOSITORY_VARIABLE in v2.56.0. If the read fails it returns -1, and the caller jumps to its cleanup label (L5).

Notice where the global still appears: in steps 4 and 7. Step 7 is library code, and the fix is Pattern 1: merge_blobs() already holds the index, and the index knows its repository (istate->repo), so that repository can be passed down to fill_mmfile_blob(), exactly like the preload-index commit. Step 4 is different: it's in a builtin, and in step 3 that repo parameter is NULL when there's no repository (no_repo ? NULL : repo, git.c:510). So global-state work usually targets library files first. If you can explain every step of this list without looking, you're ready to read and write global-state patches.

After this

Where to go from here

  • Git's own documents: Documentation/MyFirstContribution.adoc, Documentation/SubmittingPatches and CodingGuidelines, plus General Microproject Information and Hacking Git.
  • C itself: The C Programming Language by Kernighan and Ritchie is short and still the best introduction. Modern C by Jens Gustedt is free online.
  • Shell: read t/README, which documents every test helper.
  • Read patches every day: pick one thread on lore that touches the_repository and read it from v1 to the final version. You'll learn what reviewers care about faster than any other way.

Help make this guide better

Every fact here is meant to come from Git's own code and documentation, pinned to v2.56.0, but no guide is perfect. If something is wrong, out of date, or confusing, open an issue. Corrections from experienced Git contributors are especially welcome.

Reference

Glossary

TermMeaningLevel
CompilerTurns .c files into a program (gcc, clang)A, C
Header / source.h declares, .c defines1
Declaration / definition“This exists” versus “here it is”1
Include guard#ifndef X_H / #define X_H / #endif1
Forward declarationstruct foo; with no body; enough for pointers1
StructA group of named fields2
EnumNamed integer constants2
Designated initializer{ .field = value }2
PointerA variable holding an address; *, &, ->3
NULLA pointer to nothing3
Out-parameterA pointer argument the function writes a result into3
Heap, malloc, freeMemory you ask for and must give back4
strbufGit's growable string4
Memory leakMemory that's never freed4
die() / error()End the process / print and return -15
Preprocessor, macro# lines run before compiling; text replacement6
USE_THE_REPOSITORY_VARIABLEThe switch that makes the_repository visible in a file6
staticAt file level: private to the file. In a function: keeps its value.7
externDeclares a global defined in another file7
Global stateData reachable from anywhere, one copy per process7
Function pointer, callbackPassing a function for another to call8
void *A pointer to anything; used for callback data8
Builtin, cmd_*A command's C function9
the_repositoryThe global pointer to the current repositoryD, 7
repo_settings, repo_config_valuesPer-repository homes for settings that used to be globals10
LibificationMaking Git's code usable as a libraryD, 10
test_expect_successDefines one shell test11
Signed-off-by, DCOYour certification that you may submit the patch12
loreThe public mailing-list archive12
range-diffShows what changed between two versions of a series12