sindresorhus / cpy

Copy files
MIT License
425 stars 63 forks source link

Support flat mode for copying a single file #100

Closed dpilafian closed 2 years ago

dpilafian commented 2 years ago

The flat flag appears to be ignored when attempting to copy a single file.

For example, the command:

npx cpy src/data.txt dist --flat=true

creates the file:

dist/src/data.txt

I would expect the --flat=true flag setting to result in creating the file:

dist/data.txt

Steps to repeat:

  1. npm init --yes
  2. npm install cpy-cli
  3. mkdir src
  4. touch src/data.txt
  5. npx cpy src/data.txt dist --flat=true
  6. find dist -type f
copy-test
dpilafian commented 2 years ago

Test case:

cpy/test.js

test('flatten single file', async t => {
    fs.mkdirSync(t.context.tmp);
    fs.mkdirSync(path.join(t.context.tmp, 'source'));
    fs.writeFileSync(
        path.join(t.context.tmp, 'source/bar.js'),
        'console.log("bar");',
    );

    await cpy('source/bar.js', 'destination', {
        cwd: t.context.tmp,
        flat: true,
    });

    t.is(
        read(t.context.tmp, 'source/bar.js'),
        read(t.context.tmp, 'destination/bar.js'),
    );
});

One possible solution is to handle the use case by adding the following code just before the last line in preprocessDestinationPath():

cpy/index.js

    if (!entry.pattern.isDirectory && options.flat) {
        return path.join(options.cwd, destination, path.basename(entry.pattern.originalPath));
    }

With the above change, the new test case and all the previous test cases pass:

flatten-single-file

If this change is correct and is the desired approach, I'd be happy to submit it as a pull request.

sindresorhus commented 2 years ago

PR welcome :)