|
#!/usr/bin/perl |
|
use strict; |
|
use warnings; |
|
|
|
use DateTime; |
|
|
|
# generate the commit line |
|
sub create_commit { |
|
my ($commit_url, $commit_content) = @_; |
|
|
|
# sanitize the commit content |
|
$commit_content =~ s/`/\\`/g; # escaping any backticks |
|
$commit_content =~ s/^\s+|\s+$//g; # and removing leading/trailing whitespace |
|
|
|
# get the current date and time, and convert to PST |
|
my $dt = DateTime->now(); |
|
$dt->set_time_zone('America/Los_Angeles'); |
|
my $now = $dt->strftime('%Y-%m-%d %H:%M:%S %Z'); |
|
|
|
return "- [`$commit_content`]($commit_url) ($now)"; |
|
} |
|
|
|
# update the commits section in PR body |
|
sub update_commits_section { |
|
my ($body, $commit_url, $commit_content) = @_; |
|
my $commits_section_start = "<!--START_SECTION:commits-->"; |
|
my $commits_section_end = "<!--END_SECTION:commits-->"; |
|
my $new_commit = create_commit($commit_url, $commit_content); |
|
|
|
# extract the commits section |
|
if ($body =~ /$commits_section_start(.*?)$commits_section_end/s) { |
|
print STDERR "debug: found commits section\n"; |
|
my $commits_content = $1; |
|
|
|
# determine if we need newlines at the end |
|
my $end_newline = $commits_content =~ /\S/ ? "" : "\n"; |
|
|
|
# replace the old commits section with the updated one |
|
$body =~ s/\Q$commits_section_start$commits_content$commits_section_end\E/ |
|
$commits_section_start |
|
. "\n" |
|
. $new_commit |
|
. $commits_content |
|
. $end_newline |
|
. $commits_section_end |
|
/sxe; |
|
|
|
return $body; |
|
} |
|
|
|
# if the commits section doesn't exist, add it to the end of the body |
|
print STDERR "debug: writing commits section"; |
|
|
|
$body .= "\n\n" |
|
. $commits_section_start |
|
. "\n" |
|
. $new_commit |
|
. "\n" |
|
. $commits_section_end; |
|
|
|
return $body; |
|
} |
|
|
|
sub usage { |
|
my $usage .= "$0 - update the commits section in a PR body\n" |
|
. "version: 1.0.0\n\n" |
|
. "Arguments:\n" |
|
. " body: the body of the PR\n" |
|
. " commit_url: the sha of the commit\n" |
|
. " commit_content: the content of the commit\n" |
|
. "Usage: $0 <body> <commit_url> <commit_content>\n\n" |
|
. "Example: $0 \"chore: lint\" \"b47f8c0\" \"chore: lint\""; |
|
|
|
print $usage; |
|
exit 1; |
|
} |
|
|
|
if ($#ARGV != 2) { |
|
usage(); |
|
} |
|
|
|
my ($body, $commit_url, $commit_content) = @ARGV; |
|
|
|
# ensure the commit url matches the expected format |
|
if ($commit_url !~ /https:\/\/github\.com\/[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}\/(?!.*([.]{2}|^[.]{1}$))[\w.-]{1,100}\/commit\/[0-9a-f]{7,40}$/) { |
|
print STDERR "error: commit url failed validation\n"; |
|
exit 1; |
|
} |
|
|
|
my $result = update_commits_section($body, $commit_url, $commit_content); |
|
print $result; |