Skip to content

Commit 844aa51

Browse files
committed
feat(fs): add copy dir
1 parent 9ed9344 commit 844aa51

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

packages/fs/src/dir.lib.ts

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,76 @@ Trying to access a dir file from an absolute paths:
327327
}
328328
}
329329

330+
/**
331+
* Copy the directory and all its contents to a new location.
332+
*
333+
* @param toDir - The destination path for the directory or an existing FsDir instance
334+
* @returns A promise that resolves to the new copied directory
335+
* @throws If the copy operation fails
336+
*
337+
* ```typescript
338+
* import { fsDir } from "@synstack/fs";
339+
*
340+
* const sourceDir = fsDir("./source");
341+
* const copiedDir = await sourceDir.copyTo("./backup/source");
342+
* // Both directories now exist with the same content
343+
* ```
344+
*/
345+
public async copyTo(toDir: FsDir | string): Promise<FsDir> {
346+
const destDir = FsDir.cwd(toDir);
347+
const parentDir = path.dirname(destDir.path);
348+
349+
try {
350+
// Ensure parent directory exists
351+
await fs.mkdir(parentDir, { recursive: true });
352+
// Use native fs.cp with recursive option
353+
await fs.cp(this._path, destDir.path, { recursive: true });
354+
return destDir;
355+
} catch (error) {
356+
throw new Error(
357+
`Failed to copy directory from ${this._path} to ${destDir.path}`,
358+
{
359+
cause: error,
360+
},
361+
);
362+
}
363+
}
364+
365+
/**
366+
* Copy the directory and all its contents to a new location synchronously.
367+
*
368+
* @param toDir - The destination path for the directory or an existing FsDir instance
369+
* @returns The new copied directory
370+
* @throws If the copy operation fails
371+
*
372+
* ```typescript
373+
* import { fsDir } from "@synstack/fs";
374+
*
375+
* const sourceDir = fsDir("./source");
376+
* const copiedDir = sourceDir.copyToSync("./backup/source");
377+
* // Both directories now exist with the same content
378+
* ```
379+
*/
380+
public copyToSync(toDir: FsDir | string): FsDir {
381+
const destDir = FsDir.cwd(toDir);
382+
const parentDir = path.dirname(destDir.path);
383+
384+
try {
385+
// Ensure parent directory exists
386+
fsSync.mkdirSync(parentDir, { recursive: true });
387+
// Use native fsSync.cpSync with recursive option
388+
fsSync.cpSync(this._path, destDir.path, { recursive: true });
389+
return destDir;
390+
} catch (error) {
391+
throw new Error(
392+
`Failed to copy directory from ${this._path} to ${destDir.path}`,
393+
{
394+
cause: error,
395+
},
396+
);
397+
}
398+
}
399+
330400
/**
331401
* Move the directory to a new location.
332402
*

0 commit comments

Comments
 (0)