source: trunk/Mars/mbase/MDirIter.cc@ 13452

Last change on this file since 13452 was 13078, checked in by tbretz, 13 years ago
Added th possibility to use a real regular expression.
File size: 12.2 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2008
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MDirIter
28//
29// Iterator for files in several directories (with filters)
30//
31// Use this class if you want to get all filenames in a directory
32// one-by-one.
33//
34// You can specify more than one directory (also recursivly) and you
35// can use filters (eg. *.root)
36//
37// Here is an example which will print all *.root files in the current
38// directory and all its subdirectories and all Gamma*.root files in
39// the directory ../data.
40//
41// ------------------------------------------------------------------------
42//
43// // Instatiate the iterator
44// MDirIter Next();
45//
46// // Add the current directory (for *.root files) and recursive
47// // directories with the same filter
48// Next.AddDirectory(".", "*.root", kTRUE);
49// // Add the directory ../data, too (filter only Gamma*.root files)
50// Next.AddDirectory("../data", "Gamma*.root");
51//
52// TString name;
53// while (!(name=Next()).IsNull())
54// cout << name << endl;
55//
56// ------------------------------------------------------------------------
57//
58// WARNING: If you specify relative directories (like in the example) the
59// result may depend on the current working directory! Better use
60// absolute paths.
61//
62/////////////////////////////////////////////////////////////////////////////
63#include "MDirIter.h"
64
65#include <fstream>
66#include <iostream>
67
68#include <TList.h>
69#include <TNamed.h>
70#include <TRegexp.h>
71#include <TPRegexp.h>
72#include <TSystem.h>
73
74#include "MLog.h"
75#include "MLogManip.h"
76
77ClassImp(MDirIter);
78
79using namespace std;
80
81// --------------------------------------------------------------------------
82//
83// Add a directory, eg dir="../data"
84// Using a filter (wildcards) will only return files matching this filter.
85// recursive is the number of recursive directories (use 0 for none and -1
86// for all)
87// Returns the number of directories added.
88// If a directory is added using a filter and the directory is already
89// existing without a filter the filter is replaced.
90// If any directory to be added is already existing with a different
91// filter a new entry is created, eg:
92// already existing: ../data <*.root>
93// new entry: ../data <G*>
94// The filters are or'ed.
95//
96Int_t MDirIter::AddDirectory(const char *d, const char *filter, Int_t recursive)
97{
98 TString dir(d);
99
100 // Sanity check
101 if (dir.IsNull())
102 return 0;
103
104#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
105 if (dir[dir.Length()-1]!='/')
106 dir += '/';
107#else
108 if (!dir.EndsWith("/"))
109 dir += '/';
110#endif
111 gSystem->ExpandPathName(dir);
112
113 // Try to find dir in the list of existing dirs
114 TObject *o = fList.FindObject(dir);
115 if (o)
116 {
117 const TString t(o->GetTitle());
118
119 // Check whether the existing dir has an associated filter
120 if (t.IsNull())
121 {
122 // Replace old filter by new one
123 ((TNamed*)o)->SetTitle(filter);
124 return 0;
125 }
126
127 // If the filters are the same no action is taken
128 if (t==filter)
129 return 0;
130 }
131
132 fList.Add(new TNamed((const char*)dir, filter ? filter : ""));
133
134 // No recuresive directories, return
135 if (recursive==0)
136 return 1;
137
138 Int_t rc = 1;
139
140 // Create an iterator to iterate over all entries in the directory
141 MDirIter NextD(dir);
142
143 TString c;
144 while (!(c=NextD(kTRUE)).IsNull())
145 {
146 // Do not process . and .. entries
147 if (c.EndsWith("/.") || c.EndsWith("/.."))
148 continue;
149
150 // If entry is a directory add it with a lower recursivity
151 if (IsDir(c)==0)
152 rc += AddDirectory(c, filter, recursive-1);
153 }
154 return rc;
155}
156
157// --------------------------------------------------------------------------
158//
159// Add a single file to the iterator
160//
161Int_t MDirIter::AddFile(const char *name)
162{
163 return AddDirectory(gSystem->DirName(name), gSystem->BaseName(name));
164}
165
166// --------------------------------------------------------------------------
167//
168// Adds all entries from iter to this object
169//
170void MDirIter::Add(const MDirIter &iter)
171{
172 TIter NextD(&iter.fList);
173 TObject *o=0;
174 while ((o=NextD()))
175 fList.Add(o->Clone());
176}
177
178Int_t MDirIter::ReadList(const char *name)
179{
180 TString fname(name);
181 gSystem->ExpandPathName(fname);
182
183 ifstream fin(fname);
184 if (!fin)
185 {
186 gLog << err << "Cannot open file " << fname << ": ";
187 gLog << strerror(errno) << " [errno=" << errno << "]" <<endl;
188 return -1;
189 }
190
191 Int_t rc = 0;
192
193 while (1)
194 {
195 TString line;
196 line.ReadLine(fin);
197 if (!fin)
198 break;
199
200 line = line.Strip(TString::kBoth);
201 if (line[0]=='#' || line.IsNull())
202 continue;
203
204 TObjArray &arr = *line.Tokenize(' ');
205
206 for (int i=1; i<arr.GetEntries(); i++)
207 rc += AddDirectory(arr[0]->GetName(), arr[i]->GetName(), -1);
208
209 delete &arr;
210 }
211
212 return true;
213}
214
215// --------------------------------------------------------------------------
216//
217// Return the pointer to the current directory. If the pointer is NULL
218// a new directory is opened. If no new directory can be opened NULL is
219// returned.
220//
221void *MDirIter::Open()
222{
223 // Check whether a directory is already open
224 if (fDirPtr)
225 return fDirPtr;
226
227 // Get Next entry of list
228 fCurrentPath=fNext();
229
230 // Open directory if new entry was found
231 return fCurrentPath ? gSystem->OpenDirectory(fCurrentPath->GetName()) : NULL;
232}
233
234// --------------------------------------------------------------------------
235//
236// Close directory is opened. Set fDirPtr=NULL
237//
238void MDirIter::Close()
239{
240 if (fDirPtr)
241 gSystem->FreeDirectory(fDirPtr);
242 fDirPtr = NULL;
243}
244
245// --------------------------------------------------------------------------
246//
247// Returns the concatenation of 'dir' and 'name'
248//
249TString MDirIter::ConcatFileName(const char *dir, const char *name) const
250{
251 return TString(dir)+name;
252}
253
254// --------------------------------------------------------------------------
255//
256// Check whether the given name n matches the filter f.
257//
258// If the filter is encapsulated in ^ and $ it is assumed to be
259// a valid regular expression and TPRegexp is used for filtering.
260//
261// In other cases TRegex is used:
262//
263// As the filter string may contain a + character, we have to replace
264// this filter by a new filter contaning a \+ at all locations where a +
265// was in the original filter.
266//
267// We replace:
268// . by \\.
269// + by \\+
270// * by [^\\/:]*
271//
272// And surround the filter by ^ and $.
273//
274// For more details you can have a look at the template:
275// TRegexp::MakeWildcard
276//
277Bool_t MDirIter::MatchFilter(const TString &n, TString f) const
278{
279 if (f.IsNull())
280 return kTRUE;
281
282 if (f[0]=='^' && f[f.Length()-1]=='$')
283 {
284 TPRegexp regex(f);
285 return !n(regex).IsNull();
286 }
287
288 f.Prepend("^");
289 f.ReplaceAll(".", "\\.");
290 f.ReplaceAll("+", "\\+");
291 f.ReplaceAll("*", "[^\\/:]*");
292 //f.ReplaceAll("?", "[^\\/:]?");
293 f.Append("$");
294
295 return !n(TRegexp(f)).IsNull();
296}
297
298// --------------------------------------------------------------------------
299//
300// Check whether fqp is a directory.
301// Returns -1 if fqp couldn't be accesed, 0 if it is a directory,
302// 1 otherwise
303//
304Int_t MDirIter::IsDir(const char *fqp) const
305{
306 Long_t t[4];
307 if (gSystem->GetPathInfo(fqp, t, t+1, t+2, t+3))
308 return -1;
309
310 if (t[2]==3)
311 return 0;
312
313 return 1;
314}
315
316// --------------------------------------------------------------------------
317//
318// Check whether the current entry in the directory n is valid or not.
319// Entries must:
320// - not be . or ..
321// - match the associated filter
322// - match the global filter
323// - not be a directory
324// - have read permission
325//
326Bool_t MDirIter::CheckEntry(const TString n) const
327{
328 // Check . and ..
329 if (n=="." || n=="..")
330 return kFALSE;
331
332 // Check associated filter
333 if (!MatchFilter(n, fCurrentPath->GetTitle()))
334 return kFALSE;
335
336 // Check global filter
337 if (!MatchFilter(n, fFilter))
338 return kFALSE;
339
340 // Check for file or directory
341 const TString fqp = ConcatFileName(fCurrentPath->GetName(), n);
342 if (IsDir(fqp)<=0)
343 return kFALSE;
344
345 // Check for rread perissions
346 return !gSystem->AccessPathName(fqp, kReadPermission);
347
348}
349
350// --------------------------------------------------------------------------
351//
352// Reset the iteration and strat from scratch. To do this correctly we have
353// to reset the list of directories to iterate _and_ to close the current
354// directory. When you call Next() the next time the first directory will
355// be reopened again and you'll get the first entry.
356//
357// Do not try to only close the current directory or to reset the directory
358// list only. This might not give the expected result!
359//
360void MDirIter::Reset()
361{
362 Close();
363 fNext.Reset();
364}
365
366// --------------------------------------------------------------------------
367//
368// Return the Next file in the directory which is valid (see Check())
369// nocheck==1 returns the next entry unchecked
370//
371TString MDirIter::Next(Bool_t nocheck)
372{
373 fDirPtr = Open();
374 if (!fDirPtr)
375 return "";
376
377 // Get next entry in dir, if existing check validity
378 const char *n = gSystem->GetDirEntry(fDirPtr);
379 if (n)
380 return nocheck || CheckEntry(n) ? ConcatFileName(fCurrentPath->GetName(), n) : Next();
381
382 // Otherwise close directory and try to get next entry
383 Close();
384 return Next();
385}
386
387// --------------------------------------------------------------------------
388//
389// Print a single entry in the list
390//
391void MDirIter::PrintEntry(const TObject &o) const
392{
393 TString p = o.GetName();
394 TString f = o.GetTitle();
395 cout << p;
396 if (!f.IsNull())
397 cout << " <" << f << ">";
398 cout << endl;
399}
400
401// --------------------------------------------------------------------------
402//
403// Print all scheduled directories. If "all" is specified also all
404// matching entries are printed.
405//
406void MDirIter::Print(const Option_t *opt) const
407{
408 TString s(opt);
409 if (s.Contains("dbg", TString::kIgnoreCase))
410 fList.Print();
411
412 if (!s.Contains("all", TString::kIgnoreCase))
413 {
414 TIter NextD(&fList);
415 TObject *o=NULL;
416 while ((o=NextD()))
417 PrintEntry(*o);
418 return;
419 }
420
421 MDirIter NextD(*this);
422 TString name;
423 TString d;
424 while (!(name=NextD()).IsNull())
425 {
426 const TString p = NextD.fCurrentPath->GetName();
427 if (p!=d)
428 {
429 d=p;
430 PrintEntry(*NextD.fCurrentPath);
431 }
432 cout << " " << name << endl;
433 }
434}
435
436// --------------------------------------------------------------------------
437//
438// Loop over all contents (files). Sort the files alphabetically.
439// Delete the contents of this DirIter and add all sorted files
440// to this DirIter.
441//
442void MDirIter::Sort()
443{
444 MDirIter NextD(*this);
445
446 TList l;
447 l.SetOwner();
448
449 TString name;
450 while (!(name=NextD()).IsNull())
451 l.Add(new TNamed(name.Data(), ""));
452
453 l.Sort();
454
455 fList.Delete();
456 Close();
457 fFilter = "";
458
459 TIter NextN(&l);
460 TObject *o=0;
461 while ((o=NextN()))
462 {
463 TString dir = o->GetName();
464 TString fname = o->GetName();
465
466 const Int_t last = dir.Last('/');
467 if (last<0)
468 continue;
469
470 dir.Remove(last);
471 fname.Remove(0, last+1);
472
473 AddDirectory(dir, fname);
474 }
475}
Note: See TracBrowser for help on using the repository browser.