#!perl

use 5.010001;
use strict;
use warnings;

use Cwd qw(cwd);
use File::chdir;
use Getopt::Long::Complete qw(GetOptionsWithCompletion);

our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2025-11-07'; # DATE
our $DIST = 'App-CdUtils'; # DIST
our $VERSION = '0.013'; # VERSION

# FRAGMENT id=shcompgen-hint completer=1 for=cdprevsibling

my $cwd = $ENV{PWD} || cwd();
my @cwd_elems = split m!/+!, $cwd;
my $cmd = $0 =~ /cdprev/ ? 'cdprevsibling' : 'cdnextsibling';
my $sort_files_opts = $ENV{CDPREVNEXTSIBLING_SORT_FILES_OPTS} // '--by-field=name';
my %opts = (
    num => 1,
    level => 1,
);

GetOptionsWithCompletion(
    sub {
        [];
    },
    'help|h' => sub {
        print <<USAGE;
Usage:
  % $cmd [options]
Options:
  --help, -h
  --version, -v
  --num=i, -n
  --level=i, -l
USAGE
        exit 0;
    },
    'version|v' => sub {
        no warnings 'once';
        print "$cmd version ", ($main::VERSION || "dev"), "\n";
        exit 0;
    },
    'num|n=i' => \$opts{num},
    'level|l=i' => \$opts{level},
);

die "$cmd: Level must be at least 1\n" if $opts{level} < 1;

# we are at the root, no siblings
unless (@cwd_elems - $opts{level} + 1 > 0) {
    print ".\n";
    exit 0;
}

my @dirs;
{
    local $CWD = join("/", map {".."} 1..$opts{level});
    open my $fh, "sort-files $sort_files_opts |"; ## no critic: InputOutput::ProhibitTwoArgOpen
    while (defined(my $e = <$fh>)) {
        chomp $e;
        next unless -d $e;
        push @dirs, $e;
    }
}

my $curpos;
for my $i (0 .. $#dirs) {
    if ($dirs[$i] eq $cwd_elems[-$opts{level}]) {
        $curpos = $i;
        last;
    }
}

$curpos //= 0;
my $newpos = $curpos + $opts{num} * ($cmd eq 'cdprevsibling' ? -1 : 1);
$newpos = 0 if $newpos < 0;
$newpos = @dirs-1 if $newpos >= @dirs;

my @target_elems = (
    (map { ".." } 1 .. $opts{level}),
    $dirs[$newpos],
);
for my $l (reverse (1 .. $opts{level}-1)) {
    if (-d join("/", @target_elems, $cwd_elems[-$l])) {
        push @target_elems, $cwd_elems[-$l];
    } else {
        last;
    }
}

print join("/", @target_elems), "\n";

# ABSTRACT: Change to the "previous" or "next" sibling directory
# PODNAME: cdprevsibling-backend

__END__

=pod

=encoding UTF-8

=head1 NAME

cdprevsibling-backend - Change to the "previous" or "next" sibling directory

=head1 VERSION

This document describes version 0.013 of cdprevsibling-backend (from Perl distribution App-CdUtils), released on 2025-11-07.

=head1 SYNOPSIS

To use in shell:

 % cdprevsibling() { cd `cdprevsibling-backend "$1"`; }
 % cdnextsibling() { cd `cdnextsibling-backend "$1"`; }

 % pwd
 /some/path

 % ls
 four/   one/   three/   two/

 % cd four

 % cdnextsibling
 % pwd
 /some/path/one

 % cdnextsibling -n2
 % pwd
 /some/path/two

 % cdprevsibling -n3
 % pwd
 /some/path/four

 # when there is no previous/next sibling, will stay at the current position
 % cdprevsibling
 % pwd
 /some/path/four

Changing sibling of grandparent (and upper) directory:

 % tree
 .
 ├── A
 │   ├── X0
 │   ├── X1
 │   │   └── Y
 │   └── X2
 └── B
     ├── X0
     ├── X1
     │   └── Z
     └── X2
 11 directories, 0 files

 % cd A/X1
 % cdnextsibling -l2
 % pwd
 /some/path/B/X1
 % cd Z
 % cdprevsibling -l3
 % pwd
 /some/path/A/X1        # (because A/X1/Z is not available)

=head1 DESCRIPTION

B<cdprevsibling> and B<cdnextsibling> are commands to change to "previous" and
"next" sibling directories, respectively. By default, asciibetical ordering is
used. You can change the ordering by setting the
L</CDPREVNEXTSIBLING_SORT_FILES_OPTS> options, as L<sort-files> utility is used
to sort the directories.

=head1 OPTIONS

=head2 --num=i, -n

Integer. Default 1. Sibling distance to go to. 1 means the closest, i.e. if
current position is at number 5, the previous sibling is 4 and next sibling is
6. If this option is 2, it means the second closest, i.e. if current position is
at number 5, previous sibling is 3 and next sibling is 7. And so on.

=head2 --level=i, -l

Integer. Default is 1. Number of level to go upwards to find siblings for. For example:

 A/
   X0/
   X1/
     Y/
   X2/
 B/
   X0/
   X1/
     Z/
   X2/

If current position is C</A/X1> and level is 1, previous sibling would be
C</A/X0> and next sibling would be C</A/X2>.

If current position is C</A/X1> and level is 2, next sibling would be C</B/X1>
because we are finding sibling for C<A>, not C<X1>.

When level is larger than 1, it is possible that the sibling do not have the
same structure. In that case, this script will stop at the last depth where the
same directory can be found. For example, if current position is C</A/X1/Y> and
level is 3, next sibling should be C</B/X1/Y>. However, since the path does not
exist, the script will return C</B/X1>.

=head1 COMPLETION

This script has shell tab completion capability with support for several
shells.

=head2 bash

To activate bash completion for this script, put:

 complete -C cdprevsibling-backend cdprevsibling-backend

in your bash startup (e.g. C<~/.bashrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is recommended, however, that you install modules using L<cpanm-shcompgen>
which can activate shell completion for scripts immediately.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete cdprevsibling-backend 'p/*/`cdprevsibling-backend`/'

in your tcsh startup (e.g. C<~/.tcshrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is also recommended to install C<shcompgen> (see above).

=head2 other shells

For fish and zsh, install C<shcompgen> as described above.

=head1 ENVIRONMENT

=head2 CDPREVNEXTSIBLING_SORT_FILES_OPTS

String. Options to pass to B<sort-files>. Default: C<--by-field name>.

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/App-CdUtils>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-App-CdUtils>.

=head1 SEE ALSO

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 CONTRIBUTING


To contribute, you can send patches by email/via RT, or send pull requests on
GitHub.

Most of the time, you don't need to build the distribution yourself. You can
simply modify the code, then test via:

 % prove -l

If you want to build the distribution (e.g. to try to install it locally on your
system), you can install L<Dist::Zilla>,
L<Dist::Zilla::PluginBundle::Author::PERLANCAR>,
L<Pod::Weaver::PluginBundle::Author::PERLANCAR>, and sometimes one or two other
Dist::Zilla- and/or Pod::Weaver plugins. Any additional steps required beyond
that are considered a bug and can be reported to me.

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2025 by perlancar <perlancar@cpan.org>.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=App-CdUtils>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=cut
