Loading...
Searching...
No Matches
mp_dirlist.sas
Go to the documentation of this file.
1/**
2 @file
3 @brief Returns all files and subdirectories within a specified parent
4 @details When used with getattrs=NO, is not OS specific (uses dopen / dread).
5
6 Usage:
7
8 %mp_dirlist(path=/some/location, outds=myTable, maxdepth=MAX)
9
10 %mp_dirlist(outds=cwdfileprops, getattrs=YES)
11
12 %mp_dirlist(fref=MYFREF)
13
14 Entries are classified with the dopen function alone. The previous
15 implementation also used fopen - which blocks when the entry is a named pipe
16 (fifo), so a single fifo in a folder was enough to hang the whole session.
17 With getattrs=NO that hazard is gone; with getattrs=YES entries are opened to
18 read their attributes, so a fifo can still block that mode.
19
20 @note Symlinks are followed. A symlink that points at one of its own parents
21 produces an endless path (a/b/link/b/link/...), so a browse service must
22 always pass a finite <code>maxdepth=</code>.
23
24 @param [in] path= (%sysfunc(pathname(work))) Path for which to return contents.
25 Pass a blank value to list the platform roots instead - the drives that
26 exist on Windows, / on Unix.
27 @param [in] fref= (0) Provide a DISK engine fileref as an alternative to PATH
28 @param [in] maxdepth= (0) Set to a positive integer to indicate the level of
29 subdirectory scan recursion - eg 3, to go `./3/levels/deep`. For unlimited
30 recursion, set to MAX.
31 @param [in] maxobs= (0) Maximum number of rows to return. Zero means no
32 limit. Useful when the folder is expected to be huge and the caller only
33 needs a slice of it - no further levels are scanned once the cap is hit.
34 @param [in] showparent= (NO) By default, the initial parent directory is not
35 part of the results. Set to YES to include it. For this record only,
36 directory=filepath.
37 @param [out] outds= (work.mp_dirlist) The output dataset to create
38 @param [out] getattrs= (NO) If getattrs=YES then the doptname / foptname
39 functions are used to scan all properties - any characters that are not
40 valid in a SAS name (v7) are simply stripped, and the table is transposed
41 so theat each property is a column and there is one file per row. An
42 attempt is made to get all properties whether a file or folder, but some
43 files/folders cannot be accessed, and so not all properties can / will be
44 populated.
45 @param [in] level= (0) Ignored - retained so that callers of previous versions
46 do not break. Recursion is now done in a loop rather than by re-invoking
47 the macro.
48
49 @returns outds contains the following variables:
50 - directory (containing folder)
51 - file_or_folder. folder when it can be opened as a directory, file when
52 it is not a directory (or exists but is not readable, which the copy,
53 hash and zip tools treat as a file), and locked when it is listed but
54 cannot be opened at all - a broken link, for instance
55 - filepath (path/to/file.name)
56 - filename (just the file name)
57 - ext (.extension)
58 - msg (system message if any issues)
59 - level (depth of folder)
60 - OS SPECIFIC variables, if <code>getattrs=</code> is used.
61
62 <h4> SAS Macros </h4>
63 @li mf_getuniquefileref.sas
64 @li mf_getuniquename.sas
65 @li mf_nobs.sas
66 @li mddl_dirlist.sas
67 @li mp_dropmembers.sas
68
69 <h4> Related Macros </h4>
70 @li mp_dirlist.test.sas
71
72 @version 9.2
73 @sasjslint {"maxLineLength": 128}
74**/
75
76%macro mp_dirlist(path=%sysfunc(pathname(work))
77 , fref=0
78 , outds=work.mp_dirlist
79 , getattrs=NO
80 , showparent=NO
81 , maxdepth=0
82 , maxobs=0
83 , level=0 /* deprecated - ignored, kept for backwards compatibility */
84)/*/STORE SOURCE*/;
85%let getattrs=%upcase(&getattrs)XX;
86%let showparent=%upcase(&showparent)XX;
87
88/* the separator belongs to the platform, not to the path text - a unix
89 directory name may contain a backslash without that being the separator */
90%if "%upcase(&sysscp)"="WIN" or "%upcase(&sysscp)"="DNTHOST" %then %let mpsep=\;
91%else %let mpsep=/;
92
93%local lvl nfront total room done mp_roots mpsep schema rc;
94%local fref1 fref2;
95
96/* the parent can be supplied as a fileref rather than a path */
97%if &fref ne 0 %then %let path=%sysfunc(pathname(&fref));
98
99/* MAX is not a number, so convert it (and anything not a digit) to an int */
100%if %length(&maxdepth)=0 or %sysfunc(verify(&maxdepth,0123456789))>0 %then %do;
101 %if "%upcase(&maxdepth)"="MAX" %then %let maxdepth=2147483647;
102 %else %let maxdepth=0;
103%end;
104%if %length(&maxobs)=0 or %sysfunc(verify(&maxobs,0123456789))>0 %then %let maxobs=0;
105
106/* drop main (top) table if it exists */
107%mp_dropmembers(%scan(&outds,-1,.), libref=WORK)
108
109/* an empty table with the target structure - each level is appended to it */
110%let schema=work.%mf_getuniquename(prefix=mp_dirlist);
111%mddl_dirlist(&schema)
112data &outds;
113 if 0 then set &schema;
114 call missing(of _all_);
115 stop;
116run;
117
118/* a unique fileref per purpose, generated once - only macro vars are local */
119%let fref1=%mf_getuniquefileref();
120%let fref2=%mf_getuniquefileref();
121
122%let mp_roots=0;
123%if %length(&path)=0 %then %let mp_roots=1;
124
125%if &mp_roots=1 %then %do;
126 /*
127 A blank path is the platform roots: there is no filesystem root on Windows,
128 so the drives that exist are the top level, and / is that level on Unix.
129 */
130 data work.__mp_dirlist_level;
131 if 0 then set &schema;
132 length drive $3 letters $26;
133 call missing(of _all_);
134 %if "%upcase(&sysscp)"="WIN" or "%upcase(&sysscp)"="DNTHOST" %then %do;
135 letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
136 do i=1 to 26;
137 drive=cats(substr(letters,i,1),':');
138 rc=filename("&fref1",cats(drive,'\'));
139 did=dopen("&fref1");
140 if did>0 then do;
141 rc=dclose(did);
142 directory=drive;
143 filepath=cats(drive,'\');
144 filename=filepath;
145 file_or_folder='folder';
146 level=0;
147 output;
148 end;
149 rc=filename("&fref1");
150 end;
151 %end;
152 %else %do;
153 directory='';
154 filepath='/';
155 filename='/';
156 file_or_folder='folder';
157 level=0;
158 output;
159 %end;
160 keep directory filepath file_or_folder filename ext msg level;
161 stop;
162 run;
163 proc append base=&outds data=work.__mp_dirlist_level nowarn force;
164 run;
165 /* the roots are folders, so they are what the next level expands */
166 data work.__mp_dirlist_frontier;
167 set work.__mp_dirlist_level(where=(file_or_folder='folder'));
168 level=1;
169 keep filepath level;
170 run;
171 %let lvl=1;
172%end;
173%else %do;
174 /* level 0 is the parent itself; the path is read with symget so that quotes
175 and macro triggers in a folder name are never evaluated as SAS code */
176 data work.__mp_dirlist_frontier;
177 length filepath $2000 level 8;
178 filepath=symget('path');
179 level=0;
180 run;
181 %let lvl=0;
182%end;
183
184%let nfront=%sysfunc(coalesce(%mf_nobs(work.__mp_dirlist_frontier),0));
185%let done=0;
186
187%do %until(&nfront=0 or &lvl>&maxdepth or &done=1);
188
189 data work.__mp_dirlist_level;
190 if 0 then set &schema;
191 set work.__mp_dirlist_frontier;
192 length sep $1 prefix $2000 fname $255 dmsg $200;
193 drop sep prefix fname dmsg rc did mid i;
194 directory=filepath;
195 msg='';
196 file_or_folder='';
197 ext='';
198 filename='';
199 rc=filename("&fref1", directory);
200 did=dopen("&fref1");
201 dmsg=sysmsg();
202 if did=0 then do;
203 /* nothing to list - a parent that vanished between levels, or a path
204 that does not exist; the entries that pointed here are already marked
205 locked by the level that produced them */
206 end;
207 else do;
208 /* strip any trailing separator, keeping / and drive roots intact */
209 do while(length(directory)>1);
210 if substr(directory,length(directory),1) not in ('/','\') then leave;
211 if length(directory)=3 and substr(directory,2,1)=':' then leave;
212 directory=substr(directory,1,length(directory)-1);
213 end;
214 sep=symget('mpsep');
215 if directory='/' or (length(directory)=3 and substr(directory,2,1)=':')
216 then prefix=directory;
217 else prefix=cats(directory,sep);
218 do i=1 to dnum(did);
219 fname=dread(did,i);
220 filename=fname;
221 filepath=cats(prefix,fname);
222 msg='';
223 ext='';
224 /* dopen alone is enough to tell a folder from anything else, and it
225 returns immediately for a fifo - fopen would block until a writer
226 appeared */
227 rc=filename("&fref2",filepath);
228 mid=dopen("&fref2");
229 if mid>0 then do;
230 file_or_folder='folder';
231 rc=dclose(mid);
232 end;
233 else do;
234 dmsg=sysmsg();
235 if index(dmsg,'is not a directory')>0 then do;
236 file_or_folder='file';
237 ext=prxchange('s/.*\.{1,1}(.*)/$1/',1,filename);
238 if filename=ext then ext=' ';
239 end;
240 else if index(dmsg,'uthorization')>0 then do;
241 /* present but not readable. It stays a file, as it was before the
242 entry test was fixed - the copy, hash and zip tools skip anything
243 that is not a file, and a backup that silently omits an unreadable
244 file is worse than one that fails on it */
245 file_or_folder='file';
246 ext=prxchange('s/.*\.{1,1}(.*)/$1/',1,filename);
247 if filename=ext then ext=' ';
248 msg=dmsg;
249 end;
250 else if fexist("&fref2") then do;
251 /* dopen refused it and the platform said nothing about why -
252 Viya returns an empty sysmsg() for a regular file, where other
253 platforms say it is not a directory. Anything that exists and
254 cannot be opened as a folder is a file: reporting it as locked
255 both hides it from callers that keep folders only and shows the
256 user a row with no message */
257 file_or_folder='file';
258 ext=prxchange('s/.*\.{1,1}(.*)/$1/',1,filename);
259 if filename=ext then ext=' ';
260 end;
261 else do;
262 /* listed but not openable at all - a broken link, for instance */
263 file_or_folder='locked';
264 msg=dmsg;
265 end;
266 end;
267 rc=filename("&fref2");
268 output;
269 end;
270 rc=dclose(did);
271 end;
272 rc=filename("&fref1");
273 run;
274
275 /* trim the level to what is left of the maxobs budget before appending */
276 %let total=%sysfunc(coalesce(%mf_nobs(&outds),0));
277 %let room=2147483647;
278 %if &maxobs>0 %then %let room=%eval(&maxobs-&total);
279 %if &room>0 %then %do;
280 data work.__mp_dirlist_level;
281 set work.__mp_dirlist_level(obs=&room);
282 run;
283 proc append base=&outds data=work.__mp_dirlist_level force nowarn;
284 run;
285 %end;
286
287 %let total=%sysfunc(coalesce(%mf_nobs(&outds),0));
288 %if &maxobs>0 and &total>=&maxobs %then %let done=1;
289
290 /* the folders of this level become the parents of the next one */
291 %let nfront=0;
292 %if &done=0 and &lvl<&maxdepth %then %do;
293 data work.__mp_dirlist_frontier;
294 set work.__mp_dirlist_level(where=(file_or_folder='folder'));
295 level=level+1;
296 keep filepath level;
297 run;
298 %let nfront=%sysfunc(coalesce(%mf_nobs(work.__mp_dirlist_frontier),0));
299 %end;
300
301 %let lvl=%eval(&lvl+1);
302
303%end;
304
305/* include the starting folder itself, when asked */
306%if %substr(&showparent,1,1)=Y %then %do;
307 data work.__mp_dirlist_level;
308 if 0 then set &schema;
309 /* the parent is only listed when it can be opened, so a path that does
310 not exist stays an empty result even with showparent=YES */
311 filepath=symget('path');
312 rc=filename("&fref1",filepath);
313 did=dopen("&fref1");
314 if did>0 then rc=dclose(did);
315 rc=filename("&fref1");
316 if did=0 then stop;
317 directory=filepath;
318 do while(length(directory)>1);
319 if substr(directory,length(directory),1) not in ('/','\') then leave;
320 if length(directory)=3 and substr(directory,2,1)=':' then leave;
321 directory=substr(directory,1,length(directory)-1);
322 end;
323 filepath=directory;
324 file_or_folder='folder';
325 ext='';
326 filename=scan(directory,-1,'/\');
327 msg='';
328 level=0;
329 output;
330 stop;
331 run;
332 proc append base=&outds data=work.__mp_dirlist_level force nowarn;
333 run;
334%end;
335
336%if %substr(&getattrs,1,1)=Y %then %do;
337 data &outds;
338 set &outds;
339 length infoname infoval $60 fref $8;
340 if _n_=1 then call missing(fref);
341 rc=filename(fref,filepath);
342 drop rc infoname fid i close fref;
343 if file_or_folder='file' then do;
344 fid=fopen(fref);
345 if fid le 0 then do;
346 msg=sysmsg();
347 putlog "Could not open file:" filepath fid= ;
348 sasname='_MCNOTVALID_';
349 output;
350 end;
351 else do i=1 to foptnum(fid);
352 infoname=foptname(fid,i);
353 infoval=finfo(fid,infoname);
354 sasname=compress(infoname, '_', 'adik');
355 if anydigit(sasname)=1 then sasname=substr(sasname,anyalpha(sasname));
356 if upcase(sasname) ne 'FILENAME' then output;
357 end;
358 close=fclose(fid);
359 end;
360 else do;
361 fid=dopen(fref);
362 if fid le 0 then do;
363 msg=sysmsg();
364 putlog "Could not open folder:" filepath fid= ;
365 sasname='_MCNOTVALID_';
366 output;
367 end;
368 else do i=1 to doptnum(fid);
369 infoname=doptname(fid,i);
370 infoval=dinfo(fid,infoname);
371 sasname=compress(infoname, '_', 'adik');
372 if anydigit(sasname)=1 then sasname=substr(sasname,anyalpha(sasname));
373 if upcase(sasname) ne 'FILENAME' then output;
374 end;
375 close=dclose(fid);
376 end;
377 run;
378 proc sort;
379 by filepath sasname;
380 proc transpose data=&outds out=&outds(drop=_:);
381 id sasname;
382 var infoval;
383 by filepath file_or_folder filename ext ;
384 run;
385%end;
386
387data &outds;
388 set &outds(where=(filepath ne ''));
389run;
390
391/* tidy up reserved filerefs, including those not used for an empty listing */
392%let rc=%sysfunc(filename(fref1));
393%let rc=%sysfunc(filename(fref2));
394proc sql noprint;
395drop table work.__mp_dirlist_frontier, work.__mp_dirlist_level, &schema;
396quit;
397
398%mend mp_dirlist;