adamreisnz / replace-in-file

A simple utility to quickly replace contents in one or more files
580 stars 65 forks source link

Feature: Allow a virtual file system #175

Closed JoshuaKGoldberg closed 9 months ago

JoshuaKGoldberg commented 10 months ago

Hi! I've been using replace-in-file for a while now and really liking it. It's straightforward to use & works well. Thanks! ❤️

One pain point I have, though, is testing out code that calls to replace-in-file. There's no way (that I can find) right now to have replaceInFile() send its results to a callback rather than writing on disk. But some of its logic around capturing froms and passing them to to would be nontrivial to reimplement during tests. https://github.com/JoshuaKGoldberg/create-typescript-app/pull/1078/commits/67a31169ce652825989e4f2dcbe7cfa5a0334eb7 is an example of me extracting some code to somewhat test it.

Proposal: can replaceInFile be given a fs parameter that defaults to Node's fs?

const fileSystem = {
  readFile: vi.fn(),
  writeFile: vi.fn(),
};

replace({
  fileSystem,
  from: '...',
  to: '...',
});

Per https://github.com/search?q=repo%3Aadamreisnz%2Freplace-in-file+fs.+-path%3A*.spec*&type=code those four APIs look like the only ones being used in the async version. For .sync:

const fileSystemSync = {
  readFileSync: vi.fn(),
  writeFileSync: vi.fn(),
};

replace({
  fileSystem,
  from: '...',
  to: '...',
});

I'd be happy to send a PR if you'd accept it!

adamreisnz commented 10 months ago

Hey, that sounds like an interesting solution. So the fileSystem would default to Nodes functions, but would allow you to specify alternatives as well.

Yeah I'd be happy to accept a PR that allows that. I think it should even be fully backwards compatible.

JoshuaKGoldberg commented 9 months ago

Fixed by #177. Thanks!