CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
pkg.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #-*- coding: utf-8 -*-
3 #pylint: disable-msg=W0122,R0914,R0912
4 
5 """
6 File : pkg.py
7 Author : Valentin Kuznetsov <vkuznet@gmail.com>
8 Description: AbstractGenerator class provides basic functionality
9 to generate CMSSW class from given template
10 """
11 
12 # system modules
13 import os
14 import sys
15 import time
16 import pprint
17 
18 # package modules
19 from FWCore.Skeletons.utils import parse_word, functor, user_info, tree
20 
22  """
23  AbstractPkg takes care how to generate code from template/PKG
24  package area. The PKG can be any directory which may include
25  any types of files, e.g. C++ (.cc), python (.py), etc.
26  This class relies on specific logic which we outline here:
27 
28  - each template may use tags defined with double underscores
29  enclosure, e.g. __class__, __record__, etc.
30  - each template may have example tags, such tags should
31  start with @example_. While processing template user may
32  choose to strip them off or keep the code behind those tags
33  - in addition user may specify pure python code which can
34  operate with user defined tags. This code snipped should
35  be enclosed with #python_begin and #python_end lines
36  which declares start and end of python block
37  """
38  def __init__(self, config=None):
39  super(AbstractPkg, self).__init__()
40  if not config:
41  self.config = {}
42  else:
43  self.config = config
44  self.pname = self.config.get('pname', None)
45  self.tmpl = self.config.get('tmpl', None)
46  self.debug = self.config.get('debug', 0)
47  self.tdir = self.config.get('tmpl_dir')
48  self.author = user_info(self.config.get('author', None))
49  self.date = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
50  self.rcsid = '$%s$' % 'Id' # CVS commit is too smart
51  self.not_in_dir = self.config.get('not_in_dir', [])
52 
53  def tmpl_etags(self):
54  "Scan template files and return example tags"
55  keys = []
56  sdir = '%s/%s' % (self.tdir, self.tmpl)
57  for name in os.listdir(sdir):
58  if name[-1] == '~':
59  continue
60  if name == 'CVS':
61  continue
62  fname = os.path.join(sdir, name)
63  with open(fname, 'r') as stream:
64  for line in stream.readlines():
65  if line.find('@example_') != -1: # possible tag
66  keys += [k for k in line.split() if \
67  k.find('@example_') != -1]
68  return set(keys)
69 
70  def print_etags(self):
71  "Print out template example tags"
72  for key in self.tmpl_etags():
73  print key
74 
75  def tmpl_tags(self):
76  "Scan template files and return template tags"
77  keys = []
78  sdir = '%s/%s' % (self.tdir, self.tmpl)
79  for name in os.listdir(sdir):
80  if name[-1] == '~':
81  continue
82  if name == 'CVS':
83  continue
84  fname = os.path.join(sdir, name)
85  with open(fname, 'r') as stream:
86  for line in stream.readlines():
87  if line.find('__') != -1: # possible key
88  keys += [k for k in parse_word(line)]
89  return set(keys)
90 
91  def print_tags(self):
92  "Print out template keys"
93  for key in self.tmpl_tags():
94  print key
95 
96  def parse_etags(self, line):
97  """
98  Determine either skip or keep given line based on class tags
99  meta-strings
100  """
101  tmpl_etags = self.tmpl_etags()
102  keep_etags = self.config.get('tmpl_etags', [])
103  for tag in tmpl_etags:
104  if keep_etags:
105  for valid_tag in keep_etags:
106  if line.find(valid_tag) != -1:
107  line = line.replace(valid_tag, '')
108  return line
109  else:
110  if line.find(tag) != -1:
111  line = line.replace(tag, '')
112  line = ''
113  return line
114  return line
115 
116  def write(self, fname, tmpl_name, kwds):
117  "Create new file from given template name and set of arguments"
118  code = ""
119  read_code = False
120  with open(fname, 'w') as stream:
121  for line in open(tmpl_name, 'r').readlines():
122  line = self.parse_etags(line)
123  if not line:
124  continue
125  if line.find('#python_begin') != -1:
126  read_code = True
127  continue
128  if line.find('#python_end') != -1:
129  read_code = False
130  if read_code:
131  code += line
132  if code and not read_code:
133  res = functor(code, kwds, self.debug)
134  stream.write(res)
135  code = ""
136  continue
137  if not read_code:
138  for key, val in kwds.items():
139  if isinstance(val, basestring):
140  line = line.replace(key, val)
141  stream.write(line)
142 
143  def get_kwds(self):
144  "Return keyword arguments to be used in methods"
145  kwds = {'__pkgname__': self.config.get('pkgname', 'Package'),
146  '__author__': self.author,
147  '__user__': os.getlogin(),
148  '__date__': self.date,
149  '__class__': self.pname,
150  '__name__': self.pname,
151  '__rcsid__': self.rcsid,
152  '__subsys__': self.config.get('subsystem', 'Subsystem')}
153  args = self.config.get('args', None)
154  kwds.update(args)
155  if self.debug:
156  print "Template tags:"
157  pprint.pprint(kwds)
158  return kwds
159 
160  def generate(self):
161  "Generate package templates in a given directory"
162 
163  # keep current location, since generate will switch directories
164  cdir = os.getcwd()
165 
166  # read from configutation which template files to create
167  tmpl_files = self.config.get('tmpl_files', 'all')
168 
169  # setup keyword arguments which we'll pass to write method
170  kwds = self.get_kwds()
171 
172  # create template package dir and cd into it
173  if tmpl_files == 'all' and self.tmpl not in self.not_in_dir:
174  if os.path.isdir(self.pname):
175  msg = "Can't create package '%s'\n" % self.pname
176  msg += "Directory %s is already exists" % self.pname
177  print msg
178  sys.exit(1)
179  os.makedirs(self.pname)
180  os.chdir(self.pname)
181 
182  # read directory driver information and create file list to generate
183  sdir = os.path.join(self.tdir, self.tmpl)
184  sources = [s for s in os.listdir(sdir) \
185  if s != 'Driver.dir' and s.find('~') == -1]
186  driver = os.path.join(sdir, 'Driver.dir')
187  if os.path.isfile(driver):
188  sources = [s.replace('\n', '') for s in open(driver, 'r').readlines()]
189  if 'CVS' in sources:
190  sources.remove('CVS')
191 
192  # special case of Skeleton, which requires to generate only given
193  # file type if self.pname has extension of that type
194  names = set([s.split('.')[0] for s in sources])
195  if names == set(['Skeleton']):
196  if self.pname.find('.') != -1:
197  _, ext = os.path.splitext(self.pname)
198  sources = [s for s in sources if s.rfind(ext) != -1]
199  self.pname = self.pname.replace(ext, '')
200  kwds = self.get_kwds()
201  if not sources:
202  msg = 'Unable to find skeleton for extension "%s"' % ext
203  print msg
204  sys.exit(1)
205  bdir = os.environ.get('CMSSW_BASE', '')
206  dirs = os.getcwd().replace(bdir, '').split('/')
207  ldir = os.getcwd().split('/')[-1]
208  idir = ''
209  subsys = kwds['__subsys__']
210  pkgname = kwds['__pkgname__']
211  if sources == ['Skeleton.cc', 'Skeleton.h']:
212  if ldir == 'interface' and os.getcwd().find(bdir) != -1:
213  idir = '%s/%s/interface/' % (subsys, pkgname)
214  # run within some directory of the Sybsystem/Pkg area
215  # and only for mkskel <file>.cc
216  elif sources == ['Skeleton.cc'] and \
217  len(dirs) == 5 and dirs[0] == '' and dirs[1] == 'src':
218  idir = '%s/%s/interface/' % (subsys, pkgname)
219  elif sources == ['Skeleton.h'] and ldir == 'interface' and \
220  len(dirs) == 5 and dirs[0] == '' and dirs[1] == 'src':
221  idir = '%s/%s/interface/' % (subsys, pkgname)
222  kwds.update({'__incdir__': idir})
223 
224  # loop over source files, create dirs as necessary and generate files
225  # names for writing templates
226  gen_files = []
227  for src in sources:
228  if tmpl_files != 'all':
229  fname, ext = os.path.splitext(src)
230  if tmpl_files != ext:
231  continue
232  src = src.split('/')[-1]
233  if self.debug:
234  print "Read", src
235  items = src.split('/')
236  if items[-1] == '/':
237  items = items[:-1]
238  tname = items[-1] # template file name
239  tmpl_name = os.path.join(sdir, items[-1]) # full tmpl file name
240  if os.path.isfile(tmpl_name):
241  ftype = 'file'
242  else:
243  ftype = 'dir'
244  name2gen = src # new file we'll create
245  if tname.split('.')[0] == self.tmpl: # need to substitute
246  name2gen = name2gen.replace(self.tmpl, self.pname)
247  name2gen = os.path.join(os.getcwd(), name2gen)
248  if self.debug:
249  print "Create", name2gen
250  if ftype == 'dir':
251  if not os.path.isdir(name2gen):
252  os.makedirs(name2gen)
253  continue # we're done with dir
254  fdir = os.path.dirname(name2gen)
255  if not os.path.isdir(fdir):
256  os.makedirs(fdir)
257  self.write(name2gen, tmpl_name, kwds)
258  gen_files.append(name2gen.split('/')[-1])
259  if tmpl_files == 'all' and self.tmpl not in self.not_in_dir:
260  msg = 'New package "%s" of %s type is successfully generated' \
261  % (self.pname, self.tmpl)
262  else:
263  msg = 'Generated %s file' % ', '.join(gen_files)
264  if len(gen_files) > 1:
265  msg += 's'
266  print msg
267  # return back where we started
268  os.chdir(cdir)
269  if msg.find('New package') != -1:
270  tree(self.pname)
def write
Definition: pkg.py:116
def parse_word
Definition: utils.py:21
def tmpl_etags
Definition: pkg.py:53
def __init__
Definition: pkg.py:38
def replace
Definition: linker.py:10
def parse_etags
Definition: pkg.py:96
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:7
def functor
Definition: utils.py:54
def print_etags
Definition: pkg.py:70
def user_info
Definition: utils.py:96
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def get_kwds
Definition: pkg.py:143
list object
Definition: dbtoconf.py:77
def generate
Definition: pkg.py:160
def tmpl_tags
Definition: pkg.py:75
double split
Definition: MVATrainer.cc:139
def print_tags
Definition: pkg.py:91