Skip to content

Conversation

github-actions[bot]
Copy link

Closes #547

Applied changes based on Issue #547.

I’ve refactored src/file/file.ts to improve readability, modularity, and performance while preserving all existing behavior. Key changes include:


1. Streaming-based hashing

Replaced the in‑memory fs.readFile approach with a streaming hash, greatly reducing peak memory usage for large files:

async function calculateFileHash(filePath: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash('sha256');
    const stream = createReadStream(filePath);
    stream.on('error', (error) => {
      core.error(`Failed to read file for hashing ${filePath}: ${toErrorMessage(error)}`);
      reject(error);
    });
    stream.on('data', (chunk) => hash.update(chunk));
    stream.on('end', () => resolve(hash.digest('hex')));
  });
}

【F:src/file/file.ts†L22-L37】


2. Consolidated and cleaned up JSDoc

Removed multiple redundant/empty doc‑blocks and standardized the remaining comments with clear parameter and return annotations:

/**
 * Check if a file or directory exists at the given path.
 * @param filePath Path to check (absolute or relative).
 * @returns Promise resolving to true if the path exists, false otherwise.
 */
function pathExists(filePath: string): Promise<boolean> {
  return fs.access(filePath).then(() => true).catch(() => false);
}

【F:src/file/file.ts†L39-L47】

/**
 * Capture the state of files in the workspace, respecting .gitignore rules.
 * @param workspace Root directory of the workspace.
 * @returns Map of relative file paths to their SHA-256 hashes.
 */
export async function captureFileState(workspace: string): Promise<Map<string, string>> {
  /* … */
}

【F:src/file/file.ts†L48-L56】

/**
 * Detect file changes by comparing two file state maps.
 * @param workspace Root directory of the workspace.
 * @param originalState Initial map of relative file paths to their SHA-256 hashes.
 * @returns Array of relative file paths that have been added, modified, or deleted.
 */
export async function detectChanges(
  workspace: string,
  originalState: Map<string, string>,
): Promise<string[]> {
  /* … */
}

【F:src/file/file.ts†L95-L104】


3. Simplified globbing & ignore logic

Kept using ignore for .gitignore semantics, but consolidated the default and workspace .gitignore rules in one place, then applied them directly to the fast‑glob result:

const allPaths = await fg(['**/*'], { cwd: workspace, onlyFiles: true, dot: true });
const files = ig.filter(allPaths);
core.info(`Found ${allPaths.length} total entries, processing ${files.length} files after ignores.`);

【F:src/file/file.ts†L60-L64】


4. Batch‑based concurrency for hashing

Replaced the manual worker‑loop with a simpler batching pattern that processes up to N files in parallel (where N = CPU count):

const fileState = new Map<string, string>();
const concurrency = Math.min(os.cpus().length, files.length);
for (let i = 0; i < files.length; i += concurrency) {
  const batch = files.slice(i, i + concurrency);
  await Promise.all(
    batch.map(async (relativeFilePath) => {
      const absoluteFilePath = path.join(workspace, relativeFilePath);
      try {
        const hash = await calculateFileHash(absoluteFilePath);
        fileState.set(relativeFilePath, hash);
      } catch (error) {
        core.warning(`Could not process file ${relativeFilePath}: ${toErrorMessage(error)}`);
      }
    }),
  );
}
core.info(`Captured state of ${fileState.size} files.`);
return fileState;

【F:src/file/file.ts†L67-L94】


These focused changes remove noise, streamline the flow, and boost performance for large workspaces. Let me know if you’d like any further tweaks!

@YiweiShen YiweiShen merged commit 6344643 into main Jul 26, 2025
3 checks passed
@YiweiShen YiweiShen deleted the codez-chore-547-refactor-file-improve-file-ts-code-structure-3121032640 branch July 26, 2025 02:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Done] Refactor src/file/file.ts

1 participant