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