MqxM
Denoβ€’2y agoβ€’
5 replies
Mqx

walk() include only last directory...

Hey, I'm currently trying to write a replacer for file names, file content and folder names. My goal is to crawl over a certain directory and then replace a certain pattern in file names, file content and folder names. Currently I use the walk() function from the std library. My problem now is that walk() returns every single directory and not just the last one. In other words, walk() does not just give me:

file/to/directory

but:
file
file/to
file/to/directory

What is the best way to filter this?
There may also be a better method...

This is what my current attempt looks like:
import { parseArgs } from 'https://deno.land/std@0.212.0/cli/mod.ts';
import { walkSync } from 'https://deno.land/std@0.212.0/fs/mod.ts';
import { parseString as parseRegExpString } from 'https://raw.githubusercontent.com/TypeScriptPlayground/std/main/src/regexp/mod.ts'

const args = parseArgs<{
  path : string,
  pattern : string,
  replacer : string
}>(Deno.args);

if (!args.path || !args.pattern || !args.replacer) {
  console.log('Missing arguments');
  Deno.exit();
}

const pattern = parseRegExpString(args.pattern);

const pathsToUpdate: Array<{ oldPath: string, newPath: string, isFile: boolean }> = [];

Deno.chdir(args.path);
for (const entry of walkSync('.')) {
  const path = entry.path;
  const pathReplaced = path.replace(pattern, args.replacer);

  if (path !== pathReplaced) {
    pathsToUpdate.push({ oldPath: path, newPath: pathReplaced, isFile: entry.isFile });
  }
}

for (const { oldPath, newPath, isFile } of pathsToUpdate) {
  if (isFile) {
    const content = Deno.readTextFileSync(oldPath);
    const contentReplaced = content.replace(pattern, args.replacer);
    Deno.writeTextFileSync(newPath, contentReplaced);
  } else {
    Deno.renameSync(oldPath, newPath); //<- Error: /path/{{pattern}}/{{pattern}}
  }
  console.log(`Updated: ${oldPath} -> ${newPath}`);
}
Was this page helpful?