NYCJUG/2010-04-14/GeneralizeMulticopyExample

From J Wiki
Jump to navigation Jump to search

Example Code: Generalized File Copy

I have some code which has evolved rather messily and would like some suggestions on how to clean it up.

I had a function to copy files from one directory to another that I made more efficient by grouping the file names and using a batch file that handles multiple copies: “mcopyto.bat”. This batch command takes the destination as the first argument followed by all the source files as subsequent arguments, e.g. like this:

mcopyto C:\DestDir file1.txt file2.txt file3.txt

Later, I modified my J function to be an adverb so I can supply an argument other than mcopyto so that I could, i.e. move rather than copy files. The resulting J code looks like this:

NB.* copyFilesTo: copy all files named by >2}.y in dir >0{y to dir >1{y.
copyFilesTo=: 3 : 0
   'mcopyto' copyFilesTo y
:
   fls=. 2}.y [ 'srcd dest'=. 2{.y
NB. npc: # files/copy statement
   npc=. 1>.<.((+/%#)#&>fls)%~255-#'call ',x,' ',dest,' '
   1!:44 srcd [ svod=. 1!:43 ''
   (x mkMCopyTo (npc;dest),<fls) v2f batfl=. 'cpFls.bat'
   1!:44 svod [ ferase batfl [ shell batfl
NB.EG copyFilesTo ((<'C:\J\'),&.>'src';'svdocs'),0{"1 dir 'C:\J\src\*.doc'
NB.  shell&.>((<'cd ',srcd),(<'mcopyto ',dest,' '),&.>([:}.[:;' ',&.>])&.>npc<\fls)
NB.  shell batfl
)

However, this seems unnecessarily messy. Also, the temporary batch file cpFls.bat does not get erased. Any suggestions for cleaning it up? The batch file looks like this:

Rem Echo off
Rem  Multiple COPY TO %1: copy %2, %3, %4, etc.
Rem     * Copyright 1990, Devon H. McCormick * All rights reserved *
:START
If %1/==/ goto SHOWHOW
Set tmpnm=%1
:DO1
If %2/==/ goto BYEBYE
Copy %2 %tmpnm% > nul
Shift
Goto DO1
:SHOWHOW
Echo on
Rem  MCOPY target source1 source2...sourceN
Echo off
Goto BYEBYE
:BYEBYE
Set tmpnm=
Rem Echo on