@@ -154,6 +154,58 @@ function searchFile (dir, fileName, callback) {
154
154
} ) ;
155
155
}
156
156
157
+ // uses the folderScanSync to grab absolute paths of all files and folders, deleting folders (deepest first) and moving files to the target
158
+ // requires an absolute path for sourcePath and targetFolderPath.
159
+ function flattenFolderStructureSync ( sourcePath , targetFolderPath , callback ) {
160
+ return Q . resolve ( ) . then ( function ( ) {
161
+ var output = folderScanSync ( sourcePath ) ;
162
+
163
+ // move/copy files
164
+ output . files . forEach ( file => {
165
+ fs . renameSync ( file , path . resolve ( targetFolderPath , path . parse ( file ) . base ) , ( err ) => {
166
+ return callback ( err ) ;
167
+ } ) ;
168
+ } ) ;
169
+
170
+ // remove directories
171
+ output . folders . forEach ( folder => {
172
+ fs . rmdirSync ( folder , ( err ) => {
173
+ callback ( err ) ;
174
+ } ) ;
175
+ } ) ;
176
+
177
+ return Q . resolve ( ) ;
178
+ } ) . nodeify ( callback ) ;
179
+ }
180
+
181
+ // queues new entries into the unexplored paths, and iterates through it, execution stops when all reaches end.
182
+ // output is an object: { files: [], folders: [] }, the order of the files and object is reversed of traversal order
183
+ function folderScanSync ( directory ) {
184
+ const unexplored = [ directory ] ;
185
+ const folders = [ ] ;
186
+ const files = [ ] ;
187
+
188
+ for ( let i = 0 ; i < unexplored . length ; i ++ ) {
189
+ const currentPath = unexplored [ i ] ;
190
+ fs . readdirSync ( currentPath )
191
+ . forEach ( function ( fileEntry ) {
192
+ var fileEntryPath = path . join ( currentPath , fileEntry ) ;
193
+
194
+ if ( fs . statSync ( fileEntryPath ) . isDirectory ( ) ) {
195
+ unexplored . push ( fileEntryPath ) ;
196
+ folders . push ( fileEntryPath ) ;
197
+ } else {
198
+ files . push ( fileEntryPath ) ;
199
+ }
200
+ } ) ;
201
+ }
202
+
203
+ return {
204
+ folders : folders . reverse ( ) ,
205
+ files : files . reverse ( )
206
+ } ;
207
+ }
208
+
157
209
// Copies the 'source' file to 'target' if it's missing after creating the
158
210
// required directory structure.
159
211
function syncFile ( source , target , callback ) {
@@ -301,5 +353,7 @@ module.exports = {
301
353
createShortcut : createShortcut ,
302
354
replaceFileContent : replaceFileContent ,
303
355
searchFile : searchFile ,
304
- syncFiles : syncFiles
356
+ syncFiles : syncFiles ,
357
+ flattenFolderStructure : flattenFolderStructureSync ,
358
+ folderScanSync : folderScanSync
305
359
} ;
0 commit comments