xref: /petsc/config/gmakegentest.py (revision a2ae8bbe418da4705ca2b292c083bddac8c2f10e)
129921a8fSScott Kruger#!/usr/bin/env python
229921a8fSScott Kruger
35b6bfdb9SJed Brownfrom __future__ import print_function
429921a8fSScott Krugerimport os,shutil, string, re
529921a8fSScott Krugerfrom distutils.sysconfig import parse_makefile
629921a8fSScott Krugerimport sys
76ac365aeSScott Krugerimport logging, time
829921a8fSScott Krugerimport types
929921a8fSScott Krugersys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
1029921a8fSScott Krugerfrom cmakegen import Mistakes, stripsplit, AUTODIRS, SKIPDIRS
117b8851e6SJed Brownfrom collections import defaultdict
1229921a8fSScott Krugerfrom gmakegen import *
1329921a8fSScott Kruger
1429921a8fSScott Krugerimport inspect
1529921a8fSScott Krugerthisscriptdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
1629921a8fSScott Krugersys.path.insert(0,thisscriptdir)
1729921a8fSScott Krugerimport testparse
1829921a8fSScott Krugerimport example_template
1929921a8fSScott Kruger
204ff3c6a1SScott Kruger
214ff3c6a1SScott Kruger"""
224ff3c6a1SScott Kruger
238e69c5ecSJed BrownThere are 2 modes of running tests: Normal builds and run from prefix of
248e69c5ecSJed Browninstall.  They affect where to find things:
254ff3c6a1SScott Kruger
264ff3c6a1SScott Kruger
274ff3c6a1SScott KrugerCase 1.  Normal builds:
284ff3c6a1SScott Kruger
294ff3c6a1SScott Kruger     +---------------------+----------------------------------+
304ff3c6a1SScott Kruger     | PETSC_DIR           | <git dir>                        |
314ff3c6a1SScott Kruger     +---------------------+----------------------------------+
324ff3c6a1SScott Kruger     | PETSC_ARCH          | arch-foo                         |
334ff3c6a1SScott Kruger     +---------------------+----------------------------------+
344ff3c6a1SScott Kruger     | PETSC_LIBDIR        | PETSC_DIR/PETSC_ARCH/lib         |
354ff3c6a1SScott Kruger     +---------------------+----------------------------------+
364ff3c6a1SScott Kruger     | PETSC_EXAMPLESDIR   | PETSC_DIR/src                    |
374ff3c6a1SScott Kruger     +---------------------+----------------------------------+
384ff3c6a1SScott Kruger     | PETSC_TESTDIR       | PETSC_DIR/PETSC_ARCH/tests       |
394ff3c6a1SScott Kruger     +---------------------+----------------------------------+
404ff3c6a1SScott Kruger     | PETSC_GMAKEFILETEST | PETSC_DIR/gmakefile.test         |
414ff3c6a1SScott Kruger     +---------------------+----------------------------------+
424ff3c6a1SScott Kruger     | PETSC_GMAKEGENTEST  | PETSC_DIR/config/gmakegentest.py |
434ff3c6a1SScott Kruger     +---------------------+----------------------------------+
444ff3c6a1SScott Kruger
454ff3c6a1SScott Kruger
468e69c5ecSJed BrownCase 2.  From install dir:
474ff3c6a1SScott Kruger
484ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
494ff3c6a1SScott Kruger     | PETSC_DIR           | <prefix dir>                                          |
504ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
514ff3c6a1SScott Kruger     | PETSC_ARCH          | ''                                                    |
524ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
534ff3c6a1SScott Kruger     | PETSC_LIBDIR        | PETSC_DIR/PETSC_ARCH/lib                              |
544ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
554ff3c6a1SScott Kruger     | PETSC_EXAMPLESDIR   | PETSC_DIR/share/petsc/examples/src                    |
564ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
574ff3c6a1SScott Kruger     | PETSC_TESTDIR       | PETSC_DIR/PETSC_ARCH/tests                            |
584ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
594ff3c6a1SScott Kruger     | PETSC_GMAKEFILETEST | PETSC_DIR/share/petsc/examples/gmakefile.test         |
604ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
614ff3c6a1SScott Kruger     | PETSC_GMAKEGENTEST  | PETSC_DIR/share/petsc/examples/config/gmakegentest.py |
624ff3c6a1SScott Kruger     +---------------------+-------------------------------------------------------+
634ff3c6a1SScott Kruger
644ff3c6a1SScott Kruger"""
658e69c5ecSJed Brown
668e69c5ecSJed Browndef install_files(source, destdir):
678e69c5ecSJed Brown  """Install file or directory 'source' to 'destdir'.  Does not preserve
688e69c5ecSJed Brown  mode (permissions).
698e69c5ecSJed Brown  """
708e69c5ecSJed Brown  if not os.path.isdir(destdir):
718e69c5ecSJed Brown    os.makedirs(destdir)
728e69c5ecSJed Brown  if os.path.isdir(source):
738e69c5ecSJed Brown    for name in os.listdir(source):
748e69c5ecSJed Brown      install_files(os.path.join(source, name), os.path.join(destdir, os.path.basename(source)))
758e69c5ecSJed Brown  else:
768e69c5ecSJed Brown    shutil.copyfile(source, os.path.join(destdir, os.path.basename(source)))
778e69c5ecSJed Brown
7829921a8fSScott Krugerclass generateExamples(Petsc):
7929921a8fSScott Kruger  """
8029921a8fSScott Kruger    gmakegen.py has basic structure for finding the files, writing out
8129921a8fSScott Kruger      the dependencies, etc.
8229921a8fSScott Kruger  """
838e69c5ecSJed Brown  def __init__(self,petsc_dir=None, petsc_arch=None, testdir='tests', verbose=False, single_ex=False, srcdir=None):
84add6df95SStefano Zampini    super(generateExamples, self).__init__(petsc_dir=petsc_dir, petsc_arch=petsc_arch, verbose=verbose)
8529921a8fSScott Kruger
8629921a8fSScott Kruger    self.single_ex=single_ex
87add6df95SStefano Zampini    self.srcdir=srcdir
88e551db17SScott Kruger
89c173c275SScott Kruger    # Set locations to handle movement
90fc46264cSScott Kruger    self.inInstallDir=self.getInInstallDir(thisscriptdir)
914ff3c6a1SScott Kruger
928e69c5ecSJed Brown    if self.inInstallDir:
934ff3c6a1SScott Kruger      # Case 2 discussed above
94c173c275SScott Kruger      # set PETSC_ARCH to install directory to allow script to work in both
95c173c275SScott Kruger      dirlist=thisscriptdir.split(os.path.sep)
96c173c275SScott Kruger      installdir=os.path.sep.join(dirlist[0:len(dirlist)-4])
97e551db17SScott Kruger      self.arch_dir=installdir
98add6df95SStefano Zampini      if self.srcdir is None:
99c173c275SScott Kruger        self.srcdir=os.path.join(os.path.dirname(thisscriptdir),'src')
1008e69c5ecSJed Brown    else:
1018e69c5ecSJed Brown      if petsc_arch == '':
1028e69c5ecSJed Brown        raise RuntimeError('PETSC_ARCH must be set when running from build directory')
1038e69c5ecSJed Brown      # Case 1 discussed above
1048e69c5ecSJed Brown      self.arch_dir=os.path.join(self.petsc_dir,self.petsc_arch)
105add6df95SStefano Zampini      if self.srcdir is None:
1068e69c5ecSJed Brown        self.srcdir=os.path.join(self.petsc_dir,'src')
107e551db17SScott Kruger
10894666443SJed Brown    self.testroot_dir=os.path.abspath(testdir)
109e551db17SScott Kruger
11029921a8fSScott Kruger    self.ptNaming=True
111cadd188bSScott Kruger    self.verbose=verbose
11229921a8fSScott Kruger    # Whether to write out a useful debugging
113cadd188bSScott Kruger    self.summarize=True if verbose else False
11429921a8fSScott Kruger
11529921a8fSScott Kruger    # For help in setting the requirements
11612df5dc0SToby Isaac    self.precision_types="single double __float128 int32".split()
11729921a8fSScott Kruger    self.integer_types="int32 int64".split()
11829921a8fSScott Kruger    self.languages="fortran cuda cxx".split()    # Always requires C so do not list
11929921a8fSScott Kruger
12029921a8fSScott Kruger    # Things that are not test
12129921a8fSScott Kruger    self.buildkeys=testparse.buildkeys
12229921a8fSScott Kruger
12329921a8fSScott Kruger    # Adding a dictionary for storing sources, objects, and tests
12429921a8fSScott Kruger    # to make building the dependency tree easier
12529921a8fSScott Kruger    self.sources={}
12629921a8fSScott Kruger    self.objects={}
12729921a8fSScott Kruger    self.tests={}
12829921a8fSScott Kruger    for pkg in PKGS:
12929921a8fSScott Kruger      self.sources[pkg]={}
13029921a8fSScott Kruger      self.objects[pkg]=[]
13129921a8fSScott Kruger      self.tests[pkg]={}
13229921a8fSScott Kruger      for lang in LANGS:
13329921a8fSScott Kruger        self.sources[pkg][lang]={}
13429921a8fSScott Kruger        self.sources[pkg][lang]['srcs']=[]
13529921a8fSScott Kruger        self.tests[pkg][lang]={}
13629921a8fSScott Kruger
13729921a8fSScott Kruger    if not os.path.isdir(self.testroot_dir): os.makedirs(self.testroot_dir)
1380357d61fSScott Kruger
1390357d61fSScott Kruger    self.indent="   "
140cadd188bSScott Kruger    if self.verbose: print('Finishing the constructor')
14129921a8fSScott Kruger    return
14229921a8fSScott Kruger
143c173c275SScott Kruger  def srcrelpath(self,rdir):
144c173c275SScott Kruger    """
145c173c275SScott Kruger    Get relative path to source directory
146c173c275SScott Kruger    """
14794666443SJed Brown    return os.path.relpath(rdir,self.srcdir)
148c173c275SScott Kruger
149fc46264cSScott Kruger  def getInInstallDir(self,thisscriptdir):
150c173c275SScott Kruger    """
151c173c275SScott Kruger    When petsc is installed then this file in installed in:
152c173c275SScott Kruger         <PREFIX>/share/petsc/examples/config/gmakegentest.py
153c173c275SScott Kruger    otherwise the path is:
154c173c275SScott Kruger         <PETSC_DIR>/config/gmakegentest.py
155c173c275SScott Kruger    We use this difference to determine if we are in installdir
156c173c275SScott Kruger    """
157c173c275SScott Kruger    dirlist=thisscriptdir.split(os.path.sep)
158c173c275SScott Kruger    if len(dirlist)>4:
159c173c275SScott Kruger      lastfour=os.path.sep.join(dirlist[len(dirlist)-4:])
160c173c275SScott Kruger      if lastfour==os.path.join('share','petsc','examples','config'):
161c173c275SScott Kruger        return True
162c173c275SScott Kruger      else:
163c173c275SScott Kruger        return False
164c173c275SScott Kruger    else:
165c173c275SScott Kruger      return False
166c173c275SScott Kruger
16729921a8fSScott Kruger  def nameSpace(self,srcfile,srcdir):
16829921a8fSScott Kruger    """
16929921a8fSScott Kruger    Because the scripts have a non-unique naming, the pretty-printing
17029921a8fSScott Kruger    needs to convey the srcdir and srcfile.  There are two ways of doing this.
17129921a8fSScott Kruger    """
17229921a8fSScott Kruger    if self.ptNaming:
173886063b6SScott Kruger      if srcfile.startswith('run'): srcfile=re.sub('^run','',srcfile)
17494666443SJed Brown      cdir=srcdir
17529921a8fSScott Kruger      prefix=cdir.replace('/examples/','_').replace("/","_")+"-"
17629921a8fSScott Kruger      nameString=prefix+srcfile
17729921a8fSScott Kruger    else:
17829921a8fSScott Kruger      #nameString=srcdir+": "+srcfile
17929921a8fSScott Kruger      nameString=srcfile
18029921a8fSScott Kruger    return nameString
18129921a8fSScott Kruger
18229921a8fSScott Kruger  def getLanguage(self,srcfile):
18329921a8fSScott Kruger    """
18429921a8fSScott Kruger    Based on the source, determine associated language as found in gmakegen.LANGS
18529921a8fSScott Kruger    Can we just return srcext[1:\] now?
18629921a8fSScott Kruger    """
18729921a8fSScott Kruger    langReq=None
18829921a8fSScott Kruger    srcext=os.path.splitext(srcfile)[-1]
18929921a8fSScott Kruger    if srcext in ".F90".split(): langReq="F90"
19029921a8fSScott Kruger    if srcext in ".F".split(): langReq="F"
19129921a8fSScott Kruger    if srcext in ".cxx".split(): langReq="cxx"
19229921a8fSScott Kruger    if srcext == ".cu": langReq="cu"
19329921a8fSScott Kruger    if srcext == ".c": langReq="c"
19431ad0a39SScott Kruger    #if not langReq: print("ERROR: ", srcext, srcfile)
19529921a8fSScott Kruger    return langReq
19629921a8fSScott Kruger
19796d5c3b5SScott Kruger  def _getLoopVars(self,inDict,testname, isSubtest=False):
198e9b06b45SScott Kruger    """
199e9b06b45SScott Kruger    Given: 'args: -bs {{1 2 3 4 5}} -pc_type {{cholesky sor}} -ksp_monitor'
200e9b06b45SScott Kruger    Return:
20196d5c3b5SScott Kruger      inDict['args']: -ksp_monitor
20296d5c3b5SScott Kruger      inDict['subargs']: -bs ${bs} -pc_type ${pc_type}
2030357d61fSScott Kruger      loopVars['subargs']['varlist']=['bs' 'pc_type']   # Don't worry about OrderedDict
2047827e0d6SScott Kruger      loopVars['subargs']['bs']=[["bs"],["1 2 3 4 5"]]
2057827e0d6SScott Kruger      loopVars['subargs']['pc_type']=[["pc_type"],["cholesky sor"]]
20696d5c3b5SScott Kruger    subst should be passed in instead of inDict
207e9b06b45SScott Kruger    """
2082d1d28dbSJed Brown    loopVars={}; newargs=[]
20996d5c3b5SScott Kruger    lsuffix='_'
210671702b8SJed Brown    argregex = re.compile(' (?=-[a-zA-Z])')
211aae9f2d9SScott Kruger    from testparse import parseLoopArgs
2126a044f4fSJed Brown    for key in inDict:
2136a044f4fSJed Brown      if key in ('SKIP', 'regexes'):
2146a044f4fSJed Brown        continue
2150357d61fSScott Kruger      akey=('subargs' if key=='args' else key)  # what to assign
216862148f4SScott Kruger      if akey not in inDict: inDict[akey]=''
2176a044f4fSJed Brown      if akey == 'nsize' and not inDict['nsize'].startswith('{{'):
2186a044f4fSJed Brown        # Always generate a loop over nsize, even if there is only one value
2196a044f4fSJed Brown        inDict['nsize'] = '{{' + inDict['nsize'] + '}}'
2206a044f4fSJed Brown      keystr = str(inDict[key])
2210357d61fSScott Kruger      varlist = []
222089fa112SScott Kruger      for varset in argregex.split(keystr):
223e9b06b45SScott Kruger        if not varset.strip(): continue
224aae9f2d9SScott Kruger        if '{{' in varset:
225aae9f2d9SScott Kruger          keyvar,lvars,ftype=parseLoopArgs(varset)
226862148f4SScott Kruger          if akey not in loopVars: loopVars[akey]={}
2277827e0d6SScott Kruger          varlist.append(keyvar)
2282521ea3cSScott Kruger          loopVars[akey][keyvar]=[keyvar,lvars]
2297827e0d6SScott Kruger          if akey=='nsize':
2306a044f4fSJed Brown            if len(lvars.split()) > 1:
231a449fbaeSJed Brown              lsuffix += akey +'-${' + keyvar + '}'
2327827e0d6SScott Kruger          else:
23396d5c3b5SScott Kruger            inDict[akey] += ' -'+keyvar+' ${' + keyvar + '}'
23496d5c3b5SScott Kruger            lsuffix+=keyvar+'-${' + keyvar + '}_'
2357827e0d6SScott Kruger        else:
2362d1d28dbSJed Brown          if key=='args':
2372d1d28dbSJed Brown            newargs.append(varset.strip())
2382d1d28dbSJed Brown        if varlist:
2392d1d28dbSJed Brown          loopVars[akey]['varlist']=varlist
2408ba3acebSToby Isaac
2410357d61fSScott Kruger    # For subtests, args are always substituted in (not top level)
2420357d61fSScott Kruger    if isSubtest:
2432d1d28dbSJed Brown      inDict['subargs'] += " ".join(newargs)
24496d5c3b5SScott Kruger      inDict['args']=''
245862148f4SScott Kruger      if 'label_suffix' in inDict:
24696d5c3b5SScott Kruger        inDict['label_suffix']+=lsuffix.rstrip('_')
2470357d61fSScott Kruger      else:
24896d5c3b5SScott Kruger        inDict['label_suffix']=lsuffix.rstrip('_')
24996d5c3b5SScott Kruger    else:
2502b757757SJed Brown      if loopVars:
2512d1d28dbSJed Brown        inDict['args'] = ' '.join(newargs)
25296d5c3b5SScott Kruger        inDict['label_suffix']=lsuffix.rstrip('_')
253e9b06b45SScott Kruger    return loopVars
2548ba3acebSToby Isaac
25529921a8fSScott Kruger  def getArgLabel(self,testDict):
25629921a8fSScott Kruger    """
25729921a8fSScott Kruger    In all of the arguments in the test dictionary, create a simple
25829921a8fSScott Kruger    string for searching within the makefile system.  For simplicity in
25929921a8fSScott Kruger    search, remove "-", for strings, etc.
26029921a8fSScott Kruger    Also, concatenate the arg commands
26129921a8fSScott Kruger    For now, ignore nsize -- seems hard to search for anyway
26229921a8fSScott Kruger    """
26329921a8fSScott Kruger    # Collect all of the args associated with a test
264862148f4SScott Kruger    argStr=("" if 'args' not in testDict else testDict['args'])
265862148f4SScott Kruger    if 'subtests' in testDict:
26629921a8fSScott Kruger      for stest in testDict["subtests"]:
26729921a8fSScott Kruger         sd=testDict[stest]
268862148f4SScott Kruger         argStr=argStr+("" if 'args' not in sd else sd['args'])
26929921a8fSScott Kruger
27029921a8fSScott Kruger    # Now go through and cleanup
27129921a8fSScott Kruger    argStr=re.sub('{{(.*?)}}',"",argStr)
27229921a8fSScott Kruger    argStr=re.sub('-'," ",argStr)
27329921a8fSScott Kruger    for digit in string.digits: argStr=re.sub(digit," ",argStr)
27429921a8fSScott Kruger    argStr=re.sub("\.","",argStr)
27529921a8fSScott Kruger    argStr=re.sub(",","",argStr)
27629921a8fSScott Kruger    argStr=re.sub('\+',' ',argStr)
27729921a8fSScott Kruger    argStr=re.sub(' +',' ',argStr)  # Remove repeated white space
27829921a8fSScott Kruger    return argStr.strip()
27929921a8fSScott Kruger
28031ad0a39SScott Kruger  def addToSources(self,exfile,rpath,srcDict):
28129921a8fSScott Kruger    """
28229921a8fSScott Kruger      Put into data structure that allows easy generation of makefile
28329921a8fSScott Kruger    """
28494666443SJed Brown    pkg=rpath.split(os.path.sep)[0]
285e551db17SScott Kruger    relpfile=os.path.join(rpath,exfile)
28629921a8fSScott Kruger    lang=self.getLanguage(exfile)
2870aac2865SBarry Smith    if not lang: return
28829921a8fSScott Kruger    self.sources[pkg][lang]['srcs'].append(relpfile)
289fa9d32b8SSatish Balay    self.sources[pkg][lang][relpfile] = []
290862148f4SScott Kruger    if 'depends' in srcDict:
291fa9d32b8SSatish Balay      depSrcList=srcDict['depends'].split()
292fa9d32b8SSatish Balay      for depSrc in depSrcList:
29329921a8fSScott Kruger        depObj=os.path.splitext(depSrc)[0]+".o"
294fa9d32b8SSatish Balay        self.sources[pkg][lang][relpfile].append(os.path.join(rpath,depObj))
29529921a8fSScott Kruger
29629921a8fSScott Kruger    # In gmakefile, ${TESTDIR} var specifies the object compilation
29731ad0a39SScott Kruger    testsdir=rpath+"/"
29829921a8fSScott Kruger    objfile="${TESTDIR}/"+testsdir+os.path.splitext(exfile)[0]+".o"
29929921a8fSScott Kruger    self.objects[pkg].append(objfile)
30029921a8fSScott Kruger    return
30129921a8fSScott Kruger
30231ad0a39SScott Kruger  def addToTests(self,test,rpath,exfile,execname,testDict):
30329921a8fSScott Kruger    """
30429921a8fSScott Kruger      Put into data structure that allows easy generation of makefile
30529921a8fSScott Kruger      Organized by languages to allow testing of languages
30629921a8fSScott Kruger    """
30794666443SJed Brown    pkg=rpath.split("/")[0]
30829921a8fSScott Kruger    nmtest=os.path.join(rpath,test)
30929921a8fSScott Kruger    lang=self.getLanguage(exfile)
3100aac2865SBarry Smith    if not lang: return
31129921a8fSScott Kruger    self.tests[pkg][lang][nmtest]={}
31229921a8fSScott Kruger    self.tests[pkg][lang][nmtest]['exfile']=os.path.join(rpath,exfile)
31329921a8fSScott Kruger    self.tests[pkg][lang][nmtest]['exec']=execname
31429921a8fSScott Kruger    self.tests[pkg][lang][nmtest]['argLabel']=self.getArgLabel(testDict)
31529921a8fSScott Kruger    return
31629921a8fSScott Kruger
31731ad0a39SScott Kruger  def getExecname(self,exfile,rpath):
31829921a8fSScott Kruger    """
31929921a8fSScott Kruger      Generate bash script using template found next to this file.
32029921a8fSScott Kruger      This file is read in at constructor time to avoid file I/O
32129921a8fSScott Kruger    """
32229921a8fSScott Kruger    if self.single_ex:
32329921a8fSScott Kruger      execname=rpath.split("/")[1]+"-ex"
32429921a8fSScott Kruger    else:
32529921a8fSScott Kruger      execname=os.path.splitext(exfile)[0]
32629921a8fSScott Kruger    return execname
32729921a8fSScott Kruger
32829921a8fSScott Kruger  def getSubstVars(self,testDict,rpath,testname):
32929921a8fSScott Kruger    """
33029921a8fSScott Kruger      Create a dictionary with all of the variables that get substituted
33129921a8fSScott Kruger      into the template commands found in example_template.py
33229921a8fSScott Kruger    """
33329921a8fSScott Kruger    subst={}
33496d5c3b5SScott Kruger
33596d5c3b5SScott Kruger    # Handle defaults of testparse.acceptedkeys (e.g., ignores subtests)
3366a044f4fSJed Brown    if 'nsize' not in testDict: testDict['nsize'] = '1'
3370a091e3eSScott Kruger    if 'timeoutfactor' not in testDict: testDict['timeoutfactor']="1"
33896d5c3b5SScott Kruger    for ak in testparse.acceptedkeys:
33996d5c3b5SScott Kruger      if ak=='test': continue
340862148f4SScott Kruger      subst[ak]=(testDict[ak] if ak in testDict else '')
34196d5c3b5SScott Kruger
34296d5c3b5SScott Kruger    # Now do other variables
34396d5c3b5SScott Kruger    subst['execname']=testDict['execname']
344862148f4SScott Kruger    if 'filter' in testDict:
34596d5c3b5SScott Kruger      subst['filter']="'"+testDict['filter']+"'"   # Quotes are tricky - overwrite
34668a9e459SScott Kruger
34796d5c3b5SScott Kruger    # Others
34896d5c3b5SScott Kruger    subst['subargs']=''  # Default.  For variables override
34994666443SJed Brown    subst['srcdir']=os.path.join(os.path.dirname(self.srcdir), 'src', rpath)
35068a9e459SScott Kruger    subst['label_suffix']=''
35196d5c3b5SScott Kruger    subst['comments']="\n#".join(subst['comments'].split("\n"))
35268a9e459SScott Kruger    if subst['comments']: subst['comments']="#"+subst['comments']
35396d5c3b5SScott Kruger    subst['exec']="../"+subst['execname']
35429921a8fSScott Kruger    subst['testroot']=self.testroot_dir
35529921a8fSScott Kruger    subst['testname']=testname
35609cf0baaSJed Brown    dp = self.conf.get('DATAFILESPATH','')
35709cf0baaSJed Brown    subst['datafilespath_line'] = 'DATAFILESPATH=${DATAFILESPATH:-"'+dp+'"}'
35829921a8fSScott Kruger
3590bcc1aabSScott Kruger    # This is used to label some matrices
3600bcc1aabSScott Kruger    subst['petsc_index_size']=str(self.conf['PETSC_INDEX_SIZE'])
3610bcc1aabSScott Kruger    subst['petsc_scalar_size']=str(self.conf['PETSC_SCALAR_SIZE'])
3620bcc1aabSScott Kruger
36329921a8fSScott Kruger    #Conf vars
36426646c0bSSatish Balay    if self.petsc_arch.find('valgrind')>=0:
36526646c0bSSatish Balay      subst['mpiexec']='petsc_mpiexec_valgrind ' + self.conf['MPIEXEC']
36626646c0bSSatish Balay    else:
36726646c0bSSatish Balay      subst['mpiexec']=self.conf['MPIEXEC']
3684c8d737cSSatish Balay    subst['petsc_dir']=self.petsc_dir # not self.conf['PETSC_DIR'] as this could be windows path
3690a091e3eSScott Kruger    subst['petsc_arch']=self.petsc_arch
3708e69c5ecSJed Brown    if self.inInstallDir:
3718e69c5ecSJed Brown      # Case 2
3728e69c5ecSJed Brown      subst['CONFIG_DIR']=os.path.join(os.path.dirname(self.srcdir),'config')
3738e69c5ecSJed Brown    else:
3744ff3c6a1SScott Kruger      # Case 1
375e551db17SScott Kruger      subst['CONFIG_DIR']=os.path.join(self.petsc_dir,'config')
376c3a89c15SBarry Smith    subst['PETSC_BINDIR']=os.path.join(self.petsc_dir,'lib','petsc','bin')
37729921a8fSScott Kruger    subst['diff']=self.conf['DIFF']
37829921a8fSScott Kruger    subst['rm']=self.conf['RM']
37929921a8fSScott Kruger    subst['grep']=self.conf['GREP']
380d6f00007SSatish Balay    subst['petsc_lib_dir']=self.conf['PETSC_LIB_DIR']
3810eb9b082SSatish Balay    subst['wpetsc_dir']=self.conf['wPETSC_DIR']
38229921a8fSScott Kruger
3833bcca444SScott Kruger    # Output file is special because of subtests override
3843bcca444SScott Kruger    defroot=(re.sub("run","",testname) if testname.startswith("run") else testname)
385*a2ae8bbeSScott Kruger    if not "_" in defroot: defroot=defroot+"_1"
3863bcca444SScott Kruger    subst['defroot']=defroot
38794666443SJed Brown    subst['label']=self.nameSpace(defroot,self.srcrelpath(subst['srcdir']))
3883bcca444SScott Kruger    subst['redirect_file']=defroot+".tmp"
389862148f4SScott Kruger    if 'output_file' not in testDict:
3903bcca444SScott Kruger      subst['output_file']="output/"+defroot+".out"
3913bcca444SScott Kruger    # Add in the full path here.
3923bcca444SScott Kruger    subst['output_file']=os.path.join(subst['srcdir'],subst['output_file'])
3933bcca444SScott Kruger    if not os.path.isfile(os.path.join(self.petsc_dir,subst['output_file'])):
3943bcca444SScott Kruger      if not subst['TODO']:
3955b6bfdb9SJed Brown        print("Warning: "+subst['output_file']+" not found.")
3963bcca444SScott Kruger    # Worry about alt files here -- see
3973bcca444SScott Kruger    #   src/snes/examples/tutorials/output/ex22*.out
3983bcca444SScott Kruger    altlist=[subst['output_file']]
3999af0da4bSSatish Balay    basefile,ext = os.path.splitext(subst['output_file'])
400940ae1cbSBarry Smith    for i in range(1,9):
4019af0da4bSSatish Balay      altroot=basefile+"_alt"
402940ae1cbSBarry Smith      if i > 1: altroot=altroot+"_"+str(i)
4039af0da4bSSatish Balay      af=altroot+".out"
4043bcca444SScott Kruger      srcaf=os.path.join(subst['srcdir'],af)
4053bcca444SScott Kruger      fullaf=os.path.join(self.petsc_dir,srcaf)
4063bcca444SScott Kruger      if os.path.isfile(fullaf): altlist.append(srcaf)
4073bcca444SScott Kruger    if len(altlist)>1: subst['altfiles']=altlist
40831ad0a39SScott Kruger    #if len(altlist)>1: print("Found alt files: ",altlist)
40931ad0a39SScott Kruger
41031ad0a39SScott Kruger    subst['regexes']={}
41131ad0a39SScott Kruger    for subkey in subst:
41231ad0a39SScott Kruger      if subkey=='regexes': continue
41331ad0a39SScott Kruger      if not isinstance(subst[subkey],str): continue
41431ad0a39SScott Kruger      patt="@"+subkey.upper()+"@"
41531ad0a39SScott Kruger      subst['regexes'][subkey]=re.compile(patt)
4163bcca444SScott Kruger
41729921a8fSScott Kruger    return subst
41829921a8fSScott Kruger
41931ad0a39SScott Kruger  def _substVars(self,subst,origStr):
42031ad0a39SScott Kruger    """
42131ad0a39SScott Kruger      Substitute variables
42231ad0a39SScott Kruger    """
42331ad0a39SScott Kruger    Str=origStr
42431ad0a39SScott Kruger    for subkey in subst:
42531ad0a39SScott Kruger      if subkey=='regexes': continue
42631ad0a39SScott Kruger      if not isinstance(subst[subkey],str): continue
42731ad0a39SScott Kruger      if subkey.upper() not in Str: continue
42831ad0a39SScott Kruger      Str=subst['regexes'][subkey].sub(subst[subkey],Str)
42931ad0a39SScott Kruger    return Str
43031ad0a39SScott Kruger
4310357d61fSScott Kruger  def getCmds(self,subst,i):
43229921a8fSScott Kruger    """
43329921a8fSScott Kruger      Generate bash script using template found next to this file.
43429921a8fSScott Kruger      This file is read in at constructor time to avoid file I/O
43529921a8fSScott Kruger    """
4360357d61fSScott Kruger    nindnt=i # the start and has to be consistent with below
4377a853109SScott Kruger    cmdindnt=self.indent*nindnt
43829921a8fSScott Kruger    cmdLines=""
43968a9e459SScott Kruger
44029921a8fSScott Kruger    # MPI is the default -- but we have a few odd commands
44196d5c3b5SScott Kruger    if not subst['command']:
4427a853109SScott Kruger      cmd=cmdindnt+self._substVars(subst,example_template.mpitest)
44329921a8fSScott Kruger    else:
4447a853109SScott Kruger      cmd=cmdindnt+self._substVars(subst,example_template.commandtest)
4457a853109SScott Kruger    cmdLines+=cmd+"\n"+cmdindnt+"res=$?\n\n"
44629921a8fSScott Kruger
4477a853109SScott Kruger    cmdLines+=cmdindnt+'if test $res = 0; then\n'
4487a853109SScott Kruger    diffindnt=self.indent*(nindnt+1)
44964ca018dSScott Kruger    if not subst['filter_output']:
450862148f4SScott Kruger      if 'altfiles' not in subst:
4517a853109SScott Kruger        cmd=diffindnt+self._substVars(subst,example_template.difftest)
45264ca018dSScott Kruger      else:
4533bcca444SScott Kruger        # Have to do it by hand a bit because of variable number of alt files
4543bcca444SScott Kruger        rf=subst['redirect_file']
4557a853109SScott Kruger        cmd=diffindnt+example_template.difftest.split('@')[0]
4563bcca444SScott Kruger        for i in range(len(subst['altfiles'])):
4573bcca444SScott Kruger          af=subst['altfiles'][i]
458886063b6SScott Kruger          cmd+=af+' '+rf
4593bcca444SScott Kruger          if i!=len(subst['altfiles'])-1:
460886063b6SScott Kruger            cmd+=' > diff-${testname}-'+str(i)+'.out 2> diff-${testname}-'+str(i)+'.out'
461886063b6SScott Kruger            cmd+=' || ${diff_exe} '
4623bcca444SScott Kruger          else:
4633bcca444SScott Kruger            cmd+='" diff-${testname}.out diff-${testname}.out diff-${label}'
4643bcca444SScott Kruger            cmd+=subst['label_suffix']+' ""'  # Quotes are painful
4653bcca444SScott Kruger    else:
4667a853109SScott Kruger      cmd=diffindnt+self._substVars(subst,example_template.filterdifftest)
46768a9e459SScott Kruger    cmdLines+=cmd+"\n"
4687a853109SScott Kruger    cmdLines+=cmdindnt+'else\n'
4697a853109SScott Kruger    cmdLines+=diffindnt+'printf "ok ${label} # SKIP Command failed so no diff\\n"\n'
4707a853109SScott Kruger    cmdLines+=cmdindnt+'fi\n'
47129921a8fSScott Kruger    return cmdLines
47229921a8fSScott Kruger
47309cf0baaSJed Brown  def _writeTodoSkip(self,fh,tors,reasons,footer):
47468a9e459SScott Kruger    """
47568a9e459SScott Kruger    Write out the TODO and SKIP lines in the file
47668a9e459SScott Kruger    The TODO or SKIP variable, tors, should be lower case
47768a9e459SScott Kruger    """
47868a9e459SScott Kruger    TORS=tors.upper()
47968a9e459SScott Kruger    template=eval("example_template."+tors+"line")
48009cf0baaSJed Brown    tsStr=re.sub("@"+TORS+"COMMENT@",', '.join(reasons),template)
48109cf0baaSJed Brown    tab = ''
4822f2809e3SToby Isaac    if reasons:
4832f2809e3SToby Isaac      fh.write('if ! $force; then\n')
4842f2809e3SToby Isaac      tab = tab + '    '
48509cf0baaSJed Brown    if reasons == ["Requires DATAFILESPATH"]:
48609cf0baaSJed Brown      # The only reason not to run is DATAFILESPATH, which we check at run-time
4872f2809e3SToby Isaac      fh.write(tab + 'if test -z "${DATAFILESPATH}"; then\n')
4882f2809e3SToby Isaac      tab = tab + '    '
48909cf0baaSJed Brown    if reasons:
4902f2809e3SToby Isaac      fh.write(tab+tsStr+"\n" + tab + "total=1; "+tors+"=1\n")
49109cf0baaSJed Brown      fh.write(tab+footer+"\n")
49209cf0baaSJed Brown      fh.write(tab+"exit\n")
49309cf0baaSJed Brown    if reasons == ["Requires DATAFILESPATH"]:
49409cf0baaSJed Brown      fh.write('    fi\n')
4952f2809e3SToby Isaac    if reasons:
4962f2809e3SToby Isaac      fh.write('fi\n')
49709cf0baaSJed Brown    fh.write('\n\n')
49868a9e459SScott Kruger    return
49968a9e459SScott Kruger
5001fc39a0eSScott Kruger  def getLoopVarsHead(self,loopVars,i,usedVars={}):
5010357d61fSScott Kruger    """
5020357d61fSScott Kruger    Generate a nicely indented string with the format loops
5030357d61fSScott Kruger    Here is what the data structure looks like
5040357d61fSScott Kruger      loopVars['subargs']['varlist']=['bs' 'pc_type']   # Don't worry about OrderedDict
5050357d61fSScott Kruger      loopVars['subargs']['bs']=["i","1 2 3 4 5"]
5060357d61fSScott Kruger      loopVars['subargs']['pc_type']=["j","cholesky sor"]
5070357d61fSScott Kruger    """
5080357d61fSScott Kruger    outstr=''; indnt=self.indent
5099aa7185eSScott Kruger
5108ba3acebSToby Isaac    for key in loopVars:
5111fc39a0eSScott Kruger      if key in usedVars: continue         # Do not duplicate setting vars
5120357d61fSScott Kruger      for var in loopVars[key]['varlist']:
5130357d61fSScott Kruger        varval=loopVars[key][var]
5149aa7185eSScott Kruger        outstr += "{0}_in=${{{0}:-{1}}}\n".format(*varval)
5159aa7185eSScott Kruger    outstr += "\n\n"
5169aa7185eSScott Kruger
5179aa7185eSScott Kruger    for key in loopVars:
5189aa7185eSScott Kruger      for var in loopVars[key]['varlist']:
5199aa7185eSScott Kruger        varval=loopVars[key][var]
5209aa7185eSScott Kruger        outstr += indnt * i + "for {0} in ${{{0}_in}}; do\n".format(*varval)
5218ba3acebSToby Isaac        i = i + 1
5228ba3acebSToby Isaac    return (outstr,i)
5238ba3acebSToby Isaac
5248ba3acebSToby Isaac  def getLoopVarsFoot(self,loopVars,i):
5250357d61fSScott Kruger    outstr=''; indnt=self.indent
5268ba3acebSToby Isaac    for key in loopVars:
5270357d61fSScott Kruger      for var in loopVars[key]['varlist']:
5288ba3acebSToby Isaac        i = i - 1
5290357d61fSScott Kruger        outstr += indnt * i + "done\n"
5308ba3acebSToby Isaac    return (outstr,i)
5318ba3acebSToby Isaac
53229921a8fSScott Kruger  def genRunScript(self,testname,root,isRun,srcDict):
53329921a8fSScott Kruger    """
53429921a8fSScott Kruger      Generate bash script using template found next to this file.
53529921a8fSScott Kruger      This file is read in at constructor time to avoid file I/O
53629921a8fSScott Kruger    """
53729921a8fSScott Kruger    # runscript_dir directory has to be consistent with gmakefile
53829921a8fSScott Kruger    testDict=srcDict[testname]
539c173c275SScott Kruger    rpath=self.srcrelpath(root)
54029921a8fSScott Kruger    runscript_dir=os.path.join(self.testroot_dir,rpath)
54129921a8fSScott Kruger    if not os.path.isdir(runscript_dir): os.makedirs(runscript_dir)
54229921a8fSScott Kruger    fh=open(os.path.join(runscript_dir,testname+".sh"),"w")
54329921a8fSScott Kruger
54496d5c3b5SScott Kruger    # Get variables to go into shell scripts.  last time testDict used
54529921a8fSScott Kruger    subst=self.getSubstVars(testDict,rpath,testname)
54696d5c3b5SScott Kruger    loopVars = self._getLoopVars(subst,testname)  # Alters subst as well
547a449fbaeSJed Brown    if 'subtests' in testDict:
548a449fbaeSJed Brown      # The subtests inherit inDict, so we don't need top-level loops.
549a449fbaeSJed Brown      loopVars = {}
55029921a8fSScott Kruger
55164ca018dSScott Kruger    #Handle runfiles
552862148f4SScott Kruger    for lfile in subst.get('localrunfiles','').split():
553ed81ced6SJed Brown      install_files(os.path.join(root, lfile),
554ed81ced6SJed Brown                    os.path.join(runscript_dir, os.path.dirname(lfile)))
55564ca018dSScott Kruger    # Check subtests for local runfiles
556862148f4SScott Kruger    for stest in subst.get("subtests",[]):
557862148f4SScott Kruger      for lfile in testDict[stest].get('localrunfiles','').split():
558ed81ced6SJed Brown        install_files(os.path.join(root, lfile),
559ed81ced6SJed Brown                      os.path.join(runscript_dir, os.path.dirname(lfile)))
56064ca018dSScott Kruger
56129921a8fSScott Kruger    # Now substitute the key variables into the header and footer
56229921a8fSScott Kruger    header=self._substVars(subst,example_template.header)
5630bcc1aabSScott Kruger    # The header is done twice to enable @...@ in header
5640bcc1aabSScott Kruger    header=self._substVars(subst,header)
5655e7f8670SScott Kruger    footer=re.sub('@TESTROOT@',subst['testroot'],example_template.footer)
56629921a8fSScott Kruger
56729921a8fSScott Kruger    # Start writing the file
56829921a8fSScott Kruger    fh.write(header+"\n")
56929921a8fSScott Kruger
57029921a8fSScott Kruger    # If there is a TODO or a SKIP then we do it before writing out the
57129921a8fSScott Kruger    # rest of the command (which is useful for working on the test)
57229921a8fSScott Kruger    # SKIP and TODO can be for the source file or for the runs
57309cf0baaSJed Brown    self._writeTodoSkip(fh,'todo',[s for s in [srcDict.get('TODO',''), testDict.get('TODO','')] if s],footer)
57409cf0baaSJed Brown    self._writeTodoSkip(fh,'skip',srcDict.get('SKIP',[]) + testDict.get('SKIP',[]),footer)
57529921a8fSScott Kruger
57629921a8fSScott Kruger    j=0  # for indentation
57729921a8fSScott Kruger
5780357d61fSScott Kruger    if loopVars:
5798ba3acebSToby Isaac      (loopHead,j) = self.getLoopVarsHead(loopVars,j)
5808ba3acebSToby Isaac      if (loopHead): fh.write(loopHead+"\n")
58129921a8fSScott Kruger
58229921a8fSScott Kruger    # Subtests are special
5831fc39a0eSScott Kruger    allLoopVars=list(loopVars.keys())
584862148f4SScott Kruger    if 'subtests' in testDict:
58529921a8fSScott Kruger      substP=subst   # Subtests can inherit args but be careful
5864fedfc52SScott Kruger      k=0  # for label suffixes
58729921a8fSScott Kruger      for stest in testDict["subtests"]:
5881e4ea733SToby Isaac        subst=substP.copy()
5890357d61fSScott Kruger        subst.update(testDict[stest])
5904fedfc52SScott Kruger        subst['label_suffix']='-'+string.ascii_letters[k]; k+=1
5917827e0d6SScott Kruger        sLoopVars = self._getLoopVars(subst,testname,isSubtest=True)
5920357d61fSScott Kruger        if sLoopVars:
5931fc39a0eSScott Kruger          (sLoopHead,j) = self.getLoopVarsHead(sLoopVars,j,allLoopVars)
5941fc39a0eSScott Kruger          allLoopVars+=list(sLoopVars.keys())
5950357d61fSScott Kruger          fh.write(sLoopHead+"\n")
5960357d61fSScott Kruger        fh.write(self.getCmds(subst,j)+"\n")
5970357d61fSScott Kruger        if sLoopVars:
5988ba3acebSToby Isaac          (sLoopFoot,j) = self.getLoopVarsFoot(sLoopVars,j)
5990357d61fSScott Kruger          fh.write(sLoopFoot+"\n")
60029921a8fSScott Kruger    else:
60129921a8fSScott Kruger      fh.write(self.getCmds(subst,j)+"\n")
6028ba3acebSToby Isaac
6030357d61fSScott Kruger    if loopVars:
6048ba3acebSToby Isaac      (loopFoot,j) = self.getLoopVarsFoot(loopVars,j)
6050357d61fSScott Kruger      fh.write(loopFoot+"\n")
60629921a8fSScott Kruger
60729921a8fSScott Kruger    fh.write(footer+"\n")
6085b6bfdb9SJed Brown    os.chmod(os.path.join(runscript_dir,testname+".sh"),0o755)
6097827e0d6SScott Kruger    #if '10_9' in testname: sys.exit()
61029921a8fSScott Kruger    return
61129921a8fSScott Kruger
61229921a8fSScott Kruger  def  genScriptsAndInfo(self,exfile,root,srcDict):
61329921a8fSScott Kruger    """
61429921a8fSScott Kruger    Generate scripts from the source file, determine if built, etc.
61529921a8fSScott Kruger     For every test in the exfile with info in the srcDict:
61629921a8fSScott Kruger      1. Determine if it needs to be run for this arch
61729921a8fSScott Kruger      2. Generate the script
61829921a8fSScott Kruger      3. Generate the data needed to write out the makefile in a
61929921a8fSScott Kruger         convenient way
62029921a8fSScott Kruger     All tests are *always* run, but some may be SKIP'd per the TAP standard
62129921a8fSScott Kruger    """
62229921a8fSScott Kruger    debug=False
62331ad0a39SScott Kruger    rpath=self.srcrelpath(root)
62431ad0a39SScott Kruger    execname=self.getExecname(exfile,rpath)
62529921a8fSScott Kruger    isBuilt=self._isBuilt(exfile,srcDict)
62629921a8fSScott Kruger    for test in srcDict:
62729921a8fSScott Kruger      if test in self.buildkeys: continue
6285b6bfdb9SJed Brown      if debug: print(self.nameSpace(exfile,root), test)
62929921a8fSScott Kruger      srcDict[test]['execname']=execname   # Convenience in generating scripts
63029921a8fSScott Kruger      isRun=self._isRun(srcDict[test])
63129921a8fSScott Kruger      self.genRunScript(test,root,isRun,srcDict)
63229921a8fSScott Kruger      srcDict[test]['isrun']=isRun
63331ad0a39SScott Kruger      self.addToTests(test,rpath,exfile,execname,srcDict[test])
63429921a8fSScott Kruger
63529921a8fSScott Kruger    # This adds to datastructure for building deps
63631ad0a39SScott Kruger    if isBuilt: self.addToSources(exfile,rpath,srcDict)
63729921a8fSScott Kruger    return
63829921a8fSScott Kruger
63929921a8fSScott Kruger  def _isBuilt(self,exfile,srcDict):
64029921a8fSScott Kruger    """
64129921a8fSScott Kruger    Determine if this file should be built.
64229921a8fSScott Kruger    """
64329921a8fSScott Kruger    # Get the language based on file extension
64409cf0baaSJed Brown    srcDict['SKIP'] = []
64529921a8fSScott Kruger    lang=self.getLanguage(exfile)
646c2426ab2SScott Kruger    if (lang=="F" or lang=="F90"):
647c2426ab2SScott Kruger      if not self.have_fortran:
64809cf0baaSJed Brown        srcDict["SKIP"].append("Fortran required for this test")
649c2426ab2SScott Kruger      elif lang=="F90" and 'PETSC_USING_F90FREEFORM' not in self.conf:
650c2426ab2SScott Kruger        srcDict["SKIP"].append("Fortran f90freeform required for this test")
651862148f4SScott Kruger    if lang=="cu" and 'PETSC_HAVE_CUDA' not in self.conf:
65209cf0baaSJed Brown      srcDict["SKIP"].append("CUDA required for this test")
653862148f4SScott Kruger    if lang=="cxx" and 'PETSC_HAVE_CXX' not in self.conf:
65409cf0baaSJed Brown      srcDict["SKIP"].append("C++ required for this test")
65529921a8fSScott Kruger
65629921a8fSScott Kruger    # Deprecated source files
65709cf0baaSJed Brown    if srcDict.get("TODO"):
65809cf0baaSJed Brown      return False
65929921a8fSScott Kruger
66029921a8fSScott Kruger    # isRun can work with srcDict to handle the requires
661862148f4SScott Kruger    if "requires" in srcDict:
662cadd188bSScott Kruger      if srcDict["requires"]:
66329921a8fSScott Kruger        return self._isRun(srcDict)
66429921a8fSScott Kruger
66509cf0baaSJed Brown    return srcDict['SKIP'] == []
66629921a8fSScott Kruger
66729921a8fSScott Kruger
668e4653983SScott Kruger  def _isRun(self,testDict, debug=False):
66929921a8fSScott Kruger    """
67029921a8fSScott Kruger    Based on the requirements listed in the src file and the petscconf.h
67129921a8fSScott Kruger    info, determine whether this test should be run or not.
67229921a8fSScott Kruger    """
67329921a8fSScott Kruger    indent="  "
67429921a8fSScott Kruger
67509cf0baaSJed Brown    if 'SKIP' not in testDict:
67609cf0baaSJed Brown      testDict['SKIP'] = []
67729921a8fSScott Kruger    # MPI requirements
6785b08e527SSatish Balay    if 'MPI_IS_MPIUNI' in self.conf:
6796a044f4fSJed Brown      if testDict.get('nsize', '1') != '1':
68009cf0baaSJed Brown        testDict['SKIP'].append("Parallel test with serial build")
68129921a8fSScott Kruger
68229921a8fSScott Kruger      # The requirements for the test are the sum of all the run subtests
683862148f4SScott Kruger      if 'subtests' in testDict:
684862148f4SScott Kruger        if 'requires' not in testDict: testDict['requires']=""
68529921a8fSScott Kruger        for stest in testDict['subtests']:
686862148f4SScott Kruger          if 'requires' in testDict[stest]:
687862148f4SScott Kruger            testDict['requires']+=" "+testDict[stest]['requires']
6886a044f4fSJed Brown          if testDict.get('nsize', '1') != '1':
68973de2b55SScott Kruger            testDict['SKIP'].append("Parallel test with serial build")
6905b08e527SSatish Balay            break
69129921a8fSScott Kruger
69229921a8fSScott Kruger    # Now go through all requirements
693862148f4SScott Kruger    if 'requires' in testDict:
69429921a8fSScott Kruger      for requirement in testDict['requires'].split():
69529921a8fSScott Kruger        requirement=requirement.strip()
69629921a8fSScott Kruger        if not requirement: continue
6975b6bfdb9SJed Brown        if debug: print(indent+"Requirement: ", requirement)
69829921a8fSScott Kruger        isNull=False
69929921a8fSScott Kruger        if requirement.startswith("!"):
70029921a8fSScott Kruger          requirement=requirement[1:]; isNull=True
70129921a8fSScott Kruger        # Precision requirement for reals
70229921a8fSScott Kruger        if requirement in self.precision_types:
70329921a8fSScott Kruger          if self.conf['PETSC_PRECISION']==requirement:
70409cf0baaSJed Brown            if isNull:
70509cf0baaSJed Brown              testDict['SKIP'].append("not "+requirement+" required")
70609cf0baaSJed Brown              continue
7074bb4d03dSScott Kruger            continue  # Success
70809cf0baaSJed Brown          elif not isNull:
70909cf0baaSJed Brown            testDict['SKIP'].append(requirement+" required")
71009cf0baaSJed Brown            continue
71129921a8fSScott Kruger        # Precision requirement for ints
71229921a8fSScott Kruger        if requirement in self.integer_types:
71329921a8fSScott Kruger          if requirement=="int32":
71429921a8fSScott Kruger            if self.conf['PETSC_SIZEOF_INT']==4:
71509cf0baaSJed Brown              if isNull:
71609cf0baaSJed Brown                testDict['SKIP'].append("not int32 required")
71709cf0baaSJed Brown                continue
7184bb4d03dSScott Kruger              continue  # Success
71909cf0baaSJed Brown            elif not isNull:
72009cf0baaSJed Brown              testDict['SKIP'].append("int32 required")
72109cf0baaSJed Brown              continue
72229921a8fSScott Kruger          if requirement=="int64":
72329921a8fSScott Kruger            if self.conf['PETSC_SIZEOF_INT']==8:
72409cf0baaSJed Brown              if isNull:
72509cf0baaSJed Brown                testDict['SKIP'].append("NOT int64 required")
72609cf0baaSJed Brown                continue
7274bb4d03dSScott Kruger              continue  # Success
72809cf0baaSJed Brown            elif not isNull:
72909cf0baaSJed Brown              testDict['SKIP'].append("int64 required")
73009cf0baaSJed Brown              continue
73129921a8fSScott Kruger        # Datafilespath
73209cf0baaSJed Brown        if requirement=="datafilespath" and not isNull:
73309cf0baaSJed Brown          testDict['SKIP'].append("Requires DATAFILESPATH")
73409cf0baaSJed Brown          continue
73529921a8fSScott Kruger        # Defines -- not sure I have comments matching
7368304fa3fSScott Kruger        if "define(" in requirement.lower():
73729921a8fSScott Kruger          reqdef=requirement.split("(")[1].split(")")[0]
73809cf0baaSJed Brown          if reqdef in self.conf:
73929921a8fSScott Kruger            if isNull:
74009cf0baaSJed Brown              testDict['SKIP'].append("Null requirement not met: "+requirement)
74109cf0baaSJed Brown              continue
7424bb4d03dSScott Kruger            continue  # Success
7434bb4d03dSScott Kruger          elif not isNull:
74409cf0baaSJed Brown            testDict['SKIP'].append("Required: "+requirement)
74509cf0baaSJed Brown            continue
74629921a8fSScott Kruger
74729921a8fSScott Kruger        # Rest should be packages that we can just get from conf
74809cf0baaSJed Brown        if requirement == "complex":
74909cf0baaSJed Brown          petscconfvar="PETSC_USE_COMPLEX"
75009cf0baaSJed Brown        else:
75109cf0baaSJed Brown          petscconfvar="PETSC_HAVE_"+requirement.upper()
75229921a8fSScott Kruger        if self.conf.get(petscconfvar):
75329921a8fSScott Kruger          if isNull:
75409cf0baaSJed Brown            testDict['SKIP'].append("Not "+petscconfvar+" requirement not met")
75509cf0baaSJed Brown            continue
7564bb4d03dSScott Kruger          continue  # Success
757df3aec83SJed Brown        elif not isNull:
7585b6bfdb9SJed Brown          if debug: print("requirement not found: ", requirement)
75909cf0baaSJed Brown          testDict['SKIP'].append(petscconfvar+" requirement not met")
76009cf0baaSJed Brown          continue
76129921a8fSScott Kruger
76209cf0baaSJed Brown    return testDict['SKIP'] == []
76329921a8fSScott Kruger
76429921a8fSScott Kruger  def genPetscTests_summarize(self,dataDict):
76529921a8fSScott Kruger    """
76629921a8fSScott Kruger    Required method to state what happened
76729921a8fSScott Kruger    """
76829921a8fSScott Kruger    if not self.summarize: return
76929921a8fSScott Kruger    indent="   "
770cfaa06beSSatish Balay    fhname=os.path.join(self.testroot_dir,'GenPetscTests_summarize.txt')
77129921a8fSScott Kruger    fh=open(fhname,"w")
77229921a8fSScott Kruger    for root in dataDict:
773c173c275SScott Kruger      relroot=self.srcrelpath(root)
77429921a8fSScott Kruger      pkg=relroot.split("/")[1]
77529921a8fSScott Kruger      fh.write(relroot+"\n")
77629921a8fSScott Kruger      allSrcs=[]
777e551db17SScott Kruger      for lang in LANGS: allSrcs+=self.sources[pkg][lang]['srcs']
77829921a8fSScott Kruger      for exfile in dataDict[root]:
77929921a8fSScott Kruger        # Basic  information
780c173c275SScott Kruger        rfile=os.path.join(relroot,exfile)
78129921a8fSScott Kruger        builtStatus=(" Is built" if rfile in allSrcs else " Is NOT built")
78229921a8fSScott Kruger        fh.write(indent+exfile+indent*4+builtStatus+"\n")
78329921a8fSScott Kruger
78429921a8fSScott Kruger        for test in dataDict[root][exfile]:
78529921a8fSScott Kruger          if test in self.buildkeys: continue
78629921a8fSScott Kruger          line=indent*2+test
78729921a8fSScott Kruger          fh.write(line+"\n")
78829921a8fSScott Kruger          # Looks nice to have the keys in order
78929921a8fSScott Kruger          #for key in dataDict[root][exfile][test]:
79029921a8fSScott Kruger          for key in "isrun abstracted nsize args requires script".split():
791862148f4SScott Kruger            if key not in dataDict[root][exfile][test]: continue
79229921a8fSScott Kruger            line=indent*3+key+": "+str(dataDict[root][exfile][test][key])
79329921a8fSScott Kruger            fh.write(line+"\n")
79429921a8fSScott Kruger          fh.write("\n")
79529921a8fSScott Kruger        fh.write("\n")
79629921a8fSScott Kruger      fh.write("\n")
79729921a8fSScott Kruger    #fh.write("\nClass Sources\n"+str(self.sources)+"\n")
79829921a8fSScott Kruger    #fh.write("\nClass Tests\n"+str(self.tests)+"\n")
79929921a8fSScott Kruger    fh.close()
80029921a8fSScott Kruger    return
80129921a8fSScott Kruger
80229921a8fSScott Kruger  def genPetscTests(self,root,dirs,files,dataDict):
80329921a8fSScott Kruger    """
80429921a8fSScott Kruger     Go through and parse the source files in the directory to generate
80529921a8fSScott Kruger     the examples based on the metadata contained in the source files
80629921a8fSScott Kruger    """
80729921a8fSScott Kruger    debug=False
80829921a8fSScott Kruger    # Use examplesAnalyze to get what the makefles think are sources
80929921a8fSScott Kruger    #self.examplesAnalyze(root,dirs,files,anlzDict)
81029921a8fSScott Kruger
81129921a8fSScott Kruger    dataDict[root]={}
81229921a8fSScott Kruger
81329921a8fSScott Kruger    for exfile in files:
81429921a8fSScott Kruger      #TST: Until we replace files, still leaving the orginals as is
81529921a8fSScott Kruger      #if not exfile.startswith("new_"+"ex"): continue
81662197512SBarry Smith      #if not exfile.startswith("ex"): continue
81729921a8fSScott Kruger
818e4653983SScott Kruger      # Ignore emacs and other temporary files
819e4653983SScott Kruger      if exfile.startswith("."): continue
820e4653983SScott Kruger      if exfile.startswith("#"): continue
8212cde73d3SScott Kruger      if exfile.endswith("~"): continue
82231ad0a39SScott Kruger      # Only parse source files
82331ad0a39SScott Kruger      ext=os.path.splitext(exfile)[-1].lstrip('.')
82431ad0a39SScott Kruger      if ext not in LANGS: continue
82513ddbc6dSScott Kruger
82629921a8fSScott Kruger      # Convenience
82729921a8fSScott Kruger      fullex=os.path.join(root,exfile)
828cadd188bSScott Kruger      if self.verbose: print('   --> '+fullex)
82996d5c3b5SScott Kruger      dataDict[root].update(testparse.parseTestFile(fullex,0))
830862148f4SScott Kruger      if exfile in dataDict[root]:
83129921a8fSScott Kruger        self.genScriptsAndInfo(exfile,root,dataDict[root][exfile])
83229921a8fSScott Kruger
83329921a8fSScott Kruger    return
83429921a8fSScott Kruger
835cadd188bSScott Kruger  def walktree(self,top):
83629921a8fSScott Kruger    """
83729921a8fSScott Kruger    Walk a directory tree, starting from 'top'
83829921a8fSScott Kruger    """
83929921a8fSScott Kruger    # Goal of action is to fill this dictionary
84029921a8fSScott Kruger    dataDict={}
841f98eef70SScott Kruger    for root, dirs, files in os.walk(top, topdown=True):
84209a6cbfcSBernhard M. Wiedemann      dirs.sort()
84309a6cbfcSBernhard M. Wiedemann      files.sort()
84429921a8fSScott Kruger      if not "examples" in root: continue
845f98eef70SScott Kruger      if "dSYM" in root: continue
846f98eef70SScott Kruger      if os.path.basename(root.rstrip("/")) == 'output': continue
847cadd188bSScott Kruger      if self.verbose: print(root)
848b6d69c80SScott Kruger      self.genPetscTests(root,dirs,files,dataDict)
84929921a8fSScott Kruger    # Now summarize this dictionary
85031ad0a39SScott Kruger    if self.verbose: self.genPetscTests_summarize(dataDict)
85129921a8fSScott Kruger    return dataDict
85229921a8fSScott Kruger
853b0790570SJed Brown  def gen_gnumake(self, fd):
85429921a8fSScott Kruger    """
85529921a8fSScott Kruger     Overwrite of the method in the base PETSc class
85629921a8fSScott Kruger    """
85729921a8fSScott Kruger    def write(stem, srcs):
85829921a8fSScott Kruger      for lang in LANGS:
8592ae8c56aSScott Kruger        if srcs[lang]['srcs']:
86029921a8fSScott Kruger          fd.write('%(stem)s.%(lang)s := %(srcs)s\n' % dict(stem=stem, lang=lang, srcs=' '.join(srcs[lang]['srcs'])))
86129921a8fSScott Kruger    for pkg in PKGS:
86229921a8fSScott Kruger        srcs = self.gen_pkg(pkg)
863b0790570SJed Brown        write('testsrcs-' + pkg, srcs)
8642ae8c56aSScott Kruger        # Handle dependencies
8652ae8c56aSScott Kruger        for lang in LANGS:
8662ae8c56aSScott Kruger            for exfile in srcs[lang]['srcs']:
8672ae8c56aSScott Kruger                if exfile in srcs[lang]:
8682ae8c56aSScott Kruger                    ex='$(TESTDIR)/'+os.path.splitext(exfile)[0]
8692ae8c56aSScott Kruger                    exfo='$(TESTDIR)/'+os.path.splitext(exfile)[0]+'.o'
87049defe6fSJed Brown                    deps = [os.path.join('$(TESTDIR)', dep) for dep in srcs[lang][exfile]]
87149defe6fSJed Brown                    if deps:
87249defe6fSJed Brown                        # The executable literally depends on the object file because it is linked
87349defe6fSJed Brown                        fd.write(ex   +": " + " ".join(deps) +'\n')
87449defe6fSJed Brown                        # The object file containing 'main' does not normally depend on other object
87549defe6fSJed Brown                        # files, but it does when it includes their modules.  This dependency is
87649defe6fSJed Brown                        # overly blunt and could be reduced to only depend on object files for
87749defe6fSJed Brown                        # modules that are used, like "*f90aux.o".
87849defe6fSJed Brown                        fd.write(exfo +": " + " ".join(deps) +'\n')
8792ae8c56aSScott Kruger
88029921a8fSScott Kruger    return self.gendeps
88129921a8fSScott Kruger
88229921a8fSScott Kruger  def gen_pkg(self, pkg):
88329921a8fSScott Kruger    """
88429921a8fSScott Kruger     Overwrite of the method in the base PETSc class
88529921a8fSScott Kruger    """
88629921a8fSScott Kruger    return self.sources[pkg]
88729921a8fSScott Kruger
8888e69c5ecSJed Brown  def write_gnumake(self, dataDict, output=None):
88929921a8fSScott Kruger    """
89029921a8fSScott Kruger     Write out something similar to files from gmakegen.py
89129921a8fSScott Kruger
89229921a8fSScott Kruger     Test depends on script which also depends on source
89329921a8fSScott Kruger     file, but since I don't have a good way generating
89429921a8fSScott Kruger     acting on a single file (oops) just depend on
89529921a8fSScott Kruger     executable which in turn will depend on src file
89629921a8fSScott Kruger    """
89768f6ad6bSScott Kruger    # Different options for how to set up the targets
89868f6ad6bSScott Kruger    compileExecsFirst=False
89968f6ad6bSScott Kruger
90029921a8fSScott Kruger    # Open file
9018e69c5ecSJed Brown    fd = open(output, 'w')
90229921a8fSScott Kruger
90329921a8fSScott Kruger    # Write out the sources
904b0790570SJed Brown    gendeps = self.gen_gnumake(fd)
90529921a8fSScott Kruger
90629921a8fSScott Kruger    # Write out the tests and execname targets
90729921a8fSScott Kruger    fd.write("\n#Tests and executables\n")    # Delimiter
90829921a8fSScott Kruger
90929921a8fSScott Kruger    for pkg in PKGS:
91029921a8fSScott Kruger      # These grab the ones that are built
91129921a8fSScott Kruger      for lang in LANGS:
91285a27222SJed Brown        testdeps=[]
91329921a8fSScott Kruger        for ftest in self.tests[pkg][lang]:
91429921a8fSScott Kruger          test=os.path.basename(ftest)
91529921a8fSScott Kruger          basedir=os.path.dirname(ftest)
91685a27222SJed Brown          testdeps.append(self.nameSpace(test,basedir))
917612eee3eSJed Brown        fd.write("test-"+pkg+"."+lang+" := "+' '.join(testdeps)+"\n")
91865ea9442SJed Brown        fd.write('test-%s.%s : $(test-%s.%s)\n' % (pkg, lang, pkg, lang))
91929921a8fSScott Kruger
92029921a8fSScott Kruger        # test targets
92129921a8fSScott Kruger        for ftest in self.tests[pkg][lang]:
92229921a8fSScott Kruger          test=os.path.basename(ftest)
92329921a8fSScott Kruger          basedir=os.path.dirname(ftest)
92429921a8fSScott Kruger          testdir="${TESTDIR}/"+basedir+"/"
92529921a8fSScott Kruger          nmtest=self.nameSpace(test,basedir)
92629921a8fSScott Kruger          rundir=os.path.join(testdir,test)
92729921a8fSScott Kruger          script=test+".sh"
92829921a8fSScott Kruger
92929921a8fSScott Kruger          # Deps
93029921a8fSScott Kruger          exfile=self.tests[pkg][lang][ftest]['exfile']
93194666443SJed Brown          fullex=os.path.join(self.srcdir,exfile)
93229921a8fSScott Kruger          localexec=self.tests[pkg][lang][ftest]['exec']
93329921a8fSScott Kruger          execname=os.path.join(testdir,localexec)
93468f6ad6bSScott Kruger          fullscript=os.path.join(testdir,script)
93568f6ad6bSScott Kruger          tmpfile=os.path.join(testdir,test,test+".tmp")
93629921a8fSScott Kruger
937b91d4a07SJed Brown          # *.counts depends on the script and either executable (will
938b91d4a07SJed Brown          # be run) or the example source file (SKIP or TODO)
939fa9d32b8SSatish Balay          fd.write('%s.counts : %s %s'
940b91d4a07SJed Brown              % (os.path.join('$(TESTDIR)/counts', nmtest),
941b91d4a07SJed Brown                 fullscript,
9424fedfc52SScott Kruger                 execname if exfile in self.sources[pkg][lang]['srcs'] else fullex)
9434fedfc52SScott Kruger              )
944fa9d32b8SSatish Balay          if exfile in self.sources[pkg][lang]:
945fa9d32b8SSatish Balay            for dep in self.sources[pkg][lang][exfile]:
946fa9d32b8SSatish Balay              fd.write(' %s' % os.path.join('$(TESTDIR)',dep))
947fa9d32b8SSatish Balay          fd.write('\n')
9484fedfc52SScott Kruger
94929921a8fSScott Kruger          # Now write the args:
950612eee3eSJed Brown          fd.write(nmtest+"_ARGS := '"+self.tests[pkg][lang][ftest]['argLabel']+"'\n")
951df2e1f37SScott Kruger
952612eee3eSJed Brown    fd.close()
95329921a8fSScott Kruger    return
95429921a8fSScott Kruger
9558e69c5ecSJed Browndef main(petsc_dir=None, petsc_arch=None, verbose=False, single_ex=False, srcdir=None, testdir=None):
956c173c275SScott Kruger    # Allow petsc_arch to have both petsc_dir and petsc_arch for convenience
957add6df95SStefano Zampini    testdir=os.path.normpath(testdir)
958cadd188bSScott Kruger    if petsc_arch:
959add6df95SStefano Zampini        petsc_arch=petsc_arch.rstrip(os.path.sep)
960c173c275SScott Kruger        if len(petsc_arch.split(os.path.sep))>1:
961add6df95SStefano Zampini            petsc_dir,petsc_arch=os.path.split(petsc_arch)
9628e69c5ecSJed Brown    output = os.path.join(testdir, 'testfiles')
96329921a8fSScott Kruger
964e551db17SScott Kruger    pEx=generateExamples(petsc_dir=petsc_dir, petsc_arch=petsc_arch,
965e551db17SScott Kruger                         verbose=verbose, single_ex=single_ex, srcdir=srcdir,
966e551db17SScott Kruger                         testdir=testdir)
967cadd188bSScott Kruger    dataDict=pEx.walktree(os.path.join(pEx.srcdir))
9688e69c5ecSJed Brown    pEx.write_gnumake(dataDict, output)
96929921a8fSScott Kruger
97029921a8fSScott Krugerif __name__ == '__main__':
97129921a8fSScott Kruger    import optparse
97229921a8fSScott Kruger    parser = optparse.OptionParser()
97329921a8fSScott Kruger    parser.add_option('--verbose', help='Show mismatches between makefiles and the filesystem', action='store_true', default=False)
9744ff3c6a1SScott Kruger    parser.add_option('--petsc-dir', help='Set PETSC_DIR different from environment', default=os.environ.get('PETSC_DIR'))
97529921a8fSScott Kruger    parser.add_option('--petsc-arch', help='Set PETSC_ARCH different from environment', default=os.environ.get('PETSC_ARCH'))
976e551db17SScott Kruger    parser.add_option('--srcdir', help='Set location of sources different from PETSC_DIR/src', default=None)
97729921a8fSScott Kruger    parser.add_option('-s', '--single_executable', dest='single_executable', action="store_false", help='Whether there should be single executable per src subdir.  Default is false')
9788e69c5ecSJed Brown    parser.add_option('-t', '--testdir', dest='testdir',  help='Test directory [$PETSC_ARCH/tests]')
9794ff3c6a1SScott Kruger
98029921a8fSScott Kruger    opts, extra_args = parser.parse_args()
98129921a8fSScott Kruger    if extra_args:
98229921a8fSScott Kruger        import sys
98329921a8fSScott Kruger        sys.stderr.write('Unknown arguments: %s\n' % ' '.join(extra_args))
98429921a8fSScott Kruger        exit(1)
9858e69c5ecSJed Brown    if opts.testdir is None:
9868e69c5ecSJed Brown      opts.testdir = os.path.join(opts.petsc_arch, 'tests')
9874ff3c6a1SScott Kruger
9884ff3c6a1SScott Kruger    main(petsc_dir=opts.petsc_dir, petsc_arch=opts.petsc_arch,
9898e69c5ecSJed Brown         verbose=opts.verbose,
9904ff3c6a1SScott Kruger         single_ex=opts.single_executable, srcdir=opts.srcdir,
9914ff3c6a1SScott Kruger         testdir=opts.testdir)
992