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