push.pl 8.1 KB

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