#!/usr/bin/env perl
########################################################################
# Locate every git checkout above the program's directory: one means
# the program is in a main project, more than one that it is in a
# sub-project checked out inside another.  See POD.
########################################################################

use v5.40;

use File::Basename  qw( dirname );

use FindBin::Bin    qw( $Bin_p );

# export implies nouse: the .git dirs are not added to @INC.

use FindBin::libs   qw( base=.git export=root_dirs nofail );

@root_dirs
or die "No .git directory in any directory above '$Bin_p'.\n";

# nearest first: this project, then each one enclosing it.

my ( $project_d, @outer_dz ) = map { dirname $_ } @root_dirs;

if( @outer_dz )
{
    say "Sub-project: $project_d";
    say "  inside:    $_"
    for @outer_dz;
}
else
{
    say "Main project: $project_d";
}

__END__

=head1 NAME

project_roots - tell a sub-project from a main project by its .git dirs

=head1 SYNOPSIS

    project_roots

=head1 DESCRIPTION

    use FindBin::libs qw( base=.git export=root_dirs nofail );

exports C<@root_dirs>, every C<.git> directory from C<$Bin_p> up to
the root, nearest first.  Each one marks the top of a checkout, its
C<dirname>.  The number of entries says where the program is:

=over 4

=item One

The program is in a main project, C<dirname $root_dirs[0]>.

=item More than one

The program is in a sub-project: a checkout inside another one, e.g.,
a library cloned into a project's F<vendor> directory.
C<$root_dirs[0]> is the sub-project's, C<$root_dirs[-1]> the
outermost project's.

=item None

The program is not in a checkout, e.g., it was installed from a
tarball.

=back

For a program in C</work/app/vendor/lib-foo/bin>:

    /work/app/.git
    /work/app/vendor/lib-foo/.git

    Sub-project: /work/app/vendor/lib-foo
      inside:    /work/app

C<export> turns off C<use lib>, so the C<.git> dirs are not added to
C<@INC>.  The default C<ignore=/,/usr> skips C</.git> and
C</usr/.git>.

=head2 Submodules and worktrees

FindBin::libs finds directories only.  In a git submodule or a
C<git worktree>, C<.git> is a file holding the path of the real git
directory, so it is skipped: a submodule looks like part of the
project that contains it, and a worktree outside any other checkout
has no entry at all.  F<example/find_project_root> shows how to find
the C<.git> file with L<FindBin::Files>; C<git rev-parse
--show-superproject-working-tree> tells a submodule from its project.

=head1 SEE ALSO

L<FindBin::libs>, F<example/find_project_root>
