GenerateAppTreeCommand.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace UCore\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\File;
  5. /**
  6. * 生成 app 目录的文件树并保存到 app/tree.md
  7. */
  8. class GenerateAppTreeCommand extends Command
  9. {
  10. /**
  11. * 命令的名称和签名。
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'ucore:generate-apptree';
  16. /**
  17. * 命令的描述。
  18. *
  19. * @var string
  20. */
  21. protected $description = '生成 app 目录的文件树并保存到 app/tree.md';
  22. /**
  23. * 执行控制台命令。
  24. *
  25. * @return int
  26. */
  27. public function handle()
  28. {
  29. $appPath = base_path('app');
  30. $outputFile = base_path('app/tree.md');
  31. $tree = $this->generateDirectoryTree($appPath);
  32. File::put($outputFile, $tree);
  33. $this->info('File tree generated successfully at app/tree.md');
  34. return Command::SUCCESS;
  35. }
  36. /**
  37. * 生成目录树结构为字符串
  38. *
  39. * @param string $directory 目录路径
  40. * @param string $prefix 前缀,用于格式化输出
  41. * @return string 返回目录树的字符串表示
  42. */
  43. private function generateDirectoryTree(string $directory, string $prefix = ''): string
  44. {
  45. $tree = '';
  46. $files = scandir($directory);
  47. foreach ($files as $file) {
  48. if ($file === '.' || $file === '..') {
  49. continue;
  50. }
  51. $filePath = $directory . DIRECTORY_SEPARATOR . $file;
  52. $tree .= $prefix . $file . "\n";
  53. if (is_dir($filePath)) {
  54. $tree .= $this->generateDirectoryTree($filePath, $prefix . ' ');
  55. }
  56. }
  57. return $tree;
  58. }
  59. }