CMS 3D CMS Logo

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.not_in_dir = self.config.get('not_in_dir', [])
51  self.working_dir = self.config.get('working_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  for valid_tag in keep_etags:
105  if line.find(valid_tag) != -1:
106  line = line.replace(valid_tag, '')
107  return line
108  if line.find(tag) != -1:
109  line = ''
110  return line
111  return line
112 
113  def write(self, fname, tmpl_name, kwds):
114  "Create new file from given template name and set of arguments"
115  code = ""
116  read_code = False
117  if os.path.exists(fname):
118  return
119  with open(fname, 'w') as stream:
120  for line in open(tmpl_name, 'r').readlines():
121  line = self.parse_etags(line)
122  if not line:
123  continue
124  if line.find('#python_begin') != -1:
125  read_code = True
126  continue
127  if line.find('#python_end') != -1:
128  read_code = False
129  if read_code:
130  code += line
131  if code and not read_code:
132  res = functor(code, kwds, self.debug)
133  stream.write(res)
134  code = ""
135  continue
136  if not read_code:
137  for key, val in kwds.items():
138  if isinstance(val, str):
139  line = line.replace(key, val)
140  stream.write(line)
141 
142  def get_kwds(self):
143  "Return keyword arguments to be used in methods"
144  kwds = {'__pkgname__': self.config.get('pkgname', 'Package'),
145  '__author__': self.author,
146  '__user__': os.getlogin(),
147  '__date__': self.date,
148  '__class__': self.pname,
149  '__class_lowercase__': self.pname.lower(),
150  '__name__': self.pname,
151  '__subsys__': self.config.get('subsystem', 'Subsystem')}
152  args = self.config.get('args', None)
153  kwds.update(args)
154  if self.debug:
155  print "Template tags:"
156  pprint.pprint(kwds)
157  return kwds
158 
159  def generate(self):
160  "Generate package templates in a given directory"
161 
162  # keep current location, since generate will switch directories
163  cdir = os.getcwd()
164 
165  # read from configutation which template files to create
166  tmpl_files = self.config.get('tmpl_files', 'all')
167 
168  # setup keyword arguments which we'll pass to write method
169  kwds = self.get_kwds()
170 
171  # create template package dir and cd into it
172  if tmpl_files == 'all' and self.tmpl not in self.not_in_dir:
173  if os.path.isdir(self.pname):
174  msg = "Can't create package '%s'\n" % self.pname
175  msg += "Directory %s is already exists" % self.pname
176  print msg
177  sys.exit(1)
178  os.makedirs(self.pname)
179  os.chdir(self.pname)
180 
181  # read directory driver information and create file list to generate
182  sdir = os.path.join(self.tdir, self.tmpl)
183  sources = [s for s in os.listdir(sdir) \
184  if s != 'Driver.dir' and s.find('~') == -1]
185  driver = os.path.join(sdir, 'Driver.dir')
186  if os.path.isfile(driver):
187  sources = [s.replace('\n', '') for s in open(driver, 'r').readlines()]
188  if 'CVS' in sources:
189  sources.remove('CVS')
190 
191  # special case of Skeleton, which requires to generate only given
192  # file type if self.pname has extension of that type
193  names = set([s.split('.')[0] for s in sources])
194  if names == set(['Skeleton']):
195  if self.pname.find('.') != -1:
196  _, ext = os.path.splitext(self.pname)
197  sources = [s for s in sources if s.rfind(ext) != -1]
198  self.pname = self.pname.replace(ext, '')
199  kwds = self.get_kwds()
200  if not sources:
201  msg = 'Unable to find skeleton for extension "%s"' % ext
202  print msg
203  sys.exit(1)
204  bdir = os.environ.get('CMSSW_BASE', '')
205  dirs = os.getcwd().replace(bdir, '').split('/')
206  ldir = os.getcwd().split('/')[-1]
207  idir = ''
208  subsys = kwds['__subsys__']
209  pkgname = kwds['__pkgname__']
210  if sources == ['Skeleton.cc', 'Skeleton.h']:
211  if ldir == 'interface' and os.getcwd().find(bdir) != -1:
212  idir = '%s/%s/interface/' % (subsys, pkgname)
213  # run within some directory of the Sybsystem/Pkg area
214  # and only for mkskel <file>.cc
215  elif sources == ['Skeleton.cc'] and \
216  len(dirs) == 5 and dirs[0] == '' and dirs[1] == 'src':
217  idir = '%s/%s/interface/' % (subsys, pkgname)
218  elif sources == ['Skeleton.h'] and ldir == 'interface' and \
219  len(dirs) == 5 and dirs[0] == '' and dirs[1] == 'src':
220  idir = '%s/%s/interface/' % (subsys, pkgname)
221  kwds.update({'__incdir__': idir})
222 
223  # loop over source files, create dirs as necessary and generate files
224  # names for writing templates
225  gen_files = []
226  for src in sources:
227  if tmpl_files != 'all':
228  fname, ext = os.path.splitext(src)
229  if tmpl_files != ext:
230  continue
231  #also reject if this is the wrong directory
232  if self.working_dir and src.split('/')[-2] != self.working_dir:
233  continue
234  src = src.split('/')[-1]
235  if self.debug:
236  print "Read", src
237  items = src.split('/')
238  if items[-1] == '/':
239  items = items[:-1]
240  tname = items[-1] # template file name
241  tmpl_name = os.path.join(sdir, items[-1]) # full tmpl file name
242  if os.path.isfile(tmpl_name):
243  ftype = 'file'
244  else:
245  ftype = 'dir'
246  name2gen = src # new file we'll create
247  if items[-1] == 'testBuildFile.xml':
248  name2gen = '/'.join(src.split('/')[:-1])+'/BuildFile.xml'
249  if -1 !=tname.split('.')[0].find(self.tmpl): # need to substitute
250  name2gen = name2gen.replace(self.tmpl, self.pname)
251  name2gen = os.path.join(os.getcwd(), name2gen)
252  if self.debug:
253  print "Create", name2gen
254  if ftype == 'dir':
255  if not os.path.isdir(name2gen):
256  os.makedirs(name2gen)
257  continue # we're done with dir
258  fdir = os.path.dirname(name2gen)
259  if not os.path.isdir(fdir):
260  os.makedirs(fdir)
261  self.write(name2gen, tmpl_name, kwds)
262  gen_files.append(name2gen.split('/')[-1])
263  if tmpl_files == 'all' and self.tmpl not in self.not_in_dir:
264  msg = 'New package "%s" of %s type is successfully generated' \
265  % (self.pname, self.tmpl)
266  else:
267  msg = 'Generated %s file' % ', '.join(gen_files)
268  if len(gen_files) > 1:
269  msg += 's'
270  print msg
271  # return back where we started
272  os.chdir(cdir)
273  if msg.find('New package') != -1:
274  tree(self.pname)
def get_kwds(self)
Definition: pkg.py:142
def __init__(self, config=None)
Definition: pkg.py:38
def user_info(ainput=None)
Definition: utils.py:96
def replace(string, replacements)
def print_etags(self)
Definition: pkg.py:70
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:20
def generate(self)
Definition: pkg.py:159
def parse_etags(self, line)
Definition: pkg.py:96
def tmpl_etags(self)
Definition: pkg.py:53
def print_tags(self)
Definition: pkg.py:91
def tmpl_tags(self)
Definition: pkg.py:75
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def parse_word(word)
Definition: utils.py:21
def write(self, fname, tmpl_name, kwds)
Definition: pkg.py:113
def functor(code, kwds, debug=0)
Definition: utils.py:54
Definition: tree.py:1
double split
Definition: MVATrainer.cc:139