#!/usr/bin/env perl
########################################################################
# Locate the project root, the directory holding the nearest
# .git/config above the program's directory.  See POD.
########################################################################

use v5.40;

use File::Basename  qw( dirname );

use FindBin::Bin    qw( $Bin_p );

use FindBin::Files  qw( file=.git/config scalar export=git_config nofail );

$git_config
or die "No .git/config in any directory above '$Bin_p'.\n";

# $root_d/.git/config

my $root_d  = dirname dirname $git_config;

say "Project root: $root_d";

__END__

=head1 NAME

find_project_root - locate the project root from the nearest .git/config

=head1 SYNOPSIS

    find_project_root

=head1 DESCRIPTION

    use FindBin::Files qw( file=.git/config scalar export=git_config nofail );

    my $root_d = dirname dirname $git_config;

Every git checkout has a C<.git/config> file at its top: the nearest
one above the program marks the root of the project the program is
in.  From there the program can locate files by their place in the
project rather than by their distance from C<bin>, e.g.,
C<catdir $root_d, qw( share templates )>.

FindBin::Files matches files only: C<.git> is a directory in a
checkout, so the marker is C<.git/config>, which is a file.
C<export=git_config> keeps the default name, C<@config>, from being
mistaken for the program's own configuration.

Any file the project always has at its top works the same way, e.g.,
C<file=Makefile.PL> for a Perl distribution.

=head2 Worktrees and submodules

In a C<git worktree> or a submodule C<.git> is a file holding the
path of the real git directory, so there is no C<.git/config> at its
top.  The walk passes over it and finds the C<.git/config> of an
enclosing checkout, the wrong root, or nothing at all.  For a program
that is installed in a worktree or submodule, search for the C<.git>
file instead (a plain checkout has none: there it is a directory):

    use FindBin::Files qw( file=.git scalar export=git_file nofail );

    my $root_d = dirname $git_file;

or ask git, C<git -C $Bin_p rev-parse --show-toplevel>, which handles
every layout.

=head1 SEE ALSO

L<FindBin::Files>, L<git-worktree(1)>, L<git-rev-parse(1)>
