push.pl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #!/usr/bin/env perl
  2. use strict;
  3. use warnings;
  4. use 5.010;
  5. use open ':encoding(utf8)';
  6. use File::Basename qw(basename fileparse);
  7. use File::Temp;
  8. use Getopt::Long;
  9. use Mojo::File;
  10. use Mojo::JSON qw(decode_json);
  11. use Mojo::UserAgent;
  12. use Mojo::Util qw(decode encode trim url_escape);
  13. use Term::UI;
  14. use Term::ReadLine;
  15. require bytes; # this is not recommended, but we *only* use "bytes::length" from it to determine whether we need to do a more correct conversion to/from bytes for trimming (see $hubLengthLimit and usages)
  16. my $hubLengthLimit = 25_000; # NOTE: this is *bytes*, not characters 🙃
  17. my $githubBase = 'https://github.com/docker-library/docs/tree/master'; # TODO point this at the correct "dist-xxx" branch based on "namespace"
  18. my $username;
  19. my $password;
  20. my $batchmode;
  21. my $namespace;
  22. my $logos;
  23. GetOptions(
  24. 'u|username=s' => \$username,
  25. 'p|password=s' => \$password,
  26. 'batchmode!' => \$batchmode,
  27. 'namespace=s' => \$namespace,
  28. 'logos!' => \$logos,
  29. ) or die 'bad args';
  30. die 'no repos specified' unless @ARGV;
  31. my $ua = Mojo::UserAgent->new->max_redirects(10);
  32. $ua->transactor->name('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36');
  33. my $term = Term::ReadLine->new('docker-library-docs-push');
  34. unless (defined $username) {
  35. $username = $term->get_reply(prompt => 'Hub Username');
  36. }
  37. unless (defined $password) {
  38. $password = $term->get_reply(prompt => 'Hub Password'); # TODO hide the input? O:)
  39. }
  40. my $dockerHub = 'https://hub.docker.com';
  41. my $login = $ua->post($dockerHub . '/v2/users/login/' => {} => json => { username => $username, password => $password });
  42. die 'login failed: ' . $login->res->error->{message} unless $login->res->is_success;
  43. my $token = $login->res->json->{token};
  44. my $authorizationHeader = {
  45. Authorization => "JWT $token",
  46. };
  47. my $supportedTagsRegex = qr%^(# Supported tags and respective `Dockerfile` links\n\n)(.*?\n)(?=# |\[)%ms;
  48. sub prompt_for_edit {
  49. my $currentText = shift;
  50. my $proposedFile = shift;
  51. my $lengthLimit = shift // 0;
  52. my $proposedText = Mojo::File->new($proposedFile)->slurp // '** FILE MISSING! **';
  53. $proposedText = trim(decode('UTF-8', $proposedText));
  54. # remove our warning about generated files (Hub doesn't support HTML comments in Markdown)
  55. $proposedText =~ s% ^ <!-- .*? --> \s* %%sx;
  56. # extract/re-inject sponsored links
  57. my $sponsoredLinks = '';
  58. if ($currentText =~ m{ ( ^ [#] \Q Sponsored Resources\E \n .*? \n --- \n ) }smx) {
  59. $sponsoredLinks = $1 . "\n";
  60. $proposedText =~ s%$supportedTagsRegex%$sponsoredLinks$1$2%;
  61. }
  62. if ($lengthLimit > 0 && bytes::length($proposedText) > $lengthLimit) {
  63. # TODO https://github.com/docker/hub-beta-feedback/issues/238
  64. my $fullUrl = "$githubBase/$proposedFile";
  65. my $shortTags = "-\tSee [\"Supported tags and respective \`Dockerfile\` links\" at $fullUrl]($fullUrl#supported-tags-and-respective-dockerfile-links)\n\n";
  66. my $seeAlso = 'See also [docker/hub-feedback#238](https://github.com/docker/hub-feedback/issues/238) and [docker/roadmap#475](https://github.com/docker/roadmap/issues/475).';
  67. my $tagsNote = "**Note:** the description for this image is longer than the Hub length limit of $lengthLimit, so the \"Supported tags\" list has been trimmed to compensate. $seeAlso\n\n$shortTags";
  68. my $genericNote = "**Note:** the description for this image is longer than the Hub length limit of $lengthLimit, so has been trimmed. The full description can be found at [$fullUrl]($fullUrl). $seeAlso";
  69. my $startingNote = $genericNote . "\n\n";
  70. my $endingNote = "\n\n...\n\n" . $genericNote;
  71. my $trimmedText = $proposedText;
  72. # if our text is too long for the Hub length limit, let's first try removing the "Supported tags" list and add $tagsNote and see if that's enough to let us put the full image documentation
  73. $trimmedText =~ s%$supportedTagsRegex%$sponsoredLinks$1$tagsNote%ms;
  74. # (we scrape until the next "h1" or a line starting with a link which is likely a build status badge for an architecture-namespace)
  75. if (bytes::length($trimmedText) > $lengthLimit) {
  76. # ... if that doesn't do the trick, then do our older naïve description trimming (respecting utf8; see https://www.perlmonks.org/?node_id=1230659 and https://perldoc.perl.org/utf8)
  77. $trimmedText = $proposedText;
  78. utf8::encode($trimmedText);
  79. $trimmedText = $startingNote . substr $trimmedText, 0, ($lengthLimit - bytes::length($startingNote . $endingNote));
  80. # (deal with the potential of "bytes::substr" here cutting us in the middle of a unicode glyph, which is arguably a much worse problem than the markdown cutting described below 😬 again, see https://www.perlmonks.org/?node_id=1230659)
  81. $trimmedText =~ s/(?:
  82. [\xC0-\xDF]
  83. | [\xE0-\xEF] [\x80-\xBF]?
  84. | [\xF0-\xF7] [\x80-\xBF]{0,2}
  85. )\z//x;
  86. utf8::decode($trimmedText);
  87. # adding the "ending note" (https://github.com/docker/hub-feedback/issues/2220) is a bit more complicated as we have to deal with cutting off markdown ~cleanly so it renders correctly
  88. # TODO deal with "```foo" appropriately (so we don't drop our note in the middle of a code block) - the Hub's current markdown rendering (2022-04-07) does not auto-close a dangling block like this, so this isn't urgent
  89. if ($trimmedText =~ m/\n$/) {
  90. # if we already end with a newline, we should be fine to just trim newlines and add our ending note
  91. $trimmedText =~ s/\n+$//;
  92. }
  93. else {
  94. # otherwise, we need to get a little bit more creative and trim back to the last fully blank line (which we can reasonably assume is safe thanks to our markdownfmt)
  95. $trimmedText =~ s/\n\n(.\n?)*$//;
  96. }
  97. $trimmedText .= $endingNote;
  98. }
  99. $proposedText = $trimmedText;
  100. }
  101. return $currentText if $currentText eq $proposedText;
  102. my @proposedFileBits = fileparse($proposedFile, qr!\.[^.]*!);
  103. my $file = File::Temp->new(SUFFIX => '-' . basename($proposedFileBits[1]) . '-current' . $proposedFileBits[2]);
  104. my $filename = $file->filename;
  105. Mojo::File->new($filename)->spurt(encode('UTF-8', $currentText . "\n"));
  106. my $tempProposedFile = File::Temp->new(SUFFIX => '-' . basename($proposedFileBits[1]) . '-proposed' . $proposedFileBits[2]);
  107. my $tempProposedFilename = $tempProposedFile->filename;
  108. Mojo::File->new($tempProposedFilename)->spurt(encode('UTF-8', $proposedText . "\n"));
  109. system(qw(git --no-pager diff --no-index), $filename, $tempProposedFilename);
  110. my $reply;
  111. if ($batchmode) {
  112. $reply = 'yes';
  113. }
  114. else {
  115. $reply = $term->get_reply(
  116. prompt => 'Apply changes?',
  117. choices => [ qw( yes vimdiff no quit ) ],
  118. default => 'yes',
  119. );
  120. }
  121. if ($reply eq 'quit') {
  122. say 'quitting, as requested';
  123. exit;
  124. }
  125. if ($reply eq 'yes') {
  126. return $proposedText;
  127. }
  128. if ($reply eq 'vimdiff') {
  129. system('vimdiff', $tempProposedFilename, $filename) == 0 or die "vimdiff on $filename and $proposedFile failed";
  130. return trim(decode('UTF-8', Mojo::File->new($filename)->slurp));
  131. }
  132. return $currentText;
  133. }
  134. while (my $repo = shift) { # 'library/hylang', 'tianon/perl', etc
  135. $repo =~ s!^/+|/+$!!; # trim extra slashes (from "*/" globbing, for example)
  136. $repo = $namespace . '/' . $repo if $namespace; # ./push.pl --namespace xxx ...
  137. $repo = 'library/' . $repo unless $repo =~ m!/!; # "hylang" -> "library/hylang"
  138. my $repoName = $repo;
  139. $repoName =~ s!^.*/!!; # 'hylang', 'perl', etc
  140. my $repoUrl = $dockerHub . '/v2/repositories/' . $repo . '/';
  141. if ($logos && $repo =~ m{ ^ library/ }x) {
  142. # only DOI ("library"), DSOS, or DVP orgs can include a logo which is displayed in the Hub UI
  143. # if we have a logo file, let's update that metadata first
  144. my $repoLogo120 = $repoName . '/logo-120.png';
  145. if (!-f $repoLogo120) {
  146. my $repoLogoPng = $repoName . '/logo.png';
  147. my $repoLogoSvg = $repoName . '/logo.svg';
  148. my $logoToConvert = (
  149. -f $repoLogoPng
  150. ? $repoLogoPng
  151. : $repoLogoSvg
  152. );
  153. if (-f $logoToConvert) {
  154. say 'converting ' . $logoToConvert . ' to ' . $repoLogo120;
  155. system(
  156. qw( convert -background none -density 1200 -strip -resize 120x120> -gravity center -extent 120x120 ),
  157. $logoToConvert,
  158. $repoLogo120,
  159. ) == 0 or die "failed to convert $logoToConvert into $repoLogo120";
  160. }
  161. }
  162. my $logoUrlBase = $dockerHub . '/api/media/repos_logo/v1/' . url_escape($repo);
  163. if (-f $repoLogo120) {
  164. my $proposedLogo = Mojo::File->new($repoLogo120)->slurp;
  165. my $currentLogo = $ua->get($logoUrlBase, { 'Cache-Control' => 'no-cache' });
  166. $currentLogo = ($currentLogo->res->is_success ? $currentLogo->res->body : undef);
  167. if ($currentLogo && $currentLogo eq $proposedLogo) {
  168. say 'no change to ' . $repoName . ' logo; skipping';
  169. }
  170. else {
  171. say 'putting logo ' . $repoLogo120;
  172. my $logoUpload = $ua->post($logoUrlBase . '/upload' => { %$authorizationHeader, 'Content-Type' => 'image/png' } => $proposedLogo);
  173. die 'POST to ' . $logoUrlBase . '/upload failed: ' . $logoUpload->res->text unless $logoUpload->res->is_success;
  174. }
  175. } else {
  176. # if we had no logo file, we should send a DELETE request to the API just to be sure we're synchronizing the repo state appropriately even on complete logo removal
  177. say 'no ' . $repoLogo120 . '; deleting logo';
  178. my $logoDelete = $ua->delete($logoUrlBase => $authorizationHeader);
  179. die 'DELETE to ' . $logoUrlBase . ' failed: ' . $logoDelete->res->text unless $logoDelete->res->is_success or $logoDelete->res->code == 404;
  180. }
  181. }
  182. my $repoTx = $ua->get($repoUrl => $authorizationHeader);
  183. warn 'warning: failed to get: ' . $repoUrl . ' (skipping)' and next unless $repoTx->res->is_success;
  184. my $repoDetails = $repoTx->res->json;
  185. $repoDetails->{description} //= '';
  186. $repoDetails->{full_description} //= '';
  187. $repoDetails->{categories} //= [];
  188. my @repoCategories = sort map { $_->{slug} } @{ $repoDetails->{categories} };
  189. # read local categories from metadata.json
  190. my $repoMetadataBytes = Mojo::File->new($repoName . '/metadata.json')->slurp;
  191. my $repoMetadataJson = decode_json $repoMetadataBytes;
  192. my @localRepoCategories = sort @{ $repoMetadataJson->{hub}{categories} };
  193. # check if the local categories differ in length or items from the remote
  194. my $needCat = @localRepoCategories != @repoCategories;
  195. if (! $needCat) {
  196. foreach my $i (0 .. @localRepoCategories) {
  197. last if ! defined $repoCategories[$i]; # length difference already covered, so we can bail
  198. if ($localRepoCategories[$i] ne $repoCategories[$i]) {
  199. $needCat = 1;
  200. last;
  201. }
  202. }
  203. }
  204. if ($needCat) {
  205. say 'updating ' . $repoName . ' categories';
  206. my $catsPatch = $ua->patch($repoUrl . 'categories/' => { %$authorizationHeader, Accept => 'application/json' } => json => [
  207. map { {
  208. slug => $_,
  209. name => 'All those moments will be lost in time, like tears in rain... Time to die.',
  210. } } @{ $repoMetadataJson->{hub}{categories} }
  211. ]);
  212. die 'patch to categories failed: ' . $catsPatch->res->text unless $catsPatch->res->is_success;
  213. }
  214. my $hubShort = prompt_for_edit($repoDetails->{description}, $repoName . '/README-short.txt');
  215. my $hubLong = prompt_for_edit($repoDetails->{full_description}, $repoName . '/README.md', $hubLengthLimit);
  216. say 'no change to ' . $repoName . '; skipping' and next if $repoDetails->{description} eq $hubShort and $repoDetails->{full_description} eq $hubLong;
  217. say 'updating ' . $repoName;
  218. my $repoPatch = $ua->patch($repoUrl => $authorizationHeader => json => {
  219. description => $hubShort,
  220. full_description => $hubLong,
  221. });
  222. die 'patch to ' . $repoUrl . ' failed: ' . $repoPatch->res->text unless $repoPatch->res->is_success;
  223. }