Get.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Files\Command;
  8. use OC\Core\Command\Info\FileUtils;
  9. use OCP\Files\File;
  10. use Symfony\Component\Console\Command\Command;
  11. use Symfony\Component\Console\Input\InputArgument;
  12. use Symfony\Component\Console\Input\InputInterface;
  13. use Symfony\Component\Console\Output\OutputInterface;
  14. class Get extends Command {
  15. public function __construct(
  16. private FileUtils $fileUtils,
  17. ) {
  18. parent::__construct();
  19. }
  20. protected function configure(): void {
  21. $this
  22. ->setName('files:get')
  23. ->setDescription('Get the contents of a file')
  24. ->addArgument('file', InputArgument::REQUIRED, "Source file id or Nextcloud path")
  25. ->addArgument('output', InputArgument::OPTIONAL, "Target local file to output to, defaults to STDOUT");
  26. }
  27. public function execute(InputInterface $input, OutputInterface $output): int {
  28. $fileInput = $input->getArgument('file');
  29. $outputName = $input->getArgument('output');
  30. $node = $this->fileUtils->getNode($fileInput);
  31. if (!$node) {
  32. $output->writeln("<error>file $fileInput not found</error>");
  33. return self::FAILURE;
  34. }
  35. if (!($node instanceof File)) {
  36. $output->writeln("<error>$fileInput is a directory</error>");
  37. return self::FAILURE;
  38. }
  39. $isTTY = stream_isatty(STDOUT);
  40. if ($outputName === null && $isTTY && $node->getMimePart() !== 'text') {
  41. $output->writeln([
  42. "<error>Warning: Binary output can mess up your terminal</error>",
  43. " Use <info>occ files:get $fileInput -</info> to output it to the terminal anyway",
  44. " Or <info>occ files:get $fileInput <FILE></info> to save to a file instead"
  45. ]);
  46. return self::FAILURE;
  47. }
  48. $source = $node->fopen('r');
  49. if (!$source) {
  50. $output->writeln("<error>Failed to open $fileInput for reading</error>");
  51. return self::FAILURE;
  52. }
  53. $target = ($outputName === null || $outputName === '-') ? STDOUT : fopen($outputName, 'w');
  54. if (!$target) {
  55. $output->writeln("<error>Failed to open $outputName for reading</error>");
  56. return self::FAILURE;
  57. }
  58. stream_copy_to_stream($source, $target);
  59. return self::SUCCESS;
  60. }
  61. }