]> Dogcows Code - chaz/git-codeowners/blob - lib/App/Codeowners/Options.pm
cf91cce3d4d16ac5c3d6207c23c210c0f959143a
[chaz/git-codeowners] / lib / App / Codeowners / Options.pm
1 package App::Codeowners::Options;
2 # ABSTRACT: Getopt and shell completion for App::Codeowners
3
4 use v5.10.1;
5 use warnings;
6 use strict;
7
8 use Getopt::Long 2.39 ();
9 use Path::Tiny;
10
11 our $VERSION = '0.46'; # VERSION
12
13 sub pod2usage {
14 eval { require Pod::Usage };
15 if ($@) {
16 my $ref = $VERSION eq '9999.999' ? 'master' : "v$VERSION";
17 my $exit = (@_ == 1 && $_[0] =~ /^\d+$/ && $_[0]) //
18 (@_ % 2 == 0 && {@_}->{'-exitval'}) // 2;
19 print STDERR <<END;
20 Online documentation is available at:
21
22 https://github.com/chazmcgarvey/git-codeowners/blob/$ref/README.md
23
24 Tip: To enable inline documentation, install the Pod::Usage module.
25
26 END
27 exit $exit;
28 }
29 else {
30 Pod::Usage::pod2usage(@_);
31 }
32 }
33
34 sub early_options {
35 return {
36 'color|colour!' => (-t STDOUT ? 1 : 0), ## no critic (InputOutput::ProhibitInteractiveTest)
37 'format|f=s' => undef,
38 'help|h|?' => 0,
39 'manual|man' => 0,
40 'shell-completion:s' => undef,
41 'version|v' => 0,
42 };
43 }
44
45 sub command_options {
46 return {
47 'create' => {},
48 'owners' => {
49 'pattern=s' => '',
50 },
51 'patterns' => {
52 'owner=s' => '',
53 },
54 'projects' => {},
55 'show' => {
56 'owner=s@' => [],
57 'pattern=s@' => [],
58 'project=s@' => [],
59 'patterns!' => 0,
60 'projects!' => undef,
61 },
62 'update' => {},
63 };
64 }
65
66 sub commands {
67 my $self = shift;
68 my @commands = sort keys %{$self->command_options};
69 return @commands;
70 }
71
72 sub options {
73 my $self = shift;
74 my @command_options;
75 if (my $command = $self->{command}) {
76 @command_options = keys %{$self->command_options->{$command} || {}};
77 }
78 return (keys %{$self->early_options}, @command_options);
79 }
80
81 sub new {
82 my $class = shift;
83 my @args = @_;
84
85 my $self = bless {}, $class;
86
87 my @args_copy = @args;
88
89 my $opts = $self->get_options(
90 args => \@args,
91 spec => $self->early_options,
92 config => 'pass_through',
93 ) or pod2usage(2);
94
95 if ($ENV{CODEOWNERS_COMPLETIONS}) {
96 $self->{command} = $args[0] || '';
97 my $cword = $ENV{CWORD};
98 my $cur = $ENV{CUR} || '';
99 # Adjust cword to remove progname
100 while (0 < --$cword) {
101 last if $cur eq ($args_copy[$cword] || '');
102 }
103 $self->completions($cword, @args_copy);
104 exit 0;
105 }
106
107 if ($opts->{version}) {
108 my $progname = path($0)->basename;
109 print "${progname} ${VERSION}\n";
110 exit 0;
111 }
112 if ($opts->{help}) {
113 pod2usage(-exitval => 0, -verbose => 99, -sections => [qw(NAME SYNOPSIS OPTIONS COMMANDS)]);
114 }
115 if ($opts->{manual}) {
116 pod2usage(-exitval => 0, -verbose => 2);
117 }
118 if (defined $opts->{shell_completion}) {
119 $self->shell_completion($opts->{shell_completion});
120 exit 0;
121 }
122
123 # figure out the command (or default to "show")
124 my $command = shift @args;
125 my $command_options = $self->command_options->{$command || ''};
126 if (!$command_options) {
127 unshift @args, $command if defined $command;
128 $command = 'show';
129 $command_options = $self->command_options->{$command};
130 }
131
132 my $more_opts = $self->get_options(
133 args => \@args,
134 spec => $command_options,
135 ) or pod2usage(2);
136
137 %$self = (%$opts, %$more_opts, command => $command, args => \@args);
138 return $self;
139 }
140
141 sub command {
142 my $self = shift;
143 my $command = $self->{command};
144 my @commands = sort keys %{$self->command_options};
145 return if not grep { $_ eq $command } @commands;
146 $command =~ s/[^a-z]/_/g;
147 return $command;
148 }
149
150 sub args {
151 my $self = shift;
152 return @{$self->{args} || []};
153 }
154
155
156 sub get_options {
157 my $self = shift;
158 my $args = {@_ == 1 && ref $_[0] eq 'HASH' ? %{$_[0]} : @_};
159
160 my %options;
161 my %results;
162 while (my ($opt, $default_value) = each %{$args->{spec}}) {
163 my ($name) = $opt =~ /^([^=:!|]+)/;
164 $name =~ s/-/_/g;
165 $results{$name} = $default_value;
166 $options{$opt} = \$results{$name};
167 }
168
169 if (my $fn = $args->{callback}) {
170 $options{'<>'} = sub {
171 my $arg = shift;
172 $fn->($arg, \%results);
173 };
174 }
175
176 my $p = Getopt::Long::Parser->new;
177 $p->configure($args->{config} || 'default');
178 return if !$p->getoptionsfromarray($args->{args}, %options);
179
180 return \%results;
181 }
182
183
184 sub shell_completion {
185 my $self = shift;
186 my $type = lc(shift || 'bash');
187
188 if ($type eq 'bash') {
189 print <<'END';
190 # git-codeowners - Bash completion
191 # To use, eval this code:
192 # eval "$(git-codeowners --shell-completion)"
193 # This will work without the bash-completion package, but handling of colons
194 # in the completion word will work better with bash-completion installed and
195 # enabled.
196 _git_codeowners() {
197 local cur words cword
198 if declare -f _get_comp_words_by_ref >/dev/null
199 then
200 _get_comp_words_by_ref -n : cur cword words
201 else
202 words=("${COMP_WORDS[@]}")
203 cword=${COMP_CWORD}
204 cur=${words[cword]}
205 fi
206 local IFS=$'\n'
207 COMPREPLY=($(CODEOWNERS_COMPLETIONS=1 CWORD="$cword" CUR="$cur" ${words[@]}))
208 # COMPREPLY=($(${words[0]} --completions "$cword" "${words[@]}"))
209 if [[ "$?" -eq 9 ]]
210 then
211 COMPREPLY=($(compgen -A "${COMPREPLY[0]}" -- "$cur"))
212 fi
213 declare -f __ltrim_colon_completions >/dev/null && \
214 __ltrim_colon_completions "$cur"
215 return 0
216 }
217 complete -F _git_codeowners git-codeowners
218 END
219 }
220 else {
221 # TODO - Would be nice to support Zsh
222 warn "No such shell completion: $type\n";
223 }
224 }
225
226
227 sub completions {
228 my $self = shift;
229 my $cword = shift;
230 my @words = @_;
231
232 my $current = $words[$cword] || '';
233 my $prev = $words[$cword - 1] || '';
234
235 my $reply;
236
237 if ($prev eq '--format' || $prev eq '-f') {
238 $reply = $self->_completion_formats;
239 }
240 elsif ($current =~ /^-/) {
241 $reply = $self->_completion_options;
242 }
243 else {
244 if (!$self->command) {
245 $reply = [$self->commands, @{$self->_completion_options([keys %{$self->early_options}])}];
246 }
247 else {
248 print 'file';
249 exit 9;
250 }
251 }
252
253 local $, = "\n";
254 print grep { /^\Q$current\E/ } @$reply;
255 exit 0;
256 }
257
258 sub _completion_options {
259 my $self = shift;
260 my $opts = shift || [$self->options];
261
262 my @options;
263
264 for my $option (@$opts) {
265 my ($names, $op, $vtype) = $option =~ /^([^=:!]+)([=:!]?)(.*)$/;
266 my @names = split(/\|/, $names);
267
268 for my $name (@names) {
269 if ($op eq '!') {
270 push @options, "--$name", "--no-$name";
271 }
272 else {
273 if (length($name) > 1) {
274 push @options, "--$name";
275 }
276 else {
277 push @options, "-$name";
278 }
279 }
280 }
281 }
282
283 return [sort @options];
284 }
285
286 sub _completion_formats { [qw(csv json json:pretty tsv yaml)] }
287
288 1;
289
290 __END__
291
292 =pod
293
294 =encoding UTF-8
295
296 =head1 NAME
297
298 App::Codeowners::Options - Getopt and shell completion for App::Codeowners
299
300 =head1 VERSION
301
302 version 0.46
303
304 =head1 METHODS
305
306 =head2 get_options
307
308 $options = $options->get_options(
309 args => \@ARGV,
310 spec => \@expected_options,
311 callback => sub { my ($arg, $results) = @_; ... },
312 );
313
314 Convert command-line arguments to options, based on specified rules.
315
316 Returns a hashref of options or C<undef> if an error occurred.
317
318 =over 4
319
320 =item *
321
322 C<args> - Arguments from the caller (e.g. C<@ARGV>).
323
324 =item *
325
326 C<spec> - List of L<Getopt::Long> compatible option strings.
327
328 =item *
329
330 C<callback> - Optional coderef to call for non-option arguments.
331
332 =item *
333
334 C<config> - Optional L<Getopt::Long> configuration string.
335
336 =back
337
338 =head2 shell_completion
339
340 $options->shell_completion($shell_type);
341
342 Print shell code to C<STDOUT> for the given type of shell. When eval'd, the shell code enables
343 completion for the F<git-codeowners> command.
344
345 =head2 completions
346
347 $options->completions($current_arg_index, @args);
348
349 Print completions to C<STDOUT> for the given argument list and cursor position, and exit.
350
351 May also exit with status 9 and a compgen action printed to C<STDOUT> to indicate that the shell
352 should generate its own completions.
353
354 Doesn't return.
355
356 =head1 BUGS
357
358 Please report any bugs or feature requests on the bugtracker website
359 L<https://github.com/chazmcgarvey/git-codeowners/issues>
360
361 When submitting a bug or request, please include a test-file or a
362 patch to an existing test-file that illustrates the bug or desired
363 feature.
364
365 =head1 AUTHOR
366
367 Charles McGarvey <chazmcgarvey@brokenzipper.com>
368
369 =head1 COPYRIGHT AND LICENSE
370
371 This software is copyright (c) 2019 by Charles McGarvey.
372
373 This is free software; you can redistribute it and/or modify it under
374 the same terms as the Perl 5 programming language system itself.
375
376 =cut
This page took 0.058935 seconds and 3 git commands to generate.