All files / src/workspace workspace.service.ts

99.36% Statements 156/157
91.66% Branches 33/36
100% Functions 29/29
100% Lines 150/150

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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 3157x 7x         7x 7x 7x 7x 7x       7x 22x 22x   22x     22x 22x 22x     22x       7x       13x 13x 13x 13x 13x 2x 2x 2x 2x   11x           7x 13x   13x       13x   13x 13x 13x         11x     2x 1x 1x   1x       1x             4x 4x 1x       3x   3x 1x 1x       2x       7x       4x 4x   4x 4x 4x 2x   3x       4x             7x 20x 20x         7x 7x     13x     13x 13x   12x 12x 23x 35x 29x   35x       12x       18x   29x 29x   29x 23x   6x               12x 12x 12x 12x 6x       12x   12x 12x 12x   12x     12x   1x 1x         7x 17x 17x 17x       7x           6x     6x   6x     6x 6x 6x 12x 24x 6x 6x   18x       6x 6x 6x 6x 6x       6x     6x 6x 4x 12x 4x   2x 3x 1x 1x   6x 6x 6x 6x       6x     20x 6x 6x 6x 6x 6x       6x     6x 20x     6x 10x 10x   6x 6x 6x 6x   6x   6x       6x   6x       6x                 7x 1x   1x      
import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import { ContextGenerationService } from '../context-generation/context-generation.service';
import {
  SearchWorkspaceResponseDto,
  SearchResultItemDto,
} from './dto/search-workspace.dto';
import * as fs from 'fs/promises';
import * as path from 'path';
import { fuzzySearch, Trace } from '../utils';
import { exec, ExecOptions } from 'child_process';
import { trace } from '@opentelemetry/api';
import { FileTreeResponseDto, TreeNodeDto } from './dto/file-tree.dto';
 
@Injectable()
export class WorkspaceService {
  private readonly logger = new Logger(WorkspaceService.name);
  private projectRoot: string =
    process.env.REPOBURG_PROJECT_PATH || process.cwd();
  private tracer = trace.getTracer('repoburg-backend');
 
  // Cache for file tree
  private fileTreeCache: FileTreeResponseDto | null = null;
  private fileTreeCacheTimestamp: number | null = null;
  private readonly CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
 
  constructor(
    private readonly contextGenerationService: ContextGenerationService,
  ) {}
 
  @Trace()
  private execAsync(
    command: string,
    options: ExecOptions,
  ): Promise<{ stdout: string; stderr: string }> {
    return new Promise((resolve, reject) => {
      exec(command, options, (error, stdout, stderr) => {
        const stdoutStr = stdout.toString();
        const stderrStr = stderr.toString();
        if (error) {
          error['stdout'] = stdoutStr;
          error['stderr'] = stderrStr;
          reject(error);
          return;
        }
        resolve({ stdout: stdoutStr, stderr: stderrStr });
      });
    });
  }
 
  @Trace()
  private async getFilesFromRg(): Promise<string[]> {
    const rgCommand = await this.contextGenerationService.getCommandPath('rg');
    const ignoreFlags =
      await this.contextGenerationService.getRipGrepIgnoreFlags();
    // --files: lists all files, respecting ignore rules
    // --hidden: ensures hidden files (dotfiles) are included, unless ignored
    // ignoreFlags: uses .rgignore if present, otherwise .gitignore by default
    const command = `${rgCommand} ${ignoreFlags} --files . --hidden --glob '!.git'`;
 
    try {
      this.logger.log(`Executing for file list: ${command}`);
      const { stdout } = await this.execAsync(command, {
        cwd: this.projectRoot,
        maxBuffer: 256 * 1024 * 1024, // 256MB
        timeout: 10000, // 10s
      });
      return stdout.trim().split('\n').filter(Boolean);
    } catch (error) {
      // rg exits with code 1 if no files are found with --files, which is not an error for us.
      if (error.code === 1 && error.stdout === '' && error.stderr === '') {
        this.logger.log('rg --files returned no files.');
        return [];
      }
      this.logger.error(
        `Failed to get file list from rg: ${error.message}`,
        error.stack,
      );
      throw new Error(
        `Could not retrieve file list from RipGrep. Is 'rg' installed and in your PATH?`,
      );
    }
  }
 
  private resolveAndValidatePath(unsafePath: string): string {
    const normalizedPath = path.normalize(unsafePath);
    if (path.isAbsolute(normalizedPath)) {
      throw new BadRequestException(
        `Absolute paths are not allowed: ${unsafePath}`,
      );
    }
    const resolvedPath = path.resolve(this.projectRoot, normalizedPath);
 
    if (!resolvedPath.startsWith(this.projectRoot)) {
      this.logger.warn(`Path traversal attempt detected: ${unsafePath}`);
      throw new BadRequestException(
        `Path traversal is not allowed. Access denied for path: ${unsafePath}`,
      );
    }
    return resolvedPath;
  }
 
  @Trace()
  async validatePaths(paths: {
    files?: string[];
    folders?: string[];
  }): Promise<{ valid: boolean; invalidPaths: string[] }> {
    const invalidPaths: string[] = [];
    const allPaths = [...(paths.files || []), ...(paths.folders || [])];
 
    for (const p of allPaths) {
      try {
        const safePath = this.resolveAndValidatePath(p);
        await fs.access(safePath);
      } catch (e) {
        invalidPaths.push(p);
      }
    }
 
    return {
      valid: invalidPaths.length === 0,
      invalidPaths,
    };
  }
 
