Crombie Tools
InOutDirectoryHolder.h
Go to the documentation of this file.
1 /**
2  @file InOutDirectoryHolder.h
3  File that defines the InOutDirectoryHolder class
4  @author Daniel Abercrombie <dabercro@mit.edu>
5 */
6 
7 #ifndef CROMBIETOOLS_COMMONTOOLS_INOUTDIRECTORYHOLDER_H
8 #define CROMBIETOOLS_COMMONTOOLS_INOUTDIRECTORYHOLDER_H
9 
10 #include <map>
11 
12 #include "TString.h"
13 #include "InDirectoryHolder.h"
14 
15 /**
16 n @ingroup commongroup
17  @class InOutDirectoryHolder
18  This class is used to facilitate writing files to a directory.
19 
20  Main purpose is to centralize function of adding output directory to the filename
21  when considering said file.
22 */
23 
25 {
26  public:
28  virtual ~InOutDirectoryHolder() {};
29 
30  /// Sets the output directory where the files will be written, and adds a "/" if needed.
31  inline void SetOutDirectory ( TString dir ) { fOutDirectory = dir.EndsWith("/") ? dir : dir + "/"; }
32  /// @returns the output directory
33  inline TString GetOutDirectory () const { return fOutDirectory; }
34  /// Sets whether or not to overwrite files
35  inline void SetOverwriteFiles ( Bool_t overwrite ) { fOverwriteFiles = overwrite; }
36 
37  /// Adds a mapping from input to output file name
38  void SetInputOutputMap ( TString input, TString output ) { fInOutMap[input] = output; }
39 
40  protected:
41  /**
42  A helper function that prepends the output directory to a filename.
43  @param FileName is the name of a file inside
44  the fOutDirectory or an absolute path.
45  @returns FileName with the output directory prepended,
46  unless absolute or fOutDirectory is empty,
47  where it is left alone.
48  */
49  TString AddOutDir ( TString FileName ) const;
50 
51  private:
52  std::map<TString, TString> fInOutMap; ///< Stores name changes from input to output directories
53  TString fOutDirectory = ""; ///< Stores the output directory, and always ends with a '/'
54  Bool_t fOverwriteFiles = true; ///< Sets whether or not to overwrite output files
55 };
56 
57 //--------------------------------------------------------------------
58 
59 TString
60 InOutDirectoryHolder::AddOutDir(TString FileName) const {
61 
62  auto search = fInOutMap.find(FileName);
63  TString out_name = search == fInOutMap.end() ? FileName : search->second;
64  TString output = AddDirectory(fOutDirectory, out_name);
65 
66  if (!fOverwriteFiles) {
67 
68  struct stat buffer;
69  int code = stat(output.Data(), &buffer);
70  if (code == 0) {
71  std::cerr << "File already exists " << output << "!" << std::endl;
72  exit(21);
73  }
74 
75  }
76 
77  return output;
78 }
79 
80 
81 #endif