Next / Previous / Contents / TCC Help System / NM Tech homepage

4.5.  writeAllFiles(): Generate the output files

Because code fragments for several different output files may be interwoven through the input, we must do the generation of output files in two steps:

  1. Go through the set of code fragments and find all the different output file names used.

  2. For each output file name, assemble all the fragments for that file and then write them to the file.

Here's the function header:


# - - -   w r i t e A l l F i l e s   - - -

def writeAllFiles ( fragList ):
    """Assemble the fragments into their respective files.

      [ fragList is a node-set of programlisting DOM Element nodes
        with role attributes ->
          writeable files named in role attributes of fragList  :=
              text descendants of corresponding nodes in fragList ]
          sys.stderr  +:=  error message for unwriteable files ]
    """
      

Python's dictionary and list types make it easy to build a data structure containing all the code fragments in a convenient form. We call a function buildFragMap to build and return a dictionary whose keys are the different output file names. For each key, the corresponding value is a list containing all the programlisting element nodes that are directed to that output file.

    #-- 1 --
    # [ fragMap  :=  a dictionary mapping unique output file names
    #       from role attributes in fragList |-> lists of corresponding
    #       programlisting nodes from fragList ]
    fragMap  =  buildFragMap ( fragList )
      

The rest of the job just consists of going through the dictionary, one file name at a time, and passing that file name and the corresponding list of nodes to the writeFile() function to generate the actual output file:

    #-- 2 --
    # [ fragMap is a dictionary mapping unique output file names
    #   from role attributes in fragList |-> lists of corresponding
    #   programlisting nodes from fragList ->
    #     writeable files whose names are keys in fragMap  :=
    #       text descendants of the corresponding values from fragMap
    #       in document order ]
    for fileName in fragMap.keys():
        #-- 2 body --
        # [ if fileName is writeable ->
        #     file fileName  :=  text descendants of fragMap[fileName]
        #                        in document order
        #   else ->
        #     sys.stderr  +:=  error message ]
        writeFile ( fileName, fragMap[fileName] )