1
0

Put.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 OCP\Files\Folder;
  11. use OCP\Files\IRootFolder;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. class Put extends Command {
  17. public function __construct(
  18. private FileUtils $fileUtils,
  19. private IRootFolder $rootFolder,
  20. ) {
  21. parent::__construct();
  22. }
  23. protected function configure(): void {
  24. $this
  25. ->setName('files:put')
  26. ->setDescription('Write contents of a file')
  27. ->addArgument('input', InputArgument::REQUIRED, 'Source local path, use - to read from STDIN')
  28. ->addArgument('file', InputArgument::REQUIRED, 'Target Nextcloud file path to write to or fileid of existing file');
  29. }
  30. public function execute(InputInterface $input, OutputInterface $output): int {
  31. $fileOutput = $input->getArgument('file');
  32. $inputName = $input->getArgument('input');
  33. $node = $this->fileUtils->getNode($fileOutput);
  34. if ($node instanceof Folder) {
  35. $output->writeln("<error>$fileOutput is a folder</error>");
  36. return self::FAILURE;
  37. }
  38. if (!$node and is_numeric($fileOutput)) {
  39. $output->writeln("<error>$fileOutput not found</error>");
  40. return self::FAILURE;
  41. }
  42. $source = ($inputName === null || $inputName === '-') ? STDIN : fopen($inputName, 'r');
  43. if (!$source) {
  44. $output->writeln("<error>Failed to open $inputName</error>");
  45. return self::FAILURE;
  46. }
  47. if ($node instanceof File) {
  48. $target = $node->fopen('w');
  49. if (!$target) {
  50. $output->writeln("<error>Failed to open $fileOutput</error>");
  51. return self::FAILURE;
  52. }
  53. stream_copy_to_stream($source, $target);
  54. } else {
  55. $this->rootFolder->newFile($fileOutput, $source);
  56. }
  57. return self::SUCCESS;
  58. }
  59. }