source: trunk/MagicSoft/Mars/mbase/MDirIter.cc@ 5856

Last change on this file since 5856 was 5307, checked in by tbretz, 20 years ago
*** empty log message ***
File size: 11.0 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-2003
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 <iostream>
66
67#include <TNamed.h>
68#include <TRegexp.h>
69#include <TSystem.h>
70
71ClassImp(MDirIter);
72
73using namespace std;
74
75// --------------------------------------------------------------------------
76//
77// Add a directory, eg dir="../data"
78// Using a filter (wildcards) will only return files matching this filter.
79// recursive is the number of recursive directories (use 0 for none and -1
80// for all)
81// Returns the number of directories added.
82// If a directory is added using a filter and the directory is already
83// existing without a filter the filter is replaced.
84// If any directory to be added is already existing with a different
85// filter a new entry is created, eg:
86// already existing: ../data <*.root>
87// new entry: ../data <G*>
88// The filters are or'ed.
89//
90Int_t MDirIter::AddDirectory(const char *d, const char *filter, Int_t recursive)
91{
92 TString dir(d);
93
94 // Sanity check
95 if (dir.IsNull())
96 return 0;
97
98#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
99 if (dir[dir.Length()-1]!='/')
100 dir += '/';
101#else
102 if (!dir.EndsWith("/"))
103 dir += '/';
104#endif
105 gSystem->ExpandPathName(dir);
106
107 // Try to find dir in the list of existing dirs
108 TObject *o = fList.FindObject(dir);
109 if (o)
110 {
111 const TString t(o->GetTitle());
112
113 // Check whether the existing dir has an associated filter
114 if (t.IsNull())
115 {
116 // Replace old filter by new one
117 ((TNamed*)o)->SetTitle(filter);
118 return 0;
119 }
120
121 // If the filters are the same no action is taken
122 if (t==filter)
123 return 0;
124 }
125
126 fList.Add(new TNamed((const char*)dir, filter ? filter : ""));
127
128 // No recuresive directories, return
129 if (recursive==0)
130 return 1;
131
132 Int_t rc = 1;
133
134 // Create an iterator to iterate over all entries in the directory
135 MDirIter Next(dir);
136
137 TString c;
138 while (!(c=Next(kTRUE)).IsNull())
139 {
140 // Do not process . and .. entries
141 if (c.EndsWith("/.") || c.EndsWith("/.."))
142 continue;
143
144 // If entry is a directory add it with a lower recursivity
145 if (IsDir(c)==0)
146 rc += AddDirectory(c, filter, recursive-1);
147 }
148 return rc;
149}
150
151// --------------------------------------------------------------------------
152//
153// Adds all entries from iter to this object
154//
155void MDirIter::Add(const MDirIter &iter)
156{
157 TIter Next(&iter.fList);
158 TObject *o=0;
159 while ((o=Next()))
160 fList.Add(o->Clone());
161}
162
163// --------------------------------------------------------------------------
164//
165// Return the pointer to the current directory. If the pointer is NULL
166// a new directory is opened. If no new directory can be opened NULL is
167// returned.
168//
169void *MDirIter::Open()
170{
171 // Check whether a directory is already open
172 if (fDirPtr)
173 return fDirPtr;
174
175 // Get Next entry of list
176 fCurrentPath=fNext();
177
178 // Open directory if new entry was found
179 return fCurrentPath ? gSystem->OpenDirectory(fCurrentPath->GetName()) : NULL;
180}
181
182// --------------------------------------------------------------------------
183//
184// Close directory is opened. Set fDirPtr=NULL
185//
186void MDirIter::Close()
187{
188 if (fDirPtr)
189 gSystem->FreeDirectory(fDirPtr);
190 fDirPtr = NULL;
191}
192
193// --------------------------------------------------------------------------
194//
195// Returns the concatenation of 'dir' and 'name'
196//
197TString MDirIter::ConcatFileName(const char *dir, const char *name) const
198{
199 return TString(dir)+name;
200}
201
202// --------------------------------------------------------------------------
203//
204// As the filter string may contain a + character, we have to replace
205// this filter by a new filter contaning a \+ at all locations where a +
206// was in the original filter.
207//
208// We replace:
209// . by \\.
210// + by \\+
211// * by [^\\/:]*
212// ? by .
213//
214// And surround the filter by ^ and $.
215//
216// For more details you can have a look at the template:
217// TRegexp::MakeWildcard
218//
219const TRegexp MDirIter::MakeRegexp(TString n) const
220{
221 n.Prepend("^");
222 n.ReplaceAll(".", "\\.");
223 n.ReplaceAll("+", "\\+");
224 n.ReplaceAll("*", "[^\\/:]*");
225 n.ReplaceAll("?", ".");
226 n.Append("$");
227
228 return TRegexp(n, kFALSE);
229}
230
231// --------------------------------------------------------------------------
232//
233// Check whether the given name n matches the filter f.
234// Filters are of the form TRegexp(f, kTRUE)
235//
236Bool_t MDirIter::MatchFilter(const TString &n, const TString &f) const
237{
238
239 return f.IsNull() || !n(MakeRegexp(f)).IsNull();
240}
241
242// --------------------------------------------------------------------------
243//
244// Check whether fqp is a directory.
245// Returns -1 if fqp couldn't be accesed, 0 if it is a directory,
246// 1 otherwise
247//
248Int_t MDirIter::IsDir(const char *fqp) const
249{
250 Long_t t[4];
251 if (gSystem->GetPathInfo(fqp, t, t+1, t+2, t+3))
252 return -1;
253
254 if (t[2]==3)
255 return 0;
256
257 return 1;
258}
259
260// --------------------------------------------------------------------------
261//
262// Check whether the current entry in the directory n is valid or not.
263// Entries must:
264// - not be . or ..
265// - match the associated filter
266// - match the global filter
267// - not be a directory
268// - have read permission
269//
270Bool_t MDirIter::CheckEntry(const TString n) const
271{
272 // Check . and ..
273 if (n=="." || n=="..")
274 return kFALSE;
275
276 // Check associated filter
277 if (!MatchFilter(n, fCurrentPath->GetTitle()))
278 return kFALSE;
279
280 // Check global filter
281 if (!MatchFilter(n, fFilter))
282 return kFALSE;
283
284 // Check for file or directory
285 const TString fqp = ConcatFileName(fCurrentPath->GetName(), n);
286 if (IsDir(fqp)<=0)
287 return kFALSE;
288
289 // Check for rread perissions
290 return !gSystem->AccessPathName(fqp, kReadPermission);
291
292}
293
294// --------------------------------------------------------------------------
295//
296// Reset the iteration and strat from scratch. To do this correctly we have
297// to reset the list of directories to iterate _and_ to close the current
298// directory. When you call Next() the next time the first directory will
299// be reopened again and you'll get the first entry.
300//
301// Do not try to only close the current directory or to reset the directory
302// list only. This might not give the expected result!
303//
304void MDirIter::Reset()
305{
306 Close();
307 fNext.Reset();
308}
309
310// --------------------------------------------------------------------------
311//
312// Return the Next file in the directory which is valid (see Check())
313// nocheck==1 returns the next entry unchecked
314//
315TString MDirIter::Next(Bool_t nocheck)
316{
317 fDirPtr = Open();
318 if (!fDirPtr)
319 return "";
320
321 // Get next entry in dir, if existing check validity
322 const char *n = gSystem->GetDirEntry(fDirPtr);
323 if (n)
324 return nocheck || CheckEntry(n) ? ConcatFileName(fCurrentPath->GetName(), n) : Next();
325
326 // Otherwise close directory and try to get next entry
327 Close();
328 return Next();
329}
330
331// --------------------------------------------------------------------------
332//
333// Print a single entry in the list
334//
335void MDirIter::PrintEntry(const TObject &o) const
336{
337 TString p = o.GetName();
338 TString f = o.GetTitle();
339 cout << p;
340 if (!f.IsNull())
341 cout << " <" << f << ">";
342 cout << endl;
343}
344
345// --------------------------------------------------------------------------
346//
347// Print all scheduled directories. If "all" is specified also all
348// matching entries are printed.
349//
350void MDirIter::Print(const Option_t *o) const
351{
352 TString s(o);
353 if (!s.Contains("all", TString::kIgnoreCase))
354 {
355 TIter Next(&fList);
356 TObject *o=NULL;
357 while ((o=Next()))
358 PrintEntry(*o);
359 return;
360 }
361
362 MDirIter Next(*this);
363 TString name;
364 TString d;
365 while (!(name=Next()).IsNull())
366 {
367 const TString p = Next.fCurrentPath->GetName();
368 if (p!=d)
369 {
370 d=p;
371 PrintEntry(*Next.fCurrentPath);
372 }
373 cout << " " << name << endl;
374 }
375}
376
377// --------------------------------------------------------------------------
378//
379// Loop over all contents (files). Sort the files alphabetically.
380// Delete the contents of this DirIter and add all sorted files
381// to this DirIter.
382//
383void MDirIter::Sort()
384{
385 MDirIter Next(*this);
386
387 TList l;
388 l.SetOwner();
389
390 TString name;
391 while (!(name=Next()).IsNull())
392 l.Add(new TNamed(name.Data(), ""));
393
394 l.Sort();
395
396 fList.Delete();
397 Close();
398 fFilter = "";
399
400 TIter NextN(&l);
401 TObject *o=0;
402 while ((o=NextN()))
403 {
404 TString dir = o->GetName();
405 TString name = o->GetName();
406
407 const Int_t last = dir.Last('/');
408 if (last<0)
409 continue;
410
411 dir.Remove(last);
412 name.Remove(0, last+1);
413
414 AddDirectory(dir, name);
415 }
416}
Note: See TracBrowser for help on using the repository browser.