  @Trace()
  async getFileTree(): Promise<FileTreeResponseDto> {
    const now = Date.now();
    if (
      this.fileTreeCache &&
      this.fileTreeCacheTimestamp &&
      now - this.fileTreeCacheTimestamp < this.CACHE_TTL_MS
    ) {
      this.logger.log('Returning file tree from cache.');
      return this.fileTreeCache;
    }
 
    this.logger.log(
      `Building file tree from filesystem with rg: ${this.projectRoot}`,
    );
    try {
      const files = await this.getFilesFromRg();
 
      const fileTree: { [key: string]: any } = {};
      files.forEach((filePath) => {
        filePath.split(path.sep).reduce((level, part) => {
          if (!level[part]) {
            level[part] = {};
          }
          return level[part];
        }, fileTree);
      });
 
      const toArboristData = (
        subtree: { [key: string]: any },
        pathPrefix = '',
      ): TreeNodeDto[] => {
        return Object.entries(subtree)
          .map(([name, children]) => {
            const id = pathPrefix ? `${pathPrefix}/${name}` : name;
            const isFile = Object.keys(children).length === 0;
 
            if (isFile) {
              return { id, name };
            } else {
              return {
                id,
                name,
                children: toArboristData(children, id),
              };
            }
          })
          .sort((a, b) => {
            const isAFolder = !!a.children;
            const isBFolder = !!b.children;
            Iif (isAFolder && !isBFolder) return -1;
            if (!isAFolder && isBFolder) return 1;
            return a.name.localeCompare(b.name);
          });
      };
 
      const treeData = toArboristData(fileTree);
 
      const response: FileTreeResponseDto = { tree: treeData };
      this.fileTreeCache = response;
      this.fileTreeCacheTimestamp = now;
 
      this.logger.log(
        `Built and cached file tree with ${files.length} total entries.`,
      );
      return response;
    } catch (error) {
      this.logger.error('Failed to get file tree:', error);
      throw error;
    }
  }
 
  @Trace()
  async invalidateFileTreeCache(): Promise<void> {
    this.logger.log('Invalidating file tree cache.');
    this.fileTreeCache = null;
    this.fileTreeCacheTimestamp = null;
  }
 
  @Trace()
  async search(
    query: string,
    type: 'files' | 'folders' | 'all',
    page: number,
    limit: number,
  ): Promise<SearchWorkspaceResponseDto> {
    this.logger.log(`Searching for "${query}" (type: ${type})`);
 
    // We get the cached tree, or build it if not present.
    const { tree } = await this.getFileTree();
 
    const { files, folders } = this.tracer.startActiveSpan(
      'workspace.search#flattenTree',
      (span) => {
        const filesList: string[] = [];
        const foldersList: string[] = [];
        const flatten = (nodes: TreeNodeDto[]) => {
          for (const node of nodes) {
            if (node.children) {
              foldersList.push(node.id);
              flatten(node.children);
            } else {
              filesList.push(node.id);
            }
          }
        };
        flatten(tree);
        span.setAttribute('files.count', filesList.length);
        span.setAttribute('folders.count', foldersList.length);
        span.end();
        return { files: filesList, folders: foldersList };
      },
    );
 
    const searchPool = this.tracer.startActiveSpan(
      'workspace.search#prepareSearchPool',
      (span) => {
        let pool: { path: string; type: 'file' | 'folder' }[] = [];
        if (type === 'all') {
          pool = [
            ...files.map((p) => ({ path: p, type: 'file' as const })),
            ...folders.map((p) => ({ path: p, type: 'folder' as const })),
          ];
        } else if (type === 'files') {
          pool = files.map((p) => ({ path: p, type: 'file' as const }));
        } else if (type === 'folders') {
          pool = folders.map((p) => ({ path: p, type: 'folder' as const }));
        }
        span.setAttribute('pool.size', pool.length);
        span.setAttribute('search.type', type);
        span.end();
        return pool;
      },
    );
 
    const matchedPaths = this.tracer.startActiveSpan(
      'workspace.search#fuzzySearch',
      (span) => {
        const searchPoolStrings = searchPool.map((item) => item.path);
        const results = fuzzySearch(query, searchPoolStrings);
        span.setAttribute('search.query', query);
        span.setAttribute('results.count', results.length);
        span.end();
        return results;
      },
    );
 
    const { paginatedResults, total } = this.tracer.startActiveSpan(
      'workspace.search#filterAndPaginate',
      (span) => {
        const searchPoolMap = new Map<string, SearchResultItemDto>(
          searchPool.map((item) => [item.path, item]),
        );
 
        const results: SearchResultItemDto[] = matchedPaths
          .map((path) => searchPoolMap.get(path))
          .filter((item): item is SearchResultItemDto => item !== undefined);
 
        const totalResults = results.length;
        const startIndex = (page - 1) * limit;
        const endIndex = page * limit;
        const paginated = results.slice(startIndex, endIndex);
 
        span.end();
 
        return { paginatedResults: paginated, total: totalResults };
      },
    );
 
    const endIndex = page * limit;
 
    this.logger.log(
      `Search for "${query}" (type: ${type}) found ${total} total results. Returning page ${page} with ${paginatedResults.length} items.`,
    );
 
    return {
      results: paginatedResults,
      total,
      page,
      hasMore: endIndex < total,
    };
  }
 
  @Trace()
  async getFileContent(filePath: string): Promise<string> {
    this.logger.log(`Reading content for file: ${filePath}`);
    // Use the fetchFileContent method from ContextGenerationService to ensure path safety and get raw content.
    return this.contextGenerationService.fetchFileContent(filePath);
  }
}