@@ -2,6 +2,26 @@ import { promises as fs } from 'fs';
2
2
import * as path from 'path' ;
3
3
import { detectRouterType , ROOT_PAGE_COPY_NAME , ROOT_PATH_IDENTIFIERS } from './helpers' ;
4
4
5
+ async function getUniqueDir ( basePath : string , dirName : string ) : Promise < string > {
6
+ let uniquePath = dirName ;
7
+ let counter = 1 ;
8
+
9
+ const baseName = dirName . replace ( / - c o p y ( - \d + ) ? $ / , '' ) ;
10
+
11
+ while ( true ) {
12
+ try {
13
+ await fs . access ( path . join ( basePath , uniquePath ) ) ;
14
+ uniquePath = `${ baseName } -copy-${ counter } ` ;
15
+ counter ++ ;
16
+ } catch ( err : any ) {
17
+ if ( err . code === 'ENOENT' ) {
18
+ return uniquePath ;
19
+ }
20
+ throw err ;
21
+ }
22
+ }
23
+ }
24
+
5
25
export async function duplicateNextJsPage (
6
26
projectRoot : string ,
7
27
sourcePath : string ,
@@ -17,7 +37,7 @@ export async function duplicateNextJsPage(
17
37
18
38
if ( isRootPath ) {
19
39
const sourcePageFile = path . join ( routerConfig . basePath , 'page.tsx' ) ;
20
- const targetDir = path . join ( routerConfig . basePath , ROOT_PAGE_COPY_NAME ) ;
40
+ const targetDir = await getUniqueDir ( routerConfig . basePath , ROOT_PAGE_COPY_NAME ) ;
21
41
const targetPageFile = path . join ( targetDir , 'page.tsx' ) ;
22
42
23
43
// Check if target already exists
@@ -36,8 +56,9 @@ export async function duplicateNextJsPage(
36
56
}
37
57
38
58
// Handle non-root pages
59
+
39
60
const normalizedSourcePath = sourcePath ;
40
- const normalizedTargetPath = targetPath . endsWith ( '-copy' ) ? targetPath : ` ${ targetPath } -copy` ;
61
+ const normalizedTargetPath = await getUniqueDir ( routerConfig . basePath , targetPath ) ;
41
62
42
63
const sourceFull = path . join ( routerConfig . basePath , normalizedSourcePath ) ;
43
64
const targetFull = path . join ( routerConfig . basePath , normalizedTargetPath ) ;
0 commit comments