Posted By

jatkins on 01/16/17


Tagged

code sourcecode source


Versions (?)

Recursive code viewer


 / Published in: PHP
 

Recursively generates a table of contents for all .js, .html, and .css files within a given directory (and within its sub-directories and sub-sub-directories, etc.) and then prints out the source code of each file.

Released into the public domain by Josh Atkins, 2017.

  1. <?php
  2. global $root, $rootBasename, $justTOC;
  3. $root = 'c:\wamp\www';
  4. $rootBasename = basename($root);
  5. $justTOC = isset($_GET['justTOC']) && ($_GET['justTOC'] == 1 || (strtolower($_GET['justTOC']) == 'true'));
  6.  
  7. function getDescendants($parentDir) {
  8. $dirs = glob("$parentDir\\*", GLOB_ONLYDIR);
  9. $output = array();
  10. $filePaths = glob("$parentDir\\*.{js,html,css}", GLOB_BRACE);
  11. $justFilenames = array();
  12. foreach($dirs as $dir) {
  13. $output[$dir] = getDescendants($dir);
  14. }
  15. foreach($filePaths as $filePath) {
  16. $justFilenames[] = $filePath;
  17. }
  18. return array_merge($output, $justFilenames);
  19. }
  20.  
  21. $descendants = getDescendants($root);
  22.  
  23. global $scriptIndex, $paths;
  24. $paths = array();
  25. $GLOBALS['scriptIndex'] = 0;
  26. function renderTOC($nodes) {
  27. if (is_array($nodes)) {
  28. $toc = "<ul>\n";
  29. foreach($nodes as $nodeKey => $node) {
  30. $toc .= "<li>" . (is_string($nodeKey) ? "<b>" . basename($nodeKey) . "</b>" : "") . renderTOC($node) . "</li>\n";
  31. }
  32. $toc .= "</ul>\n";
  33. } else {
  34. $relativePath = '\\' . $GLOBALS['rootBasename'] . substr($nodes, strlen($GLOBALS['root']));
  35. $toc = "<a href=\"" . ($GLOBALS['justTOC'] ? $relativePath : "#script$GLOBALS[scriptIndex]") . "\">" . basename($nodes) . "</a>";
  36. $GLOBALS['paths'][] = array(
  37. 'relative' => substr(str_replace('\\', '/', substr($nodes, strlen($GLOBALS['root']))), 1),
  38. 'absolute' => $nodes
  39. );
  40. $GLOBALS['scriptIndex']++;
  41. }
  42. return $toc;
  43. }
  44. echo renderTOC($descendants) . "<hr>\n";
  45.  
  46. if (!$GLOBALS['justTOC']) {
  47. $fileIndex = 0;
  48. foreach($paths as $path) {
  49. echo "<h2 id=\"script$fileIndex\"><a href=\"$path[relative]\">$path[absolute]</a></h2>\n<pre>".htmlentities(file_get_contents($path['absolute']))."</pre>\n<hr>\n";
  50. $fileIndex++;
  51. }
  52. }
  53. ?>

Report this snippet  

You need to login to post a comment.