Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prepending / appending to file (API bikeshedding) #5

Open
boneskull opened this issue Sep 13, 2019 · 1 comment
Open

prepending / appending to file (API bikeshedding) #5

boneskull opened this issue Sep 13, 2019 · 1 comment

Comments

@boneskull
Copy link
Contributor

I'm using replace-in-files-cli (specifically, the programmatic API) to prepend a banner to a bunch of files.

There are myriad packages to do this sort of thing, but they either a) expect the data to be in package.json, b) are plugins for a task runner like grunt, c) unmaintained, or d) hopelessly broken and overengineered. If you have written a standalone tool to do this, please let me know!

This is what "prepend to file" looks like:

const replace = require('replace-in-files-cli/api');

// let's pretend top-level await works
await replace('/path/to/file', {
  find: [/^/], // <--------------------------
  replacement: '/* my awesome banner */'
});

Whereas "append to file" looks like this:

const replace = require('replace-in-files-cli/api');

// let's pretend top-level await works
await replace('/path/to/file', {
  find: [/$/g], // <------------------------
  replacement: '/* my awesome banner */'
});

This isn't quite obvious. I had to play around with regexes to arrive at "append", which works opposite of how I'd expect--I'd expect a banner after every line (which can be accomplished with /$/gm). Anyway.

  • I'm thinking supporting append and prepend flags would be more user-friendly.
  • But since it's not really a "replace" operation, maybe it's out-of-scope for this module?
  • Providing sugar functions like append() or prepend() might be OK, except that a user may want to append/prepend and find/replace in a single operation--find accepts an array, after all.
@sindresorhus
Copy link
Owner

I didn't put much effort into the API, so it could definitely be improved.

How about adding a transform option that gives you the whole file and let you do whatever you want?

await replace('/path/to/file', {
  transform: (data, filePath) => `/* my awesome banner */\n${data}`
});

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

No branches or pull requests

2 participants