GnuFindAdapter.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Finder\Adapter;
  11. use Symfony\Component\Finder\Shell\Shell;
  12. use Symfony\Component\Finder\Shell\Command;
  13. use Symfony\Component\Finder\Iterator\SortableIterator;
  14. use Symfony\Component\Finder\Expression\Expression;
  15. /**
  16. * Shell engine implementation using GNU find command.
  17. *
  18. * @author Jean-François Simon <contact@jfsimon.fr>
  19. */
  20. class GnuFindAdapter extends AbstractFindAdapter
  21. {
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function getName()
  26. {
  27. return 'gnu_find';
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. protected function buildFormatSorting(Command $command, $sort)
  33. {
  34. switch ($sort) {
  35. case SortableIterator::SORT_BY_NAME:
  36. $command->ins('sort')->add('| sort');
  37. return;
  38. case SortableIterator::SORT_BY_TYPE:
  39. $format = '%y';
  40. break;
  41. case SortableIterator::SORT_BY_ACCESSED_TIME:
  42. $format = '%A@';
  43. break;
  44. case SortableIterator::SORT_BY_CHANGED_TIME:
  45. $format = '%C@';
  46. break;
  47. case SortableIterator::SORT_BY_MODIFIED_TIME:
  48. $format = '%T@';
  49. break;
  50. default:
  51. throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort));
  52. }
  53. $command
  54. ->get('find')
  55. ->add('-printf')
  56. ->arg($format.' %h/%f\\n')
  57. ->add('| sort | cut')
  58. ->arg('-d ')
  59. ->arg('-f2-')
  60. ;
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. protected function canBeUsed()
  66. {
  67. return $this->shell->getType() === Shell::TYPE_UNIX && parent::canBeUsed();
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. protected function buildFindCommand(Command $command, $dir)
  73. {
  74. return parent::buildFindCommand($command, $dir)->add('-regextype posix-extended');
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. protected function buildContentFiltering(Command $command, array $contains, $not = false)
  80. {
  81. foreach ($contains as $contain) {
  82. $expr = Expression::create($contain);
  83. // todo: avoid forking process for each $pattern by using multiple -e options
  84. $command
  85. ->add('| xargs -I{} -r grep -I')
  86. ->add($expr->isCaseSensitive() ? null : '-i')
  87. ->add($not ? '-L' : '-l')
  88. ->add('-Ee')->arg($expr->renderPattern())
  89. ->add('{}')
  90. ;
  91. }
  92. }
  93. }