| 1 | use warnings; | ||
| 2 | |||
| 3 | package Git::Repository::Plugin::GitHooks; | ||
| 4 | # ABSTRACT: A Git::Repository plugin with some goodies for hook developers | ||
| 5 | $Git::Repository::Plugin::GitHooks::VERSION = '3.5.0'; | ||
| 6 | use parent qw/Git::Repository::Plugin/; | ||
| 7 | |||
| 8 | use v5.16.0; | ||
| 9 | use utf8; | ||
| 10 | use Carp; | ||
| 11 | use Path::Tiny; | ||
| 12 | use IO::Interactive 'is_interactive'; | ||
| 13 | use Log::Any '$log'; | ||
| 14 | |||
| 15 | sub _keywords { ## no critic (ProhibitUnusedPrivateSubroutines) | ||
| 16 | |||
| 17 | return | ||
| 18 | qw/ | ||
| 19 | prepare_hook load_plugins invoke_external_hooks | ||
| 20 | |||
| 21 | post_hook post_hooks | ||
| 22 | |||
| 23 | cache | ||
| 24 | |||
| 25 | get_config get_config_boolean get_config_integer | ||
| 26 | |||
| 27 | check_timeout | ||
| 28 | |||
| 29 | fault get_faults fail_on_faults | ||
| 30 | |||
| 31 | undef_commit empty_tree get_commit get_commits | ||
| 32 | |||
| 33 | read_commit_msg_file write_commit_msg_file | ||
| 34 | |||
| 35 | get_affected_refs get_affected_ref_range get_affected_ref_commits | ||
| 36 | |||
| 37 | filter_name_status_in_index filter_name_status_in_range filter_name_status_in_commit | ||
| 38 | |||
| 39 | filter_files_in_index filter_files_in_range filter_files_in_commit | ||
| 40 | |||
| 41 | authenticated_user repository_name | ||
| 42 | |||
| 43 | get_current_branch get_sha1 get_head_or_empty_tree | ||
| 44 | |||
| 45 | blob file_size file_mode | ||
| 46 | |||
| 47 | is_reference_enabled match_user im_admin grok_acls | ||
| 48 | /; | ||
| 49 | } | ||
| 50 | |||
| 51 | # This package variable tells get_config which character encoding is used in | ||
| 52 | # the output of the git-config command. Usually none, and decoding isn't | ||
| 53 | # necessary. But sometimes it is... | ||
| 54 | our $CONFIG_ENCODING = undef; | ||
| 55 | |||
| 56 | ############## | ||
| 57 | # The following routines prepare the arguments for some hooks to make | ||
| 58 | # it easier to deal with them later on. | ||
| 59 | |||
| 60 | # Some hooks get information from STDIN as text lines with | ||
| 61 | # space-separated fields. This routine reads up all of STDIN and tucks | ||
| 62 | # that information in the Git::Repository object. | ||
| 63 | |||
| 64 | sub _push_input_data { | ||
| 65 | my ($git, $data) = @_; | ||
| 66 | push @{$git->{_plugin_githooks}{input_data}}, $data; | ||
| 67 | return; | ||
| 68 | } | ||
| 69 | |||
| 70 | sub _get_input_data { | ||
| 71 | my ($git) = @_; | ||
| 72 | return $git->{_plugin_githooks}{input_data} || []; | ||
| 73 | } | ||
| 74 | |||
| 75 | sub _prepare_input_data { | ||
| 76 | my ($git) = @_; | ||
| 77 | while (<STDIN>) { ## no critic (InputOutput::ProhibitExplicitStdin) | ||
| 78 | chomp; | ||
| 79 | _push_input_data($git, [split]); | ||
| 80 | } | ||
| 81 | my $input_data = _get_input_data($git); | ||
| 82 | $log->info(_prepare_input_data => {input_data => $input_data}); | ||
| 83 | return $input_data; | ||
| 84 | } | ||
| 85 | |||
| 86 | # The pre-receive and post-receive hooks get the list of affected | ||
| 87 | # commits via STDIN. This routine gets them all and set all affected | ||
| 88 | # refs in the Git object. | ||
| 89 | |||
| 90 | sub _prepare_receive { | ||
| 91 | my ($git) = @_; | ||
| 92 | foreach (@{_prepare_input_data($git)}) { | ||
| 93 | my ($old_commit, $new_commit, $ref) = @$_; | ||
| 94 | _set_affected_ref($git, $ref, $old_commit, $new_commit); | ||
| 95 | } | ||
| 96 | return; | ||
| 97 | } | ||
| 98 | |||
| 99 | # The update hook get three arguments telling which reference is being | ||
| 100 | # updated, from which commit, to which commit. Here we use these | ||
| 101 | # arguments to set the affected ref in the Git object. | ||
| 102 | |||
| 103 | sub _prepare_update { | ||
| 104 | my ($git, $args) = @_; | ||
| 105 | _set_affected_ref($git, @$args); | ||
| 106 | $log->debug(_prepare_update => {affected_refs => _get_affected_refs_hash($git)}); | ||
| 107 | return; | ||
| 108 | } | ||
| 109 | |||
| 110 | # Gerrit hooks get a list of option/value pairs. Here we convert the list into a | ||
| 111 | # hash and change the original argument list into a single hash-ref. We also | ||
| 112 | # record information about the user performing the push. Based on: | ||
| 113 | # https://gerrit.googlesource.com/plugins/hooks/+/refs/heads/master/src/main/resources/Documentation/hooks.md | ||
| 114 | |||
| 115 | sub _prepare_gerrit_args { | ||
| 116 | my ($git, $args) = @_; | ||
| 117 | |||
| 118 | my %opt = @$args; | ||
| 119 | |||
| 120 | # Each Gerrit hook receive the full name and email of the user | ||
| 121 | # performing the hooked operation via a specific option in the | ||
| 122 | # format "User Name (email@example.net)". Here we grok it. | ||
| 123 | my $user = | ||
| 124 | $opt{'--uploader'} || | ||
| 125 | $opt{'--author'} || | ||
| 126 | $opt{'--submitter'} || | ||
| 127 | $opt{'--abandoner'} || | ||
| 128 | $opt{'--restorer'} || | ||
| 129 | $opt{'--reviewer'} || | ||
| 130 | undef; | ||
| 131 | |||
| 132 | # Here we make the name and email available in two environment variables | ||
| 133 | # (GERRIT_USER_NAME and GERRIT_USER_EMAIL) so that | ||
| 134 | # Git::Repository::Plugin::GitHooks::authenticated_user can more easily | ||
| 135 | # grok the userid from them later. | ||
| 136 | if ($user && $user =~ /([^\(]+)\s+\(([^\)]+)\)/) { | ||
| 137 | $ENV{GERRIT_USER_NAME} = $1; ## no critic (Variables::RequireLocalizedPunctuationVars) | ||
| 138 | $ENV{GERRIT_USER_EMAIL} = $2; ## no critic (Variables::RequireLocalizedPunctuationVars) | ||
| 139 | } | ||
| 140 | |||
| 141 | $log->debug(_prepare_gerrit_args => {opt => \%opt}); | ||
| 142 | |||
| 143 | # Now we create a Gerrit::REST object connected to the Gerrit | ||
| 144 | # server and tack it to the hook arguments so that Gerrit plugins | ||
| 145 | # can interact with it. | ||
| 146 | |||
| 147 | # We 'require' the module instead of 'use' it because it's only | ||
| 148 | # used if one sets up Gerrit hooks, which may not be the most | ||
| 149 | # common usage of Git::Hooks. | ||
| 150 | eval {require Gerrit::REST} | ||
| 151 | or croak __PACKAGE__, ": Please, install the Gerrit::REST module to use Gerrit hooks.\n"; | ||
| 152 | |||
| 153 | $opt{gerrit} = do { | ||
| 154 | my %info; | ||
| 155 | foreach my $arg (qw/url username password/) { | ||
| 156 | $info{$arg} = $git->get_config('githooks.gerrit' => $arg) | ||
| 157 | or croak __PACKAGE__, ": Missing githooks.gerrit.$arg configuration variable.\n"; | ||
| 158 | } | ||
| 159 | |||
| 160 | Gerrit::REST->new(@info{qw/url username password/}); | ||
| 161 | }; | ||
| 162 | |||
| 163 | @$args = (\%opt); | ||
| 164 | |||
| 165 | $git->{_plugin_githooks}{gerrit_args} = \%opt; | ||
| 166 | |||
| 167 | return; | ||
| 168 | } | ||
| 169 | |||
| 170 | # The ref-update and the commit-received Gerrit hooks are invoked synchronously | ||
| 171 | # when a user pushes commits to a branch. So, they act much like Git's standard | ||
| 172 | # 'update' hook. This routine prepares the options as usual and sets the | ||
| 173 | # affected ref accordingly. The documented arguments for the hook are these: | ||
| 174 | |||
| 175 | # ref-update --project <project name> --refname <refname> --uploader <uploader> | ||
| 176 | # --uploader-username <username> --oldrev <sha1> --newrev <sha1> | ||
| 177 | |||
| 178 | # commit-received --project <project name> --refname <refname> --uploader | ||
| 179 | # <uploader> --uploader-username <username> --oldrev <sha1> --newrev <sha1> | ||
| 180 | # --cmdref <refname> | ||
| 181 | |||
| 182 | sub _prepare_gerrit_ref_update { | ||
| 183 | my ($git, $args) = @_; | ||
| 184 | |||
| 185 | _prepare_gerrit_args($git, $args); | ||
| 186 | |||
| 187 | # The --refname argument contains the branch short-name if it's in the | ||
| 188 | # refs/heads/ namespace. But we need to always use the branch long-name, | ||
| 189 | # so we change it here. | ||
| 190 | my $refname = $args->[0]{'--refname'}; | ||
| 191 | $refname = "refs/heads/$refname" | ||
| 192 | unless $refname =~ m:^refs/:; | ||
| 193 | |||
| 194 | _set_affected_ref($git, $refname, @{$args->[0]}{qw/--oldrev --newrev/}); | ||
| 195 | $log->debug(_prepare_gerrit_ref_update => {affected_refs => _get_affected_refs_hash($git)}); | ||
| 196 | return; | ||
| 197 | } | ||
| 198 | |||
| 199 | # The submit Gerrit hook is invoked synchronously when a user tries to submit a | ||
| 200 | # change. So, it acts much like Git's standard 'update' hook. This routine | ||
| 201 | # prepares the options as usual and sets the affected ref accordingly. The | ||
| 202 | # documented arguments for the hook are these: | ||
| 203 | |||
| 204 | # submit --project <project name> --branch <branch> --submitter <submitter> | ||
| 205 | # --patchset <patchset id> --commit <sha1> | ||
| 206 | |||
| 207 | sub _prepare_gerrit_submit { | ||
| 208 | my ($git, $args) = @_; | ||
| 209 | |||
| 210 | _prepare_gerrit_args($git, $args); | ||
| 211 | |||
| 212 | # The --branch argument contains the branch short-name if it's in the | ||
| 213 | # refs/heads/ namespace. But we need to always use the branch long-name, | ||
| 214 | # so we change it here. | ||
| 215 | my $refname = $args->[0]{'--branch'}; | ||
| 216 | $refname = "refs/heads/$refname" | ||
| 217 | unless $refname =~ m:^refs/:; | ||
| 218 | |||
| 219 | my $parent = $git->get_sha1("$refname^"); | ||
| 220 | |||
| 221 | _set_affected_ref($git, $refname, $parent, $args->[0]{'--commit'}); | ||
| 222 | $log->debug(_prepare_gerrit_submit => {affected_refs => _get_affected_refs_hash($git)}); | ||
| 223 | return; | ||
| 224 | } | ||
| 225 | |||
| 226 | # The following routine is the post_hook used by the Gerrit hooks | ||
| 227 | # patchset-created and draft-published. It basically casts a vote on the | ||
| 228 | # patchset based on the errors found during the hook processing. | ||
| 229 | |||
| 230 | sub _gerrit_patchset_post_hook { | ||
| 231 | my ($hook_name, $git, $args) = @_; | ||
| 232 | |||
| 233 | for my $arg (qw/project branch change patchset/) { | ||
| 234 | exists $args->{"--$arg"} | ||
| 235 | or croak __PACKAGE__, ": Missing --$arg argument to Gerrit's $hook_name hook.\n"; | ||
| 236 | } | ||
| 237 | |||
| 238 | # We have to use the most complete form of Gerrit change ids because | ||
| 239 | # it's the only unanbiguous one. Vide: | ||
| 240 | # https://gerrit.cpqd.com.br/Documentation/rest-api-changes.html#change-id. | ||
| 241 | |||
| 242 | # Up to Gerrit 2.12 the argument --change passed the change's Change-Id | ||
| 243 | # code. So, we had to build the complete change id using the information | ||
| 244 | # passed on the arguments --project and --branch. From Gerrit 2.13 on | ||
| 245 | # the --change argument already contains the complete change id. So we | ||
| 246 | # have to figure out if we need to build it or not. | ||
| 247 | |||
| 248 | # Also, for the old Gerrit we have to url-escape the change-id because | ||
| 249 | # the project name may contain slashes (and perhaps other reserved | ||
| 250 | # characters). This is possibly not a complete solution. Vide: | ||
| 251 | # http://mark.stosberg.com/blog/2010/12/percent-encoding-uris-in-perl.html. | ||
| 252 | |||
| 253 | require URI::Escape; | ||
| 254 | my $id = $args->{'--change'} =~ /~/ | ||
| 255 | ? $args->{'--change'} | ||
| 256 | : URI::Escape::uri_escape(join('~', @{$args}{qw/--project --branch --change/})); | ||
| 257 | |||
| 258 | my $patchset = $args->{'--patchset'}; | ||
| 259 | |||
| 260 | # Grok all configuration options at once to make it easier to deal with them below. | ||
| 261 | my %cfg = ( | ||
| 262 | 'votes-to-approve' => $git->get_config('githooks.gerrit' => 'votes-to-approve'), | ||
| 263 | 'votes-to-reject' => $git->get_config('githooks.gerrit' => 'votes-to-reject'), | ||
| 264 | 'comment-ok' => $git->get_config('githooks.gerrit' => 'comment-ok'), | ||
| 265 | 'auto-submit' => $git->get_config_boolean('githooks.gerrit' => 'auto-submit'), | ||
| 266 | ); | ||
| 267 | |||
| 268 | # https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-review | ||
| 269 | my %review_input = (tag => 'autogenerated:git-hooks'); | ||
| 270 | my $auto_submit = 0; | ||
| 271 | |||
| 272 | if (my $faults = $git->get_faults()) { | ||
| 273 | $review_input{labels} = $cfg{'votes-to-reject'} || 'Code-Review-1'; | ||
| 274 | |||
| 275 | # We have to truncate $faults down to a little less than 64kB because up | ||
| 276 | # to at least Gerrit 2.14.4 messages are saved in a MySQL column of type | ||
| 277 | # 'text', which has this limit. | ||
| 278 | if (length $faults > 65000) { | ||
| 279 | $faults = substr($faults, 0, 65000) . "...\n<truncated>\n"; | ||
| 280 | } | ||
| 281 | $review_input{message} = $faults; | ||
| 282 | } else { | ||
| 283 | $review_input{labels} = $cfg{'votes-to-approve'} || 'Code-Review+1'; | ||
| 284 | $review_input{message} = "[Git::Hooks] $cfg{'comment-ok'}" | ||
| 285 | if $cfg{'comment-ok'}; | ||
| 286 | $auto_submit = 1 if $cfg{'auto-submit'}; | ||
| 287 | } | ||
| 288 | |||
| 289 | # Convert, e.g., 'LabelA-1,LabelB+2' into { LabelA => '-1', LabelB => '+2' } | ||
| 290 | $review_input{labels} = { map {/^([-\w]+)([-+]\d+)$/i} split(',', $review_input{labels}) }; | ||
| 291 | |||
| 292 | if (my $notify = $git->get_config('githooks.gerrit' => 'notify')) { | ||
| 293 | $review_input{notify} = $notify; | ||
| 294 | } | ||
| 295 | |||
| 296 | $log->debug(_gerrit_patchset_post_hook => { | ||
| 297 | review_input => \%review_input, | ||
| 298 | auto_submit => $auto_submit, | ||
| 299 | }); | ||
| 300 | |||
| 301 | # Cast review | ||
| 302 | eval { $args->{gerrit}->POST("/changes/$id/revisions/$patchset/review", \%review_input) } | ||
| 303 | or croak __PACKAGE__ . ": error in Gerrit::REST::POST(/changes/$id/revisions/$patchset/review): $@\n"; | ||
| 304 | |||
| 305 | # Auto submit if requested and passed verification | ||
| 306 | if ($auto_submit) { | ||
| 307 | eval { $args->{gerrit}->POST("/changes/$id/submit", {wait_for_merge => 'true'}) } | ||
| 308 | or croak __PACKAGE__ . ": I couldn't submit the change. Perhaps you have to rebase it manually to resolve a conflict. Please go to its web page to check it out. The error message follows: $@\n"; | ||
| 309 | } | ||
| 310 | |||
| 311 | return; | ||
| 312 | } | ||
| 313 | |||
| 314 | # Gerrit's patchset-created hook is invoked when a commit is pushed to a | ||
| 315 | # refs/for/* branch for revision. It's invoked asynchronously, i.e., it | ||
| 316 | # can't stop the push to happen. Instead, if it detects any problem, we must | ||
| 317 | # reject the commit via Gerrit's own revision process. So, we prepare a post | ||
| 318 | # hook action in which we see if there were errors that should be signaled | ||
| 319 | # via a code review action. Note, however, that draft changes can only be | ||
| 320 | # accessed by their respective owners and usually can't be voted on by the | ||
| 321 | # hook. So, draft changes aren't voted on and we exit the hook prematurely. | ||
| 322 | # The arguments for the hook are these: | ||
| 323 | |||
| 324 | # patchset-created --change <change id> --is-draft <boolean> \ | ||
| 325 | # --kind <change kind> --change-url <change url> \ | ||
| 326 | # --change-owner <change owner> --project <project name> \ | ||
| 327 | # --branch <branch> --topic <topic> --uploader <uploader> | ||
| 328 | # --commit <sha1> --patchset <patchset id> | ||
| 329 | |||
| 330 | # Gerrit's draft-published hook is invoked when a draft change is | ||
| 331 | # published. In this state they're are visible by the hook and can be voted | ||
| 332 | # on. The arguments for the hook are these: | ||
| 333 | |||
| 334 | # draft-published --change <change id> --change-url <change url> \ | ||
| 335 | # --change-owner <change owner> --project <project name> \ | ||
| 336 | # --branch <branch> --topic <topic> --uploader <uploader> \ | ||
| 337 | # --commit <sha1> --patchset <patchset id> | ||
| 338 | |||
| 339 | sub _prepare_gerrit_patchset { | ||
| 340 | my ($git, $args) = @_; | ||
| 341 | |||
| 342 | _prepare_gerrit_args($git, $args); | ||
| 343 | |||
| 344 | exit(0) if exists $args->[0]{'--is-draft'} and $args->[0]{'--is-draft'} eq 'true'; | ||
| 345 | |||
| 346 | $git->post_hook(\&_gerrit_patchset_post_hook); | ||
| 347 | |||
| 348 | return; | ||
| 349 | } | ||
| 350 | |||
| 351 | # The %prepare_hook hash maps hook names to the routine that must be | ||
| 352 | # invoked in order to "prepare" their arguments. | ||
| 353 | |||
| 354 | my %prepare_hook = ( | ||
| 355 | 'update' => \&_prepare_update, | ||
| 356 | 'pre-push' => \&_prepare_input_data, | ||
| 357 | 'post-rewrite' => \&_prepare_input_data, | ||
| 358 | 'pre-receive' => \&_prepare_receive, | ||
| 359 | 'post-receive' => \&_prepare_receive, | ||
| 360 | 'ref-update' => \&_prepare_gerrit_ref_update, | ||
| 361 | 'commit-received' => \&_prepare_gerrit_ref_update, | ||
| 362 | 'submit' => \&_prepare_gerrit_submit, | ||
| 363 | 'patchset-created' => \&_prepare_gerrit_patchset, | ||
| 364 | 'draft-published' => \&_prepare_gerrit_patchset, | ||
| 365 | ); | ||
| 366 | |||
| 367 | sub prepare_hook { | ||
| 368 | my ($git, $hook_name, $args) = @_; | ||
| 369 | |||
| 370 | $git->{_plugin_githooks}{arguments} = $args; | ||
| 371 | my $basename = path($hook_name)->basename; | ||
| 372 | $git->{_plugin_githooks}{hookname} = $basename; | ||
| 373 | |||
| 374 | # Some hooks need some argument munging before we invoke them | ||
| 375 | if (my $prepare = $prepare_hook{$basename}) { | ||
| 376 | $prepare->($git, $args); | ||
| 377 | } | ||
| 378 | |||
| 379 | return $basename; | ||
| 380 | } | ||
| 381 | |||
| 382 | sub load_plugins { | ||
| 383 | my ($git) = @_; | ||
| 384 | |||
| 385 | my %plugins; | ||
| 386 | |||
| 387 | foreach my $plugin (map {split} $git->get_config(githooks => 'plugin')) { | ||
| 388 | my ($negation, $prefix, $basename) = ($plugin =~ /^(\!?)((?:.+::)?)(.+)/); | ||
| 389 | |||
| 390 | if (exists $ENV{$basename} && ! $ENV{$basename}) { | ||
| 391 | delete @plugins{$basename, "$prefix$basename"}; | ||
| 392 | } elsif ($negation) { | ||
| 393 | delete $plugins{"$prefix$basename"}; | ||
| 394 | } else { | ||
| 395 | $plugins{"$prefix$basename"} = [$prefix, $basename]; | ||
| 396 | } | ||
| 397 | } | ||
| 398 | |||
| 399 | return unless %plugins; # no one configured | ||
| 400 | |||
| 401 | # Remove disabled plugins from the list of plugins | ||
| 402 | my %disabled_plugins = map {($_ => undef)} map {split} $git->get_config(githooks => 'disable'); | ||
| 403 | delete @plugins{grep {exists $disabled_plugins{$_}} keys %plugins}; | ||
| 404 | |||
| 405 | # Define the list of directories where we'll look for the hook | ||
| 406 | # plugins. First the local directory 'githooks' under the | ||
| 407 | # repository path, then the optional list of directories | ||
| 408 | # specified by the githooks.plugins config option, and, | ||
| 409 | # finally, the Git::Hooks standard hooks directory. | ||
| 410 | my @plugin_dirs = grep {-d} ( | ||
| 411 | 'githooks', | ||
| 412 | $git->get_config(githooks => 'plugins'), | ||
| 413 | path($INC{'Git/Hooks.pm'})->parent->child('Hooks'), | ||
| 414 | ); | ||
| 415 | |||
| 416 | $log->debug(load_plugins => {plugins => \%plugins, plugin_dirs => \@plugin_dirs}); | ||
| 417 | |||
| 418 | # Load remaining enabled plugins | ||
| 419 | while (my ($key, $plugin) = each %plugins) { | ||
| 420 | my ($prefix, $basename) = @$plugin; | ||
| 421 | my $exit = do { | ||
| 422 | if ($prefix) { | ||
| 423 | # It must be a module name | ||
| 424 | ## no critic (ProhibitStringyEval, RequireCheckingReturnValueOfEval) | ||
| 425 | eval "require $prefix$basename"; | ||
| 426 | ## use critic | ||
| 427 | } else { | ||
| 428 | # Otherwise, it's a basename we must look for in @plugin_dirs | ||
| 429 | $basename .= '.pm' unless $basename =~ /\.p[lm]$/i; | ||
| 430 | my @scripts = grep {!-d} map {path($_)->child($basename)} @plugin_dirs; | ||
| 431 | $basename = shift @scripts | ||
| 432 | or croak __PACKAGE__, ": can't find enabled hook $basename.\n"; | ||
| 433 | do $basename; | ||
| 434 | } | ||
| 435 | }; | ||
| 436 | unless ($exit) { | ||
| 437 | croak __PACKAGE__, ": couldn't parse $basename: $@\n" if $@; | ||
| 438 | croak __PACKAGE__, ": couldn't do $basename: $!\n" unless defined $exit; | ||
| 439 | croak __PACKAGE__, ": couldn't run $basename\n"; | ||
| 440 | } | ||
| 441 | } | ||
| 442 | |||
| 443 | return; | ||
| 444 | } | ||
| 445 | |||
| 446 | sub _invoke_external_hook { ## no critic (ProhibitExcessComplexity) | ||
| 447 | my ($git, $file, $hook, @args) = @_; | ||
| 448 | |||
| 449 | my $prefix = '[' . __PACKAGE__ . '(' . path($file)->basename . ')]'; | ||
| 450 | |||
| 451 | my $tempfile = Path::Tiny->tempfile(UNLINK => 1); | ||
| 452 | |||
| 453 | ## no critic (RequireBriefOpen, RequireCarping) | ||
| 454 | open(my $oldout, '>&', \*STDOUT) or croak "Can't dup STDOUT: $!"; | ||
| 455 | open(STDOUT , '>' , $tempfile) or croak "Can't redirect STDOUT to \$tempfile: $!"; | ||
| 456 | open(my $olderr, '>&', \*STDERR) or croak "Can't dup STDERR: $!"; | ||
| 457 | open(STDERR , '>&', \*STDOUT) or croak "Can't dup STDOUT for STDERR: $!"; | ||
| 458 | ## use critic | ||
| 459 | |||
| 460 | if ($hook =~ /^(?:pre-receive|post-receive|pre-push|post-rewrite)$/) { | ||
| 461 | |||
| 462 | # These hooks receive information via STDIN that we read once | ||
| 463 | # before invoking any hook. Now, we must regenerate the same | ||
| 464 | # information and output it to the external hooks we invoke. | ||
| 465 | |||
| 466 | my $pid = open my $pipe, '|-'; ## no critic (InputOutput::RequireBriefOpen) | ||
| 467 | |||
| 468 | if (! defined $pid) { | ||
| 469 | $git->fault("I can't fork: $!", {prefix => $prefix}); | ||
| 470 | } elsif ($pid) { | ||
| 471 | # parent | ||
| 472 | $pipe->print(join("\n", map {join(' ', @$_)} @{_get_input_data($git)}) . "\n"); | ||
| 473 | my $exit = $pipe->close; | ||
| 474 | |||
| 475 | ## no critic (RequireBriefOpen, RequireCarping) | ||
| 476 | open(STDOUT, '>&', $oldout) or croak "Can't dup \$oldout: $!"; | ||
| 477 | open(STDERR, '>&', $olderr) or croak "Can't dup \$olderr: $!"; | ||
| 478 | ## use critic | ||
| 479 | |||
| 480 | my $output = $tempfile->slurp; | ||
| 481 | if ($exit) { | ||
| 482 | say STDERR $output if length $output; | ||
| 483 | return 1; | ||
| 484 | } elsif ($!) { | ||
| 485 | $git->fault("Error closing pipe to external hook: $!", { | ||
| 486 | prefix => $prefix, | ||
| 487 | details => $output, | ||
| 488 | }); | ||
| 489 | } else { | ||
| 490 | $git->fault("External hook exited with code $?", { | ||
| 491 | prefix => $prefix, | ||
| 492 | details => $output, | ||
| 493 | }); | ||
| 494 | } | ||
| 495 | } else { | ||
| 496 | # child | ||
| 497 | { exec {$file} ($hook, @args) } | ||
| 498 | |||
| 499 | ## no critic (RequireBriefOpen, RequireCarping) | ||
| 500 | open(STDOUT, '>&', $oldout) or croak "Can't dup \$oldout: $!"; | ||
| 501 | open(STDERR, '>&', $olderr) or croak "Can't dup \$olderr: $!"; | ||
| 502 | ## use critic | ||
| 503 | |||
| 504 | croak "$prefix: can't exec: $!\n"; | ||
| 505 | } | ||
| 506 | |||
| 507 | } else { | ||
| 508 | |||
| 509 | if (@args && ref $args[0]) { | ||
| 510 | # This is a Gerrit hook and we need to expand its arguments | ||
| 511 | @args = %{$args[0]}; | ||
| 512 | } | ||
| 513 | |||
| 514 | my $exit = system {$file} ($hook, @args); | ||
| 515 | |||
| 516 | ## no critic (RequireBriefOpen, RequireCarping) | ||
| 517 | open(STDOUT, '>&', $oldout) or croak "Can't dup \$oldout: $!"; | ||
| 518 | open(STDERR, '>&', $olderr) or croak "Can't dup \$olderr: $!"; | ||
| 519 | ## use critic | ||
| 520 | |||
| 521 | my $output = $tempfile->slurp; | ||
| 522 | |||
| 523 | if ($exit == 0) { | ||
| 524 | say STDERR $output if length $output; | ||
| 525 | return 1; | ||
| 526 | } else { | ||
| 527 | my $message = do { | ||
| 528 | if ($exit == -1) { | ||
| 529 | "failed to execute external hook: $!"; | ||
| 530 | } elsif ($exit & 127) { | ||
| 531 | sprintf("external hook died with signal %d, %s coredump", | ||
| 532 | ($exit & 127), ($exit & 128) ? 'with' : 'without'); | ||
| 533 | } else { | ||
| 534 | sprintf("'$file' exited abnormally with value %d", $exit >> 8); | ||
| 535 | } | ||
| 536 | }; | ||
| 537 | $git->fault($message, {prefix => $prefix, details => $output}); | ||
| 538 | } | ||
| 539 | } | ||
| 540 | |||
| 541 | return 0; | ||
| 542 | } | ||
| 543 | |||
| 544 | sub invoke_external_hooks { | ||
| 545 | my ($git, @args) = @_; | ||
| 546 | |||
| 547 | return if $^O eq 'MSWin32' || ! $git->get_config_boolean(githooks => 'externals'); | ||
| 548 | |||
| 549 | my $hookname = $git->{_plugin_githooks}{hookname}; | ||
| 550 | |||
| 551 | foreach my $dir ( | ||
| 552 | grep {-e} | ||
| 553 | map {path($_)->child($hookname)} | ||
| 554 | ($git->get_config(githooks => 'hooks'), path($git->git_dir())->child('hooks.d')) | ||
| 555 | ) { | ||
| 556 | opendir my $dh, $dir | ||
| 557 | or $git->fault("I cannot opendir '$dir'", {details => $!}) | ||
| 558 | and next; | ||
| 559 | foreach my $file (grep {!-d && -x} map {path($dir)->child($_)} readdir $dh) { | ||
| 560 | _invoke_external_hook($git, $file, $hookname, @args) | ||
| 561 | or $git->fault(": error in external hook '$file'"); | ||
| 562 | } | ||
| 563 | } continue { | ||
| 564 | $git->check_timeout(); | ||
| 565 | } | ||
| 566 | |||
| 567 | return; | ||
| 568 | } | ||
| 569 | |||
| 570 | ############## | ||
| 571 | # The following routines are invoked after all hooks have been | ||
| 572 | # processed. Some hooks may need to take a global action depending on | ||
| 573 | # the overall result of all hooks. | ||
| 574 | |||
| 575 | sub post_hook { | ||
| 576 | my ($git, $sub) = @_; | ||
| 577 | push @{$git->{_plugin_githooks}{post_hooks}}, $sub; | ||
| 578 | return; | ||
| 579 | } | ||
| 580 | |||
| 581 | sub post_hooks { | ||
| 582 | my ($git) = @_; | ||
| 583 | if ($git->{_plugin_githooks}{post_hooks}) { | ||
| 584 | return @{$git->{_plugin_githooks}{post_hooks}} | ||
| 585 | } else { | ||
| 586 | return; | ||
| 587 | } | ||
| 588 | } | ||
| 589 | |||
| 590 | sub cache { | ||
| 591 | my ($git, $section) = @_; | ||
| 592 | |||
| 593 | unless (exists $git->{_plugin_githooks}{cache}{$section}) { | ||
| 594 | $git->{_plugin_githooks}{cache}{$section} = {}; | ||
| 595 | } | ||
| 596 | |||
| 597 | return $git->{_plugin_githooks}{cache}{$section}; | ||
| 598 | } | ||
| 599 | |||
| 600 | sub get_config { | ||
| 601 | my ($git, $section, $var) = @_; | ||
| 602 | |||
| 603 | unless (exists $git->{_plugin_githooks}{config}) { | ||
| 604 | my %config; | ||
| 605 | |||
| 606 | my $config = do { | ||
| 607 | local $/ = "\c@"; | ||
| 608 | $git->run(qw/config --null --list/); | ||
| 609 | }; | ||
| 610 | |||
| 611 | if (defined $CONFIG_ENCODING) { | ||
| 612 | require Encode; | ||
| 613 | $config = Encode::decode($CONFIG_ENCODING, $config); | ||
| 614 | } | ||
| 615 | |||
| 616 | if (defined $config) { | ||
| 617 | # The --null option to git-log makes it output a null character | ||
| 618 | # after each option/value. The option and value are separated by a | ||
| 619 | # newline, unless there is no value, in which case, there is no | ||
| 620 | # newline. | ||
| 621 | while ($config =~ /([^\cJ]+)(\cJ[^\c@]*|)\c@/sg) { | ||
| 622 | my ($option, $value) = ($1, $2); | ||
| 623 | if ($option =~ /(.+)\.(.+)/) { | ||
| 624 | my ($osection, $okey) = (lc $1, lc $2); | ||
| 625 | if ($value =~ s/^\cJ//) { | ||
| 626 | ## no critic (ProhibitDeepNests) | ||
| 627 | if ($value eq 'undef') { | ||
| 628 | # The 'undef' string is a special mark telling us to | ||
| 629 | # disregard every previous value already set for | ||
| 630 | # this variable. | ||
| 631 | delete $config{$osection}{$okey}; | ||
| 632 | } else { | ||
| 633 | push @{$config{$osection}{$okey}}, $value; | ||
| 634 | } | ||
| 635 | } else { | ||
| 636 | # An option without a value is considered a boolean | ||
| 637 | # true. We mark it explicitly so instead of leaving it | ||
| 638 | # undefined because Perl would consider it false. | ||
| 639 | push @{$config{$osection}{$okey}}, 'true'; | ||
| 640 | } | ||
| 641 | } else { | ||
| 642 | croak __PACKAGE__, ": Cannot grok config variable name '$option'.\n"; | ||
| 643 | } | ||
| 644 | } | ||
| 645 | } | ||
| 646 | |||
| 647 | # Set default values for undefined ones. | ||
| 648 | $config{githooks}{externals} //= ['true']; | ||
| 649 | $config{githooks}{gerrit}{enabled} //= ['true']; | ||
| 650 | $config{githooks}{'abort-commit'} //= ['true']; | ||
| 651 | |||
| 652 | $git->{_plugin_githooks}{config} = \%config; | ||
| 653 | } | ||
| 654 | |||
| 655 | my $config = $git->{_plugin_githooks}{config}; | ||
| 656 | |||
| 657 | $section = lc $section if defined $section; | ||
| 658 | $var = lc $var if defined $var; | ||
| 659 | |||
| 660 | if (! defined $section) { | ||
| 661 | return $config; | ||
| 662 | } elsif (! defined $var) { | ||
| 663 | $config->{$section} = {} unless exists $config->{$section}; | ||
| 664 | return $config->{$section}; | ||
| 665 | } elsif (exists $config->{$section}{$var}) { | ||
| 666 | if (wantarray) { | ||
| 667 | $log->trace(get_config => { | ||
| 668 | wantarray => 1, | ||
| 669 | section => $section, | ||
| 670 | var => $var, | ||
| 671 | result => $config->{$section}{$var}, | ||
| 672 | }); | ||
| 673 | return @{$config->{$section}{$var}}; | ||
| 674 | } else { | ||
| 675 | $log->trace(get_config => { | ||
| 676 | wantarray => 0, | ||
| 677 | section => $section, | ||
| 678 | var => $var, | ||
| 679 | result => $config->{$section}{$var}[-1], | ||
| 680 | }); | ||
| 681 | return $config->{$section}{$var}[-1]; | ||
| 682 | } | ||
| 683 | } else { | ||
| 684 | $log->trace(get_config => { | ||
| 685 | wantarray => wantarray, | ||
| 686 | section => $section, | ||
| 687 | var => $var, | ||
| 688 | result => [], | ||
| 689 | }); | ||
| 690 | return; | ||
| 691 | } | ||
| 692 | } | ||
| 693 | |||
| 694 | sub get_config_boolean { | ||
| 695 | my ($git, $section, $var) = @_; | ||
| 696 | |||
| 697 | my $bool = $git->get_config($section, $var); | ||
| 698 | |||
| 699 | if (! defined $bool) { | ||
| 700 | return; | ||
| 701 | } elsif (ref $bool) { | ||
| 702 | croak __PACKAGE__, ": get_bool_config method requires two arguments\n"; | ||
| 703 | } elsif ($bool =~ /^(?:yes|on|true|1)$/i) { | ||
| 704 | return 1; | ||
| 705 | } elsif ($bool =~ /^(?:no|off|false|0|)$/i) { | ||
| 706 | return 0; | ||
| 707 | } else { | ||
| 708 | croak __PACKAGE__, ": get_config_boolean($section, $var) not a valid boolean: '$bool'\n"; | ||
| 709 | } | ||
| 710 | } | ||
| 711 | |||
| 712 | sub get_config_integer { | ||
| 713 | my ($git, $section, $var) = @_; | ||
| 714 | |||
| 715 | my $int = $git->get_config($section, $var); | ||
| 716 | |||
| 717 | if (! defined $int) { | ||
| 718 | return; | ||
| 719 | } elsif (ref $int) { | ||
| 720 | croak __PACKAGE__, ": get_config_integer() requires two arguments\n"; | ||
| 721 | } elsif ($int =~ /^([+-]?)([0-9]+)([kmg]?)$/i) { | ||
| 722 | my ($signal, $num, $unit) = ($1, $2, lc $3); | ||
| 723 | if ($unit) { | ||
| 724 | if ($unit eq 'k') { | ||
| 725 | $num *= 1024; | ||
| 726 | } elsif ($unit eq 'm') { | ||
| 727 | $num *= 1024*1024; | ||
| 728 | } elsif ($unit eq 'g') { | ||
| 729 | $num *= 1024*1024*1024; | ||
| 730 | } | ||
| 731 | } | ||
| 732 | if ($signal eq '-') { | ||
| 733 | $num *= -1; | ||
| 734 | } | ||
| 735 | return $num; | ||
| 736 | } else { | ||
| 737 | croak __PACKAGE__, ": get_config_integer($section, $var) not a valid integer: '$int'\n"; | ||
| 738 | } | ||
| 739 | } | ||
| 740 | |||
| 741 | sub _githooks_colors { | ||
| 742 | my ($git) = @_; | ||
| 743 | |||
| 744 | my $cache = $git->cache('colors'); | ||
| 745 | |||
| 746 | unless (exists $cache->{reset}) { | ||
| 747 | # Check if we want to colorize the output, and if so, return a hash | ||
| 748 | # containing the default colors. Otherwise, return a hash containing no | ||
| 749 | # color codes at all. | ||
| 750 | |||
| 751 | # NOTE: We have to pass the TERM environment variable explicitly because | ||
| 752 | # Git::Repository's constructor deletes it by default. (Se discussion in | ||
| 753 | # https://rt.cpan.org/Ticket/Display.html?id=124711.) | ||
| 754 | |||
| 755 | my $stdout_is_tty = is_interactive() ? 'true' : 'false'; | ||
| 756 | my $githooks_color = $git->run(qw/config --get-colorbool githooks.color/, $stdout_is_tty, | ||
| 757 | {env => {TERM => $ENV{TERM}}}); | ||
| 758 | if ($githooks_color eq 'true') { | ||
| 759 | $cache->{header} = $git->run(qw/config --get-color githooks.color.header/, 'green'); | ||
| 760 | $cache->{footer} = $git->run(qw/config --get-color githooks.color.footer/, 'green'); | ||
| 761 | $cache->{context} = $git->run(qw/config --get-color githooks.color.context/, 'red bold'); | ||
| 762 | $cache->{message} = $git->run(qw/config --get-color githooks.color.message/, 'yellow'); | ||
| 763 | $cache->{details} = ''; | ||
| 764 | $cache->{reset} = $git->run(qw/config --get-color/, '', 'reset'); | ||
| 765 | } else { | ||
| 766 | $cache->{header} = ''; | ||
| 767 | $cache->{footer} = ''; | ||
| 768 | $cache->{context} = ''; | ||
| 769 | $cache->{message} = ''; | ||
| 770 | $cache->{details} = ''; | ||
| 771 | $cache->{reset} = ''; | ||
| 772 | } | ||
| 773 | } | ||
| 774 | |||
| 775 | return $cache; | ||
| 776 | } | ||
| 777 | |||
| 778 | sub check_timeout { | ||
| 779 | my ($git) = @_; | ||
| 780 | |||
| 781 | my $cache = $git->cache('timeout'); | ||
| 782 | |||
| 783 | $cache->{timeout} = $git->get_config_integer(githooks => 'timeout'); | ||
| 784 | |||
| 785 | return unless $cache->{timeout}; | ||
| 786 | |||
| 787 | $cache->{start_time} = time; | ||
| 788 | |||
| 789 | my $now = time; | ||
| 790 | |||
| 791 | if (($now - $cache->{start_time}) >= $cache->{timeout}) { | ||
| 792 | $git->fault("Hook timeout"); | ||
| 793 | $git->fail_on_faults(); | ||
| 794 | } | ||
| 795 | |||
| 796 | return; | ||
| 797 | } | ||
| 798 | |||
| 799 | sub fault { | ||
| 800 | my ($git, $message, $info) = @_; | ||
| 801 | $info //= {}; | ||
| 802 | |||
| 803 | my $colors = _githooks_colors($git); | ||
| 804 | |||
| 805 | my $msg; | ||
| 806 | |||
| 807 | { | ||
| 808 | my $prefix = $info->{prefix} || caller; | ||
| 809 | my @context; | ||
| 810 | if (my $commit = $info->{commit}) { | ||
| 811 | $commit = $commit->commit | ||
| 812 | if ref $commit; # It's a Git::Repository::Log object | ||
| 813 | $commit = $git->run('rev-parse', '--short', $commit) | ||
| 814 | if $commit =~ /^[0-9a-f]{40}$/; # It can be '<new>' or ':0' sometimes | ||
| 815 | push @context, "commit $commit"; | ||
| 816 | } | ||
| 817 | if (my $ref = $info->{ref}) { | ||
| 818 | push @context, "on ref $ref"; | ||
| 819 | } | ||
| 820 | if (my $option = $info->{option}) { | ||
| 821 | push @context, "violates option '$option'"; | ||
| 822 | } | ||
| 823 | $msg = "$colors->{context}\[$prefix"; | ||
| 824 | $msg .= ': ' . join(' ', @context) if @context; | ||
| 825 | $msg .= "]$colors->{reset}\n"; | ||
| 826 | } | ||
| 827 | |||
| 828 | chomp $message; # strip trailing newlines | ||
| 829 | $msg .= "\n$colors->{message}$message$colors->{reset}\n"; | ||
| 830 | |||
| 831 | if (my $details = $info->{details}) { | ||
| 832 | $details =~ s/\n*$//s; # strip trailing newlines | ||
| 833 | $details =~ s/^/ /gm; # prefix each line with two spaces | ||
| 834 | $msg .= "\n$colors->{details}$details$colors->{reset}\n\n"; | ||
| 835 | } | ||
| 836 | |||
| 837 | push @{$git->{_plugin_githooks}{faults}}, $msg; | ||
| 838 | |||
| 839 | # Return true to allow for the idiom: <expression> or $git->fault(...) and <next|last|return>; | ||
| 840 | return 1; | ||
| 841 | } | ||
| 842 | |||
| 843 | sub get_faults { | ||
| 844 | my ($git) = @_; | ||
| 845 | |||
| 846 | return unless exists $git->{_plugin_githooks}{faults}; | ||
| 847 | |||
| 848 | my $colors = _githooks_colors($git); | ||
| 849 | |||
| 850 | my $faults = ''; | ||
| 851 | |||
| 852 | if (my $header = $git->get_config(githooks => 'error-header')) { | ||
| 853 | $faults .= $colors->{header} . qx{$header} . "$colors->{reset}\n"; ## no critic (ProhibitBacktickOperators) | ||
| 854 | } | ||
| 855 | |||
| 856 | $faults .= join("\n\n", @{$git->{_plugin_githooks}{faults}}); | ||
| 857 | |||
| 858 | if ($git->{_plugin_githooks}{hookname} =~ /^commit-msg|pre-commit$/ | ||
| 859 | && ! $git->get_config_boolean(githooks => 'abort-commit')) { | ||
| 860 | $faults .= <<'EOS'; | ||
| 861 | |||
| 862 | ATTENTION: To fix the problems in this commit, please consider amending it: | ||
| 863 | |||
| 864 | git commit --amend | ||
| 865 | EOS | ||
| 866 | } | ||
| 867 | |||
| 868 | if (my $footer = $git->get_config(githooks => 'error-footer')) { | ||
| 869 | $faults .= "\n$colors->{footer}" . qx{$footer} . "$colors->{reset}\n"; ## no critic (ProhibitBacktickOperators) | ||
| 870 | } | ||
| 871 | |||
| 872 | if (my $prefix = $git->get_config(githooks => 'error-prefix')) { | ||
| 873 | $faults =~ s/^/$prefix/gm; | ||
| 874 | } | ||
| 875 | |||
| 876 | if (my $limit = $git->get_config_integer(githooks => 'error-length-limit')) { | ||
| 877 | if ($limit > 0 && $limit < length($faults)) { | ||
| 878 | my $mark = "\n\n[MESSAGE TRUNCATED at githooks.error-length-limit]\n"; | ||
| 879 | substr($faults, $limit - length($mark) - 1, length($faults), $mark); | ||
| 880 | } | ||
| 881 | } | ||
| 882 | |||
| 883 | return $faults; | ||
| 884 | } | ||
| 885 | |||
| 886 | sub fail_on_faults { | ||
| 887 | my ($git, $warn_only) = @_; | ||
| 888 | |||
| 889 | if (my $faults = $git->get_faults()) { | ||
| 890 | $log->debug(Environment => {ENV => \%ENV}); | ||
| 891 | $faults .= "\n" unless $faults =~ /\n$/; | ||
| 892 | if ($warn_only) { | ||
| 893 | $log->warning(Warning => {faults => $faults}); | ||
| 894 | carp $faults; | ||
| 895 | } else { | ||
| 896 | $log->error(Error => {faults => $faults}); | ||
| 897 | croak $faults; | ||
| 898 | } | ||
| 899 | } | ||
| 900 | |||
| 901 | return; | ||
| 902 | } | ||
| 903 | |||
| 904 | sub undef_commit { | ||
| 905 | return '0000000000000000000000000000000000000000'; | ||
| 906 | } | ||
| 907 | |||
| 908 | sub empty_tree { | ||
| 909 | return '4b825dc642cb6eb9a060e54bf8d69288fbee4904'; | ||
| 910 | } | ||
| 911 | |||
| 912 | sub get_commit { | ||
| 913 | my ($git, $commit) = @_; | ||
| 914 | |||
| 915 | my $cache = $git->cache('commits'); | ||
| 916 | |||
| 917 | # $commit may be a symbolic reference, but we only want to cache commits | ||
| 918 | # by their SHA1 ids, since the symbolic references may change. | ||
| 919 | unless ($commit =~ /^[0-9A-F]{40}$/ && exists $cache->{$commit}) { | ||
| 920 | my @commits = $git->log('-1', $commit); | ||
| 921 | $commit = $commits[0]->{commit}; | ||
| 922 | $cache->{$commit} = $commits[0]; | ||
| 923 | } | ||
| 924 | |||
| 925 | return $cache->{$commit}; | ||
| 926 | } | ||
| 927 | |||
| 928 | sub get_commits { | ||
| 929 | my ($git, $old_commit, $new_commit, $options, $paths) = @_; | ||
| 930 | |||
| 931 | my $cache = $git->cache('ranges'); | ||
| 932 | |||
| 933 | my $range = join( | ||
| 934 | ':', | ||
| 935 | $old_commit, | ||
| 936 | $new_commit, | ||
| 937 | defined $options ? join('', @$options) : '', | ||
| 938 | defined $paths ? join('', @$paths) : '', | ||
| 939 | ); | ||
| 940 | |||
| 941 | unless (exists $cache->{$range}) { | ||
| 942 | # We're interested in all commits reachable from $new_commit but | ||
| 943 | # neither reachable from $old_commit nor from any other existing | ||
| 944 | # reference. | ||
| 945 | |||
| 946 | # We're going to use the "git rev-list" command for that. As you can | ||
| 947 | # read on its documentation, the syntax to specify this set of | ||
| 948 | # commits is this: | ||
| 949 | # "--not --branches --tags --not $new_commit ^$old_commit". | ||
| 950 | |||
| 951 | # However, there are some special cases... | ||
| 952 | |||
| 953 | # When an old branch is deleted $new_commit is null (i.e., | ||
| 954 | # '0'x40). In this case previous commits are being forgotten and the | ||
| 955 | # hooks usually don't need to check them. So, in this situation we | ||
| 956 | # simply return an empty list of commits. | ||
| 957 | |||
| 958 | return if $new_commit eq $git->undef_commit; | ||
| 959 | |||
| 960 | # The @excludes list will contain the arguments to git-log necessary to | ||
| 961 | # exclude from $new_commit history all commits already reachable by any | ||
| 962 | # other reference. | ||
| 963 | my @excludes; | ||
| 964 | |||
| 965 | if ($git->{_plugin_githooks}{hookname} !~ /^post-/) { | ||
| 966 | # In pre-* hooks (e.g., pre-receive, update) we can use the '--not | ||
| 967 | # --branches --tags' arguments. | ||
| 968 | @excludes = qw/--not --branches --tags --not/; | ||
| 969 | } else { | ||
| 970 | # When we're called in a post-receive or post-update hook, the | ||
| 971 | # pushed references already point to $new_commit. So, in these cases | ||
| 972 | # the "--not --branches --tags" options would exclude from the | ||
| 973 | # results all commits reachable from $new_commit, which is exactly | ||
| 974 | # what we don't want... In order to avoid that we can't use these | ||
| 975 | # options directly with git-log. Instead, we use the git-rev-parse | ||
| 976 | # command to get a list of all commits directly reachable by | ||
| 977 | # existing references. Then we'll see if we have to remove any | ||
| 978 | # commit from that list. | ||
| 979 | |||
| 980 | @excludes = $git->run(qw/rev-parse --not --branches --tags/); | ||
| 981 | |||
| 982 | # But we can't simply remove $new_commit from @excludes because it | ||
| 983 | # can be reachable by other references. This can happen, for | ||
| 984 | # instance, when one creates a new branch and pushes it before | ||
| 985 | # making any commits to it or when one pushes a branch after a | ||
| 986 | # fast-forward merge. So, we only remove it if it's reachable by a | ||
| 987 | # single reference, which must be the reference being pushed. | ||
| 988 | |||
| 989 | if ($git->version_ge('2.7.0')) { | ||
| 990 | # The --points-at option was implemented in this version of Git | ||
| 991 | my @new_commit_refs = $git->run( | ||
| 992 | qw/for-each-ref --format %(refname) --count 2 --points-at/, $new_commit, | ||
| 993 | ); | ||
| 994 | if (@new_commit_refs == 1) { | ||
| 995 | @excludes = grep {$_ ne "^$new_commit"} @excludes; | ||
| 996 | } | ||
| 997 | } else { | ||
| 998 | # KLUDGE: I couldn't find a direct way to see how many refs | ||
| 999 | # point to $new_commit in older Gits. So, I use the porcelain | ||
| 1000 | # git-log command with a format that shows the decoration for a | ||
| 1001 | # single commit, which returns something like: (HEAD -> next, | ||
| 1002 | # tag: v2.2.0, origin/next) | ||
| 1003 | my $decoration = $git->run(qw/log -n1 --format=%d/, $new_commit); | ||
| 1004 | $decoration =~ s/HEAD,\s*//; | ||
| 1005 | |||
| 1006 | # If there are commas in $decoration it means that there are | ||
| 1007 | # more than one reference. | ||
| 1008 | if ($decoration !~ /,/) { | ||
| 1009 | @excludes = grep {$_ ne "^$new_commit"} @excludes; | ||
| 1010 | } | ||
| 1011 | } | ||
| 1012 | |||
| 1013 | # And we have to make sure $old_commit is on the list, as --not | ||
| 1014 | # --branches --tags wouldn't bring it when we're being called in a | ||
| 1015 | # post-receive or post-update hook. | ||
| 1016 | |||
| 1017 | push @excludes, "^$old_commit" unless $old_commit eq $git->undef_commit; | ||
| 1018 | } | ||
| 1019 | |||
| 1020 | my @arguments; | ||
| 1021 | |||
| 1022 | push @arguments, @$options if defined $options; | ||
| 1023 | push @arguments, @excludes, $new_commit; | ||
| 1024 | push @arguments, '--', @$paths if defined $paths; | ||
| 1025 | |||
| 1026 | $cache->{$range} = [$git->log(@arguments)]; | ||
| 1027 | } | ||
| 1028 | |||
| 1029 | return @{$cache->{$range}}; | ||
| 1030 | } | ||
| 1031 | |||
| 1032 | sub read_commit_msg_file { | ||
| 1033 | my ($git, $msgfile) = @_; | ||
| 1034 | |||
| 1035 | my $encoding = $git->get_config(i18n => 'commitEncoding') || 'utf-8'; | ||
| 1036 | |||
| 1037 | my $msg = path($msgfile)->slurp({binmode => ":encoding($encoding)"}); | ||
| 1038 | |||
| 1039 | # Truncate the message just before the diff, if any. | ||
| 1040 | $msg =~ s:\ndiff --git .*::s; | ||
| 1041 | |||
| 1042 | # The comments in the following lines were taken from the "git | ||
| 1043 | # help stripspace" documentation to guide the | ||
| 1044 | # implementation. Previously we invoked the "git stripspace -s" | ||
| 1045 | # external command via Git::command_bidi_pipe to do the cleaning | ||
| 1046 | # but it seems that it doesn't work on FreeBSD. So, we reimplement | ||
| 1047 | # its functionality here. | ||
| 1048 | |||
| 1049 | for ($msg) { | ||
| 1050 | # Skip and remove all lines starting with comment character | ||
| 1051 | # (default #). | ||
| 1052 | s/^#.*//gm; | ||
| 1053 | |||
| 1054 | # remove trailing whitespace from all lines | ||
| 1055 | s/[ \t\f]+$//gm; | ||
| 1056 | |||
| 1057 | # collapse multiple consecutive empty lines into one empty line | ||
| 1058 | s/\n{3,}/\n\n/gs; | ||
| 1059 | |||
| 1060 | # remove empty lines from the beginning and end of the input | ||
| 1061 | # add a missing \n to the last line if necessary. | ||
| 1062 | s/^\n+//s; | ||
| 1063 | s/\n*$/\n/s; | ||
| 1064 | |||
| 1065 | # In the case where the input consists entirely of whitespace | ||
| 1066 | # characters, no output will be produced. | ||
| 1067 | s/^\s+$//s; | ||
| 1068 | } | ||
| 1069 | |||
| 1070 | return $msg; | ||
| 1071 | } | ||
| 1072 | |||
| 1073 | sub write_commit_msg_file { | ||
| 1074 | my ($git, $msgfile, @msg) = @_; | ||
| 1075 | |||
| 1076 | my $encoding = $git->get_config(i18n => 'commitEncoding') || 'utf-8'; | ||
| 1077 | |||
| 1078 | path($msgfile)->spew({binmode => ":encoding($encoding)"}, @msg); | ||
| 1079 | |||
| 1080 | return; | ||
| 1081 | } | ||
| 1082 | |||
| 1083 | # Internal funtion to set the affected references in an update or | ||
| 1084 | # pre-receive hook. | ||
| 1085 | |||
| 1086 | sub _set_affected_ref { | ||
| 1087 | my ($git, $ref, $old_commit, $new_commit) = @_; | ||
| 1088 | $git->{_plugin_githooks}{affected_refs}{$ref}{range} = [$old_commit, $new_commit]; | ||
| 1089 | return; | ||
| 1090 | } | ||
| 1091 | |||
| 1092 | # internal method | ||
| 1093 | sub _get_affected_refs_hash { | ||
| 1094 | my ($git) = @_; | ||
| 1095 | |||
| 1096 | return $git->{_plugin_githooks}{affected_refs} || {}; | ||
| 1097 | } | ||
| 1098 | |||
| 1099 | sub get_affected_refs { | ||
| 1100 | my ($git) = @_; | ||
| 1101 | |||
| 1102 | return keys %{_get_affected_refs_hash($git)}; | ||
| 1103 | } | ||
| 1104 | |||
| 1105 | sub get_affected_ref_range { | ||
| 1106 | my ($git, $ref) = @_; | ||
| 1107 | |||
| 1108 | my $affected = _get_affected_refs_hash($git); | ||
| 1109 | |||
| 1110 | exists $affected->{$ref}{range} | ||
| 1111 | or croak __PACKAGE__, ": get_affected_ref_range($ref): no such affected ref\n"; | ||
| 1112 | |||
| 1113 | return @{$affected->{$ref}{range}}; | ||
| 1114 | } | ||
| 1115 | |||
| 1116 | sub get_affected_ref_commits { | ||
| 1117 | my ($git, $ref, $options, $paths) = @_; | ||
| 1118 | |||
| 1119 | return $git->get_commits($git->get_affected_ref_range($ref), $options, $paths); | ||
| 1120 | } | ||
| 1121 | |||
| 1122 | sub filter_name_status_in_index { | ||
| 1123 | my ($git, $filter) = @_; | ||
| 1124 | |||
| 1125 | my %actions; | ||
| 1126 | |||
| 1127 | my $output = $git->run( | ||
| 1128 | qw/diff-index --name-status --ignore-submodules --no-commit-id --cached -r -z/, | ||
| 1129 | "--diff-filter=$filter", | ||
| 1130 | $git->get_head_or_empty_tree(), | ||
| 1131 | ); | ||
| 1132 | |||
| 1133 | my @output = split /\0/, $output; | ||
| 1134 | while (@output >= 2) { | ||
| 1135 | my ($action, $file) = splice @output, 0, 2; | ||
| 1136 | $actions{$file} = $action; | ||
| 1137 | } | ||
| 1138 | |||
| 1139 | return \%actions; | ||
| 1140 | } | ||
| 1141 | |||
| 1142 | sub filter_name_status_in_range { | ||
| 1143 | my ($git, $filter, $from, $to, $options, $paths) = @_; | ||
| 1144 | |||
| 1145 | # If $to is the undefined commit this means that a branch or tag is being | ||
| 1146 | # removed. In this situation we return the empty list, bacause no file | ||
| 1147 | # has been affected. | ||
| 1148 | return {} if $to eq $git->undef_commit; | ||
| 1149 | |||
| 1150 | if ($from eq $git->undef_commit) { | ||
| 1151 | # If $from is the undefined commit we get the list of commits | ||
| 1152 | # reachable from $to and not reachable from $from and all other | ||
| 1153 | # references. This list is in chronological order. We want to grok | ||
| 1154 | # the files changed from the list's first commit's PARENT commit to | ||
| 1155 | # the list's last commit. | ||
| 1156 | |||
| 1157 | if (my @commits = $git->get_commits($from, $to, $options, $paths)) { | ||
| 1158 | if (my @parents = $commits[0]->parent()) { | ||
| 1159 | $from = $parents[0]; | ||
| 1160 | } else { | ||
| 1161 | # If the list's first commit has no parent (i.e., it's a root | ||
| 1162 | # commit) then we return the empty hash because git-diff-tree | ||
| 1163 | # cannot compare the undefined commit with a commit. | ||
| 1164 | return {}; | ||
| 1165 | } | ||
| 1166 | } else { | ||
| 1167 | # If @commits is empty we return an empty hash because no new commit | ||
| 1168 | # was pushed. | ||
| 1169 | return {}; | ||
| 1170 | } | ||
| 1171 | } | ||
| 1172 | |||
| 1173 | my %actions; | ||
| 1174 | |||
| 1175 | my $output = $git->run( | ||
| 1176 | qw/diff-tree --name-status --ignore-submodules --no-commit-id -r -z/, | ||
| 1177 | "--diff-filter=$filter", | ||
| 1178 | $from, $to, '--', | ||
| 1179 | ); | ||
| 1180 | |||
| 1181 | my @output = split /\0/, $output; | ||
| 1182 | while (@output >= 2) { | ||
| 1183 | my ($action, $file) = splice @output, 0, 2; | ||
| 1184 | $actions{$file} = $action; | ||
| 1185 | } | ||
| 1186 | |||
| 1187 | return \%actions; | ||
| 1188 | } | ||
| 1189 | |||
| 1190 | sub filter_name_status_in_commit { | ||
| 1191 | my ($git, $filter, $commit) = @_; | ||
| 1192 | |||
| 1193 | my $output = $git->run( | ||
| 1194 | qw/diff-tree --name-status --ignore-submodules -m -r -z/, | ||
| 1195 | "--diff-filter=$filter", | ||
| 1196 | $commit, | ||
| 1197 | ); | ||
| 1198 | |||
| 1199 | my @output = split /\0/, $output; | ||
| 1200 | |||
| 1201 | # @output is a sequence of commits, actions, and files, with the following | ||
| 1202 | # general pattern: { COMMIT { ACTION FILE }* }+, | ||
| 1203 | |||
| 1204 | # COMMIT is the parent commit of $commit. There can be more than one if | ||
| 1205 | # $commit is a merge commit. | ||
| 1206 | |||
| 1207 | # Below we parse the sequence, tucking all the information in %actions. | ||
| 1208 | |||
| 1209 | my %actions; | ||
| 1210 | |||
| 1211 | my $sha1; | ||
| 1212 | my $action; | ||
| 1213 | my $parents = 0; | ||
| 1214 | my $expect = 'sha1'; | ||
| 1215 | |||
| 1216 | # PARSE @output | ||
| 1217 | while (@output) { | ||
| 1218 | if ($expect eq 'sha1') { | ||
| 1219 | if ($output[0] =~ /^[0-9a-f]{40}$/) { | ||
| 1220 | $sha1 = shift @output; | ||
| 1221 | ++$parents; | ||
| 1222 | $expect = 'sha1 or action'; | ||
| 1223 | } else { | ||
| 1224 | croak; | ||
| 1225 | } | ||
| 1226 | } elsif ($expect eq 'sha1 or action') { | ||
| 1227 | if ($output[0] =~ /^[0-9a-f]{40}$/) { | ||
| 1228 | $sha1 = shift @output; | ||
| 1229 | ++$parents; | ||
| 1230 | } elsif ($output[0] =~ /^[A-Z]$/) { | ||
| 1231 | $action = shift @output; | ||
| 1232 | $expect = 'file'; | ||
| 1233 | } else { | ||
| 1234 | croak; | ||
| 1235 | } | ||
| 1236 | } elsif ($expect eq 'file') { | ||
| 1237 | $actions{shift @output}{$sha1} = $action; | ||
| 1238 | $expect = 'sha1 or action'; | ||
| 1239 | } else { | ||
| 1240 | croak; | ||
| 1241 | } | ||
| 1242 | } | ||
| 1243 | |||
| 1244 | # %actions is a multi-level hash: $actions{$file}{$sha1} = $action. Next | ||
| 1245 | # we remove the $commit level, joining all $actions together under $file. | ||
| 1246 | |||
| 1247 | foreach my $file (keys %actions) { | ||
| 1248 | if (keys(%{$actions{$file}}) == $parents) { | ||
| 1249 | # For merge commits we're interested only in files that were | ||
| 1250 | # affected in all parent commits. For files affected in all parents | ||
| 1251 | # we join their actions together. Non-merge commits ($parents == 1) | ||
| 1252 | # reduce to the general case of merge commits. | ||
| 1253 | $actions{$file} = join('', values %{$actions{$file}}); | ||
| 1254 | } else { | ||
| 1255 | # Files not affected in all parents we don't care about. | ||
| 1256 | delete $actions{$file}; | ||
| 1257 | } | ||
| 1258 | } | ||
| 1259 | |||
| 1260 | return \%actions; | ||
| 1261 | } | ||
| 1262 | |||
| 1263 | sub filter_files_in_index { | ||
| 1264 | my ($git, $filter) = @_; | ||
| 1265 | my @files = sort keys %{$git->filter_name_status_in_index($filter)}; | ||
| 1266 | return @files; | ||
| 1267 | } | ||
| 1268 | |||
| 1269 | sub filter_files_in_range { | ||
| 1270 | my ($git, @args) = @_; | ||
| 1271 | my @files = sort keys %{$git->filter_name_status_in_range(@args)}; | ||
| 1272 | return @files; | ||
| 1273 | } | ||
| 1274 | |||
| 1275 | sub filter_files_in_commit { | ||
| 1276 | my ($git, $commit) = @_; | ||
| 1277 | my @files = sort keys %{$git->filter_name_status_in_commit($commit)}; | ||
| 1278 | return @files; | ||
| 1279 | } | ||
| 1280 | |||
| 1281 | sub authenticated_user { | ||
| 1282 | my ($git) = @_; | ||
| 1283 | |||
| 1284 | unless (exists $git->{_plugin_githooks}{authenticated_user}) { | ||
| 1285 | if (my $userenv = $git->get_config(githooks => 'userenv')) { | ||
| 1286 | if ($userenv =~ /^eval:(.*)/) { | ||
| 1287 | $git->{_plugin_githooks}{authenticated_user} = eval $1; ## no critic (BuiltinFunctions::ProhibitStringyEval) | ||
| 1288 | croak __PACKAGE__, ": error evaluating userenv value ($userenv): $@\n" | ||
| 1289 | if $@; | ||
| 1290 | } elsif (exists $ENV{$userenv}) { | ||
| 1291 | $git->{_plugin_githooks}{authenticated_user} = $ENV{$userenv}; | ||
| 1292 | } else { | ||
| 1293 | croak __PACKAGE__, ": option userenv environment variable ($userenv) is not defined.\n"; | ||
| 1294 | } | ||
| 1295 | } else { | ||
| 1296 | $git->{_plugin_githooks}{authenticated_user} = $ENV{GERRIT_USER_EMAIL} || $ENV{BB_USER_NAME} || $ENV{GL_USERNAME} || $ENV{USER} || undef; | ||
| 1297 | } | ||
| 1298 | } | ||
| 1299 | |||
| 1300 | return $git->{_plugin_githooks}{authenticated_user}; | ||
| 1301 | } | ||
| 1302 | |||
| 1303 | sub repository_name { | ||
| 1304 | my ($git) = @_; | ||
| 1305 | |||
| 1306 | unless (exists $git->{_plugin_githooks}{repository_name}) { | ||
| 1307 | if (my $gerrit_args = $git->{_plugin_githooks}{gerrit_args}) { | ||
| 1308 | # Gerrit | ||
| 1309 | $git->{_plugin_githooks}{repository_name} = $gerrit_args->{'--project'}; | ||
| 1310 | } elsif (exists $ENV{BB_REPO_SLUG}) { | ||
| 1311 | # Bitbucket Server environment variables available for hooks: | ||
| 1312 | # https://developer.atlassian.com/server/bitbucket/how-tos/write-hook-scripts/ | ||
| 1313 | $git->{_plugin_githooks}{repository_name} = "$ENV{BB_PROJECT_KEY}/$ENV{BB_REPO_SLUG}"; | ||
| 1314 | } elsif (exists $ENV{GL_PROJECT_PATH}) { | ||
| 1315 | # GitLab environment variables available for hooks: | ||
| 1316 | # https://docs.gitlab.com/ee/administration/server_hooks.html | ||
| 1317 | $git->{_plugin_githooks}{repository_name} = "$ENV{GL_PROJECT_PATH}"; | ||
| 1318 | } else { | ||
| 1319 | # As a last resort, return GIT_DIR's basename | ||
| 1320 | my $gitdir = path($git->git_dir()); | ||
| 1321 | my $basename = $gitdir->basename; | ||
| 1322 | if ($basename eq '.git') { | ||
| 1323 | $basename = $gitdir->parent->basename; | ||
| 1324 | } | ||
| 1325 | $git->{_plugin_githooks}{repository_name} = $basename; | ||
| 1326 | } | ||
| 1327 | } | ||
| 1328 | |||
| 1329 | return $git->{_plugin_githooks}{repository_name}; | ||
| 1330 | } | ||
| 1331 | |||
| 1332 | sub get_current_branch { | ||
| 1333 | my ($git) = @_; | ||
| 1334 | my $branch = $git->run({fatal => [-129, -128], quiet => 1}, qw/symbolic-ref HEAD/); | ||
| 1335 | |||
| 1336 | # Return undef if we're in detached head state | ||
| 1337 | return $? == 0 ? $branch : undef; | ||
| 1338 | } | ||
| 1339 | |||
| 1340 | sub get_sha1 { | ||
| 1341 | my ($git, $rev) = @_; | ||
| 1342 | |||
| 1343 | return $git->run(qw/rev-parse --verify/, $rev); | ||
| 1344 | } | ||
| 1345 | |||
| 1346 | sub get_head_or_empty_tree { | ||
| 1347 | my ($git) = @_; | ||
| 1348 | |||
| 1349 | my $head = $git->run({fatal => [-129, -128], quiet => 1}, qw/rev-parse --verify HEAD/); | ||
| 1350 | |||
| 1351 | # Return the empty tree object if in the initial commit | ||
| 1352 | return $? == 0 ? $head : $git->empty_tree; | ||
| 1353 | } | ||
| 1354 | |||
| 1355 | sub blob { | ||
| 1356 | my ($git, $rev, $file, @args) = @_; | ||
| 1357 | |||
| 1358 | my $cache = $git->cache('blob'); | ||
| 1359 | |||
| 1360 | my $blob = "$rev:$file"; | ||
| 1361 | |||
| 1362 | unless (exists $cache->{$blob}) { | ||
| 1363 | $cache->{tmpdir} //= Path::Tiny->tempdir(@args); | ||
| 1364 | |||
| 1365 | my $path = path($file); | ||
| 1366 | |||
| 1367 | # Calculate temporary file path | ||
| 1368 | my $revdir = $rev =~ s/^://r; # remove ':' from ':0' because Windows don't like ':' in filenames | ||
| 1369 | my $filepath = $cache->{tmpdir}->child($revdir, $path); | ||
| 1370 | |||
| 1371 | # Create directory path for the temporary file. | ||
| 1372 | $filepath->parent->mkpath; | ||
| 1373 | |||
| 1374 | # Create temporary file and copy contents to it | ||
| 1375 | open my $tmp, '>:', $filepath ## no critic (RequireBriefOpen) | ||
| 1376 | or croak "Internal error: can't create file '$filepath': $!"; | ||
| 1377 | |||
| 1378 | my $cmd = $git->command(qw/cat-file blob/, $blob); | ||
| 1379 | my $stdout = $cmd->stdout; | ||
| 1380 | my $read; | ||
| 1381 | while ($read = sysread $stdout, my $buffer, 64 * 1024) { | ||
| 1382 | my $length = length $buffer; | ||
| 1383 | my $offset = 0; | ||
| 1384 | while ($length) { | ||
| 1385 | my $written = syswrite $tmp, $buffer, $length, $offset; | ||
| 1386 | defined $written | ||
| 1387 | or croak "Internal error: can't write to '$filepath': $!"; | ||
| 1388 | $length -= $written; | ||
| 1389 | $offset += $written; | ||
| 1390 | } | ||
| 1391 | } | ||
| 1392 | defined $read | ||
| 1393 | or croak "Internal error: can't read from git cat-file pipe: $!"; | ||
| 1394 | $cmd->close; | ||
| 1395 | |||
| 1396 | $tmp->close; | ||
| 1397 | |||
| 1398 | if (my $exit = $cmd->exit) { | ||
| 1399 | croak "Command 'git cat-file blob $blob' exited with code $exit\n"; | ||
| 1400 | } | ||
| 1401 | |||
| 1402 | $cache->{$blob} = $filepath; | ||
| 1403 | } | ||
| 1404 | |||
| 1405 | return $cache->{$blob}->stringify; | ||
| 1406 | } | ||
| 1407 | |||
| 1408 | sub file_size { | ||
| 1409 | my ($git, $rev, $file) = @_; | ||
| 1410 | |||
| 1411 | return $git->run(qw/cat-file -s/, "$rev:$file"); | ||
| 1412 | } | ||
| 1413 | |||
| 1414 | sub file_mode { | ||
| 1415 | my ($git, $rev, $file) = @_; | ||
| 1416 | |||
| 1417 | if ($rev eq ':0') { | ||
| 1418 | my @diff_index = $git->run(qw/diff-index --cached --raw --no-color HEAD/, $file); | ||
| 1419 | |||
| 1420 | if (@diff_index == 1) { | ||
| 1421 | if (my ($src_mode, $dst_mode, $rest) = $diff_index[0] =~ /^:(\d+) (\d+) (.*)/) { | ||
| 1422 | return oct $dst_mode; | ||
| 1423 | } else { | ||
| 1424 | croak "Internal error: cannot parse output of git-diff-idex:\n\n $diff_index[0]"; | ||
| 1425 | } | ||
| 1426 | } else { | ||
| 1427 | croak "Internal error: git-diff-index should return a single line"; | ||
| 1428 | } | ||
| 1429 | } else { | ||
| 1430 | my @ls_tree = $git->run('ls-tree', "$rev:", $file ); | ||
| 1431 | |||
| 1432 | if (@ls_tree == 1) { | ||
| 1433 | if (my ($mode, $type, $object, $filename) = | ||
| 1434 | $ls_tree[0] =~ /^(\d+) ([a-z]+) ([a-z0-9]{40})\t(.+)/) { | ||
| 1435 | return oct $mode; | ||
| 1436 | } else { | ||
| 1437 | croak "Internal error: cannot parse output of git-ls-tree:\n\n $ls_tree[0]"; | ||
| 1438 | } | ||
| 1439 | } else { | ||
| 1440 | croak "Internal error: $rev:$file should be a blob"; | ||
| 1441 | } | ||
| 1442 | } | ||
| 1443 | |||
| 1444 | croak "Can't happen!"; | ||
| 1445 | } | ||
| 1446 | |||
| 1447 | sub is_reference_enabled { | ||
| 1448 | my ($git, $reference) = @_; | ||
| 1449 | |||
| 1450 | return 1 unless defined $reference; | ||
| 1451 | |||
| 1452 | my $cache = $git->cache('is_reference_enabled'); | ||
| 1453 | |||
| 1454 | unless (exists $cache->{$reference}) { | ||
| 1455 | my $check_reference = sub { | ||
| 1456 | foreach ($git->get_config(githooks => 'ref')) { | ||
| 1457 | if (/^\^/) { | ||
| 1458 | return 1 if $reference =~ qr/$_/; | ||
| 1459 | } else { | ||
| 1460 | return 1 if $reference eq $_; | ||
| 1461 | } | ||
| 1462 | } | ||
| 1463 | |||
| 1464 | foreach ($git->get_config(githooks => 'noref')) { | ||
| 1465 | if (/^\^/) { | ||
| 1466 | return 0 if $reference =~ qr/$_/; | ||
| 1467 | } else { | ||
| 1468 | return 0 if $reference eq $_; | ||
| 1469 | } | ||
| 1470 | } | ||
| 1471 | |||
| 1472 | return 1; | ||
| 1473 | }; | ||
| 1474 | |||
| 1475 | $cache->{$reference} = $check_reference->(); | ||
| 1476 | } | ||
| 1477 | |||
| 1478 | return $cache->{$reference}; | ||
| 1479 | } | ||
| 1480 | |||
| 1481 | sub _grok_groups_spec { | ||
| 1482 | my ($groups, $specs, $source) = @_; | ||
| 1483 | foreach (@$specs) { | ||
| 1484 | s/\#.*//; # strip comments | ||
| 1485 | next unless /\S/; # skip blank lines | ||
| 1486 | /^\s*([\w-]+)\s*=\s*(.+?)\s*$/ | ||
| 1487 | or croak __PACKAGE__, ": invalid line in '$source': $_\n"; | ||
| 1488 | my ($groupname, $members) = ($1, $2); | ||
| 1489 | exists $groups->{"\@$groupname"} | ||
| 1490 | and croak __PACKAGE__, ": redefinition of group ($groupname) in '$source': $_\n"; | ||
| 1491 | foreach my $member (split ' ', $members) { | ||
| 1492 | if ($member =~ /^\@/) { | ||
| 1493 | # group member | ||
| 1494 | $groups->{"\@$groupname"}{$member} = $groups->{$member} | ||
| 1495 | or croak __PACKAGE__, ": unknown group ($member) cited in '$source': $_\n"; | ||
| 1496 | } else { | ||
| 1497 | # user member | ||
| 1498 | $groups->{"\@$groupname"}{$member} = undef; | ||
| 1499 | } | ||
| 1500 | } | ||
| 1501 | } | ||
| 1502 | return; | ||
| 1503 | } | ||
| 1504 | |||
| 1505 | sub _grok_groups { | ||
| 1506 | my ($git) = @_; | ||
| 1507 | |||
| 1508 | my $cache = $git->cache('githooks'); | ||
| 1509 | |||
| 1510 | unless (exists $cache->{groups}) { | ||
| 1511 | my @groups = $git->get_config(githooks => 'groups') | ||
| 1512 | or croak __PACKAGE__, ": you have to define the githooks.groups option to use groups.\n"; | ||
| 1513 | |||
| 1514 | my $groups = {}; | ||
| 1515 | foreach my $spec (@groups) { | ||
| 1516 | if (my ($groupfile) = ($spec =~ /^file:(.*)/)) { | ||
| 1517 | my @groupspecs = path($groupfile)->lines; | ||
| 1518 | defined $groupspecs[0] | ||
| 1519 | or croak __PACKAGE__, ": can't open groups file ($groupfile): $!\n"; | ||
| 1520 | _grok_groups_spec($groups, \@groupspecs, $groupfile); | ||
| 1521 | } else { | ||
| 1522 | my @groupspecs = split /\n/, $spec; | ||
| 1523 | _grok_groups_spec($groups, \@groupspecs, "githooks.groups"); | ||
| 1524 | } | ||
| 1525 | } | ||
| 1526 | $cache->{groups} = $groups; | ||
| 1527 | } | ||
| 1528 | |||
| 1529 | return $cache->{groups}; | ||
| 1530 | } | ||
| 1531 | |||
| 1532 | sub _im_memberof { | ||
| 1533 | my ($git, $myself, $groupname) = @_; | ||
| 1534 | |||
| 1535 | my $groups = _grok_groups($git); | ||
| 1536 | |||
| 1537 | exists $groups->{$groupname} | ||
| 1538 | or croak __PACKAGE__, ": group $groupname is not defined.\n"; | ||
| 1539 | |||
| 1540 | my $group = $groups->{$groupname}; | ||
| 1541 | return 1 if exists $group->{$myself}; | ||
| 1542 | while (my ($member, $subgroup) = each %$group) { | ||
| 1543 | next unless defined $subgroup; | ||
| 1544 | return 1 if _im_memberof($git, $myself, $member); | ||
| 1545 | } | ||
| 1546 | return 0; | ||
| 1547 | } | ||
| 1548 | |||
| 1549 | sub match_user { | ||
| 1550 | my ($git, $spec) = @_; | ||
| 1551 | |||
| 1552 | if (my $myself = $git->authenticated_user()) { | ||
| 1553 | if ($spec =~ /^\^/) { | ||
| 1554 | return 1 if $myself =~ $spec; | ||
| 1555 | } elsif ($spec =~ /^@/) { | ||
| 1556 | return 1 if _im_memberof($git, $myself, $spec); | ||
| 1557 | } else { | ||
| 1558 | return 1 if $myself eq $spec; | ||
| 1559 | } | ||
| 1560 | } | ||
| 1561 | |||
| 1562 | return 0; | ||
| 1563 | } | ||
| 1564 | |||
| 1565 | sub im_admin { | ||
| 1566 | my ($git) = @_; | ||
| 1567 | foreach my $spec ($git->get_config(githooks => 'admin')) { | ||
| 1568 | return 1 if match_user($git, $spec); | ||
| 1569 | } | ||
| 1570 | return 0; | ||
| 1571 | } | ||
| 1572 | |||
| 1573 | sub grok_acls { | ||
| 1574 | my ($git, $cfg, $actions) = @_; | ||
| 1575 | |||
| 1576 | my @acls; | ||
| 1577 | |||
| 1578 | ACL: | ||
| 1579 | foreach ($git->get_config($cfg => 'acl')) { | ||
| 1580 | my %acl; | ||
| 1581 | if (/^\s*(allow|deny)\s+([$actions]+)\s+(\S+)/) { | ||
| 1582 | $acl{acl} = $_; | ||
| 1583 | $acl{allow} = $1 eq 'allow'; | ||
| 1584 | $acl{action} = $2; | ||
| 1585 | my $spec = $3; | ||
| 1586 | |||
| 1587 | # Interpolate environment variables embedded as "{VAR}". | ||
| 1588 | $spec =~ s/{(\w+)}/$ENV{$1}/ige; | ||
| 1589 | # Pre-compile regex | ||
| 1590 | $acl{spec} = substr($spec, 0, 1) eq '^' ? qr/$spec/ : $spec; | ||
| 1591 | } else { | ||
| 1592 | croak "invalid acl syntax for actions '$actions': $_\n"; | ||
| 1593 | } | ||
| 1594 | |||
| 1595 | if (substr($_, $+[0]) =~ /^\s*by\s+(\S+)\s*$/) { | ||
| 1596 | $acl{who} = $1; | ||
| 1597 | # Discard this ACL if it doesn't match the user | ||
| 1598 | next ACL unless $git->match_user($acl{who}); | ||
| 1599 | } elsif (substr($_, $+[0]) !~ /^\s*$/) { | ||
| 1600 | croak "invalid acl syntax for actions '$actions: $_\n"; | ||
| 1601 | } | ||
| 1602 | |||
| 1603 | unshift @acls, \%acl; | ||
| 1604 | } | ||
| 1605 | |||
| 1606 | return @acls; | ||
| 1607 | } | ||
| 1608 | |||
| 1609 | |||
| 1610 | 1; # End of Git::Repository::Plugin::GitHooks | ||
| 1611 | |||
| 1612 | __END__ |