All files / src file-crawler.ts

70.68% Statements 41/58
52.63% Branches 10/19
50% Functions 4/8
70.17% Lines 40/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 1692x 2x 2x           2x 14x 14x             14x 4x 4x   1x 1x                                                                                                                                   4x               4x 4x     4x   4x 8x 8x   8x 8x     8x 11x   11x 7x             7x 7x 7x   4x         8x 8x           8x       4x   4x               19x 11x   6x 3x     3x       11x 15x          
import * as core from '@actions/core'
import * as fs from 'fs'
import * as path from 'path'
import { TreeNode } from './types'
 
/**
 * File crawler class for finding HTML files and building tree structure
 */
export class FileCrawler {
  private htmlFiles: string[] = []
  private filterRegex: RegExp = /.*/  // Default matches everything
  
  /**
   * Creates a new FileCrawler instance
   * @param fileFilter Optional regex pattern to filter files
   */
  constructor(fileFilter?: string) {
    if (fileFilter && fileFilter.trim() !== '') {
      try {
        this.filterRegex = new RegExp(fileFilter)
      } catch (error) {
        core.warning(`Invalid regex pattern "${fileFilter}": ${error}`)
        this.filterRegex = /.*/ // If regex is invalid, include all files
      }
    }
  }
  
  /**
   * Crawls a directory recursively to find HTML files
   * @param dirPath The directory path to crawl
   * @returns Array of HTML file paths
   */
  async crawlDirectory(dirPath: string): Promise<string[]> {
    this.htmlFiles = []
    await this.crawlRecursive(dirPath)
    return this.htmlFiles
  }
 
  /**
   * Recursively crawls directories to find HTML files
   * @param currentPath Current directory path being crawled
   */
  private async crawlRecursive(currentPath: string): Promise<void> {
    try {
      const stats = await fs.promises.stat(currentPath)
      
      if (stats.isDirectory()) {
        const entries = await fs.promises.readdir(currentPath)
        
        for (const entry of entries) {
          const fullPath = path.join(currentPath, entry)
          await this.crawlRecursive(fullPath)
        }
      } else Iif (stats.isFile() && this.isHtmlFile(currentPath) && this.matchesFilter(currentPath)) {
        this.htmlFiles.push(currentPath)
      }
    } catch (error) {
      core.warning(`Error accessing path ${currentPath}: ${error}`)
    }
  }
 
  /**
   * Checks if a file is an HTML file based on its extension
   * @param filePath The file path to check
   * @returns True if the file is an HTML file
   */
  private isHtmlFile(filePath: string): boolean {
    const ext = path.extname(filePath).toLowerCase()
    return ext === '.html' || ext === '.htm'
  }
 
  /**
   * Checks if a file matches the compiled regex filter
   * @param filePath The file path to check
   * @returns True if the file matches the filter
   */
  private matchesFilter(filePath: string): boolean {
    const fileName = path.basename(filePath)
    return this.filterRegex.test(fileName)
  }
 
  /**
   * Builds a tree structure from the found HTML files
   * @param htmlFiles Array of HTML file paths
   * @param rootPath The root directory path
   * @returns Tree structure representing the HTML files
   */
  buildTreeStructure(htmlFiles: string[], rootPath: string): TreeNode {
    const root: TreeNode = {
      name: path.basename(rootPath) || rootPath,
      path: rootPath,
      type: 'directory',
      children: []
    }
 
    // Create a map to store directory nodes
    const nodeMap = new Map<string, TreeNode>()
    nodeMap.set(rootPath, root)
 
    // Sort files to ensure consistent ordering
    const sortedFiles = htmlFiles.sort()
 
    for (const filePath of sortedFiles) {
      const relativePath = path.relative(rootPath, filePath)
      const pathParts = relativePath.split(path.sep)
      
      let currentPath = rootPath
      let currentNode = root
 
      // Create directory nodes as needed
      for (let i = 0; i < pathParts.length - 1; i++) {
        currentPath = path.join(currentPath, pathParts[i])
        
        if (!nodeMap.has(currentPath)) {
          const dirNode: TreeNode = {
            name: pathParts[i],
            path: currentPath,
            type: 'directory',
            children: []
          }
          
          nodeMap.set(currentPath, dirNode)
          currentNode.children!.push(dirNode)
          currentNode = dirNode
        } else {
          currentNode = nodeMap.get(currentPath)!
        }
      }
 
      // Add the HTML file node
      const fileName = pathParts[pathParts.length - 1]
      const fileNode: TreeNode = {
        name: fileName,
        path: filePath,
        type: 'file'
      }
      
      currentNode.children!.push(fileNode)
    }
 
    // Sort children in each directory (directories first, then files)
    this.sortTreeNodes(root)
 
    return root
  }
 
  /**
   * Recursively sorts tree nodes (directories first, then files, both alphabetically)
   * @param node The tree node to sort
   */
  private sortTreeNodes(node: TreeNode): void {
    if (node.children) {
      node.children.sort((a, b) => {
        // Directories come before files
        if (a.type !== b.type) {
          return a.type === 'directory' ? -1 : 1
        }
        // Within the same type, sort alphabetically
        return a.name.localeCompare(b.name)
      })
 
      // Recursively sort children
      for (const child of node.children) {
        this.sortTreeNodes(child)
      }
    }
  }
}