push.pl 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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::UserAgent;
  10. use Mojo::Util qw(b64_encode decode encode slurp spurt trim);
  11. use Term::UI;
  12. use Term::ReadLine;
  13. my $hubLengthLimit = 25_000;
  14. my $githubBase = 'https://github.com/docker-library/docs/tree/master'; # TODO point this at the correct "dist-xxx" branch based on "namespace"
  15. my $username;
  16. my $password;
  17. my $batchmode;
  18. my $namespace;
  19. my $logos;
  20. GetOptions(
  21. 'u|username=s' => \$username,
  22. 'p|password=s' => \$password,
  23. 'batchmode!' => \$batchmode,
  24. 'namespace=s' => \$namespace,
  25. 'logos!' => \$logos,
  26. ) or die 'bad args';
  27. die 'no repos specified' unless @ARGV;
  28. my $ua = Mojo::UserAgent->new->max_redirects(10);
  29. $ua->transactor->name('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36');
  30. my $term = Term::ReadLine->new('docker-library-docs-push');
  31. unless (defined $username) {
  32. $username = $term->get_reply(prompt => 'Hub Username');
  33. }
  34. unless (defined $password) {
  35. $password = $term->get_reply(prompt => 'Hub Password'); # TODO hide the input? O:)
  36. }
  37. my $login = $ua->post('https://hub.docker.com/v2/users/login/' => {} => json => { username => $username, password => $password });
  38. die 'login failed' unless $login->success;
  39. my $token = $login->res->json->{token};
  40. my $csrf;
  41. for my $cookie (@{ $login->res->cookies }) {
  42. if ($cookie->name eq 'csrftoken') {
  43. $csrf = $cookie->value;
  44. last;
  45. }
  46. }
  47. die 'missing CSRF token' unless defined $csrf;
  48. my $attemptLogin = $ua->post('https://hub.docker.com/attempt-login/' => {} => json => { jwt => $token });
  49. die 'attempt-login failed' unless $attemptLogin->success;
  50. my $authorizationHeader = {
  51. Authorization => "JWT $token",
  52. 'X-CSRFToken' => $csrf,
  53. };
  54. my $userData = $ua->get('https://hub.docker.com/v2/user/' => $authorizationHeader);
  55. die 'user failed' unless $userData->success;
  56. $userData = $userData->res->json;
  57. sub prompt_for_edit {
  58. my $currentText = shift;
  59. my $proposedFile = shift;
  60. my $lengthLimit = shift // 0;
  61. my $proposedText = slurp $proposedFile or warn 'missing ' . $proposedFile;
  62. $proposedText = trim(decode('UTF-8', $proposedText));
  63. # remove our warning about generated files (Hub doesn't support HTML comments in Markdown)
  64. $proposedText =~ s% ^ <!-- .*? --> \s* %%sx;
  65. if ($lengthLimit > 0 && length($proposedText) > $lengthLimit) {
  66. # TODO https://github.com/docker/hub-beta-feedback/issues/238
  67. my $fullUrl = "$githubBase/$proposedFile";
  68. 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. The full list can be found at [$fullUrl]($fullUrl#supported-tags-and-respective-dockerfile-links). See [docker/hub-beta-feedback#238](https://github.com/docker/hub-beta-feedback/issues/238) for more information.\n\n";
  69. 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). See [docker/hub-beta-feedback#238](https://github.com/docker/hub-beta-feedback/issues/238) for more information.\n\n";
  70. my $trimmedText = $proposedText;
  71. # 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
  72. $trimmedText =~ s%^(# Supported tags and respective `Dockerfile` links\n\n).*?\n(?=# |\[)%$1$tagsNote%ms;
  73. # (we scrape until the next "h1" or a line starting with a link which is likely a build status badge for an architecture-namespace)
  74. if (length($trimmedText) > $lengthLimit) {
  75. # ... if that doesn't do the trick, then do our older naïve description trimming
  76. $trimmedText = $genericNote . substr $proposedText, 0, ($lengthLimit - length($genericNote));
  77. }
  78. $proposedText = $trimmedText;
  79. }
  80. return $currentText if $currentText eq $proposedText;
  81. my @proposedFileBits = fileparse($proposedFile, qr!\.[^.]*!);
  82. my $file = File::Temp->new(SUFFIX => '-' . basename($proposedFileBits[1]) . '-current' . $proposedFileBits[2]);
  83. my $filename = $file->filename;
  84. spurt encode('UTF-8', $currentText . "\n"), $filename;
  85. my $tempProposedFile = File::Temp->new(SUFFIX => '-' . basename($proposedFileBits[1]) . '-proposed' . $proposedFileBits[2]);
  86. my $tempProposedFilename = $tempProposedFile->filename;
  87. spurt encode('UTF-8', $proposedText . "\n"), $tempProposedFilename;
  88. system(qw(git --no-pager diff --no-index), $filename, $tempProposedFilename);
  89. my $reply;
  90. if ($batchmode) {
  91. $reply = 'yes';
  92. }
  93. else {
  94. $reply = $term->get_reply(
  95. prompt => 'Apply changes?',
  96. choices => [ qw( yes vimdiff no quit ) ],
  97. default => 'yes',
  98. );
  99. }
  100. if ($reply eq 'quit') {
  101. say 'quitting, as requested';
  102. exit;
  103. }
  104. if ($reply eq 'yes') {
  105. return $proposedText;
  106. }
  107. if ($reply eq 'vimdiff') {
  108. system('vimdiff', $tempProposedFilename, $filename) == 0 or die "vimdiff on $filename and $proposedFile failed";
  109. return trim(decode('UTF-8', slurp($filename)));
  110. }
  111. return $currentText;
  112. }
  113. while (my $repo = shift) { # 'library/hylang', 'tianon/perl', etc
  114. $repo =~ s!^/+|/+$!!; # trim extra slashes (from "*/" globbing, for example)
  115. $repo = $namespace . '/' . $repo if $namespace; # ./push.pl --namespace xxx ...
  116. $repo = 'library/' . $repo unless $repo =~ m!/!; # "hylang" -> "library/hylang"
  117. my $repoName = $repo;
  118. $repoName =~ s!^.*/!!; # 'hylang', 'perl', etc
  119. my $repoUrl = 'https://hub.docker.com/v2/repositories/' . $repo . '/';
  120. if ($logos && $repo =~ m{ ^ library/ }x) {
  121. # the "library" org images include a logo which is displayed in the Hub UI
  122. # if we have a logo file, let's update that metadata first
  123. my $repoLogo120 = $repoName . '/logo-120.png';
  124. if (!-f $repoLogo120) {
  125. my $repoLogoPng = $repoName . '/logo.png';
  126. my $repoLogoSvg = $repoName . '/logo.svg';
  127. my $logoToConvert = (
  128. -f $repoLogoPng
  129. ? $repoLogoPng
  130. : $repoLogoSvg
  131. );
  132. if (-f $logoToConvert) {
  133. say 'converting ' . $logoToConvert . ' to ' . $repoLogo120;
  134. system(
  135. qw( convert -background none -density 1200 -strip -resize 120x120> -gravity center -extent 120x120 ),
  136. $logoToConvert,
  137. $repoLogo120,
  138. ) == 0 or die "failed to convert $repoLogoPng into $repoLogo120";
  139. }
  140. }
  141. if (-f $repoLogo120) {
  142. my $proposedLogo = slurp($repoLogo120);
  143. my $currentLogo = $ua->get('https://d1q6f0aelx0por.cloudfront.net/product-logos/' . join('-', split(m{/}, $repo)) . '-logo.png', { 'Cache-Control' => 'no-cache' });
  144. $currentLogo = ($currentLogo->success ? $currentLogo->res->body : undef);
  145. if ($currentLogo && $currentLogo eq $proposedLogo) {
  146. say 'no change to ' . $repoName . ' logo; skipping';
  147. }
  148. else {
  149. say 'putting logo ' . $repoLogo120;
  150. my $logoUrl = $repoUrl . 'logo';
  151. my $logoPut = $ua->put($logoUrl => $authorizationHeader => json => {
  152. 'image_data' => b64_encode($proposedLogo),
  153. 'content_type' => 'image/png',
  154. 'file_ext' => 'png',
  155. });
  156. warn 'warning: put to ' . $logoUrl . ' failed: ' . $logoPut->res->text unless $logoPut->success;
  157. }
  158. }
  159. }
  160. my $repoTx = $ua->get($repoUrl => $authorizationHeader);
  161. warn 'warning: failed to get: ' . $repoUrl . ' (skipping)' and next unless $repoTx->success;
  162. my $repoDetails = $repoTx->res->json;
  163. $repoDetails->{description} //= '';
  164. $repoDetails->{full_description} //= '';
  165. my $hubShort = prompt_for_edit($repoDetails->{description}, $repoName . '/README-short.txt');
  166. my $hubLong = prompt_for_edit($repoDetails->{full_description}, $repoName . '/README.md', $hubLengthLimit);
  167. say 'no change to ' . $repoName . '; skipping' and next if $repoDetails->{description} eq $hubShort and $repoDetails->{full_description} eq $hubLong;
  168. say 'updating ' . $repoName;
  169. my $repoPatch = $ua->patch($repoUrl => $authorizationHeader => json => {
  170. description => $hubShort,
  171. full_description => $hubLong,
  172. });
  173. warn 'patch to ' . $repoUrl . ' failed: ' . $repoPatch->res->text and next unless $repoPatch->success;
  174. }