Пример #1
0
def getFilesToProcess(rule, dirObj):
    """
    Get the files to process by expanding the expressions in "files" and
    concatenating the src_dir as prefix.
    """

    # Safety guard, if srcFiles is empty, no need to proceed. Silence.
    srcFiles = dirObj.getProperty(rule, 'files').split()
    if srcFiles == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return []

    srcDir = dirObj.getProperty(rule, 'src_dir')
    toProcess = []
    for srcFile in srcFiles:
        found = glob.glob(os.path.join(srcDir, srcFile))

        # Something was given in the variable, but nothing was found. Warn the
        # user but proceed.
        if found == []:
            print i18n.get('file_not_found').format(srcFile)
            # Exiting here sometimes is needed (i.e. when searching for a source
            # file to process) and sometimes it's ok (i.e. when searching for
            # files to export). There should be a boolean to select either
            # behavior
            # sys.exit(1)

        toProcess.extend(found)

    return toProcess
Пример #2
0
def doClean(rule, dirObj, toProcess, srcDir, dstDir):
    """
    Function to execute the core of the clean operation. It is in its own
    function because it is used also by the export rule.
    """

    # Identical source and destination, useless operation
    if os.path.abspath(srcDir) == os.path.abspath(dstDir):
        return

    for datafile in toProcess:

        adagio.logDebug(rule, dirObj, ' EXEC ' + datafile)

        # If file not found, terminate
        if not os.path.exists(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Remove the srcDir prefix
        dstFile = datafile.replace(srcDir, '', 1)
        # If the result has a slash, remove it
        if dstFile[0] == '/':
            dstFile = dstFile[1:]
        # Derive the destination file name
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        # If file is not there, bypass
        if not os.path.exists(dstFile):
            continue

        # Proceed with the cleaning (dump the file name being deleted)
        rules.remove(dstFile)
Пример #3
0
    def dumpOptions(self, rule, prefix):
        """
        Print the value of the options affecting the computations
        """


        # Remove the .vars from the end of the rule to fish for options
        rule = re.sub('\.?vars$', '', rule)
        if rule == '':
            rule = prefix
        basicPrefix = rule.split('.')[0]

        # Concatenate all the variable values and pass through pager (skip help
        # because it is supposed to be printed outside this function)
        str = i18n.get('var_preamble').format(prefix) + '\n\n'
        for (on, ov) in sorted(self.options.items(rule)):
            if on == 'help':
                continue
            
            # Get the help_message from the global dict (try first with the rule
            # name, and if not found, without it to find generic variables)
            help_message = adagio.variable_help_messages.get(basicPrefix + 
                                                             '.' + on)
            if help_message == None:
                help_message = adagio.variable_help_messages.get(on)

            # Create the string: value + help message
            str += ' - ' + on + ' = ' + ov + '\n'
            if help_message != None:
                str += '   ' + help_message + '\n\n'
            else:
                str += '   ' + i18n.get('user_defined_variable') + '\n\n'

        return str
Пример #4
0
def Execute(rule, dirObj, pad = None):
    """
    Execute the rule in the given directory
    """

    if pad == 'None':
        pad = ''

    (toProcess, remoteRules,
     optionsToSet, newExportDir) = prepareRule(rule, dirObj)

    # Loop over each directory
    for dirName in toProcess:
        adagio.logInfo(rule, dirObj, 'RECUR: ' + dirName)
        if not os.path.isdir(dirName):
            print i18n.get('not_a_directory').format(dirName)
            sys.exit(1)
        remoteDir = directory.getDirectoryObject(dirName, optionsToSet)

	if remoteDir.rule_list == []:
	    # If rule_list is empty, there is no Properties.dgo in that dir, skip execution
            continue

        # Execute the targets in the remote directory
        remoteDir.Execute(remoteRules, pad + '  ')

    return
Пример #5
0
   def checkCreateErroneousRule(self, ruleName, ruleDescription, ruleCode, ruleLog):
      print '  Check notifications'
      notification.waitText(self.browser, notification.Type.Success, i18n.get()["modals"]["dashboard"]["sub-windows"]["automation-center"]["ruleSuccessfullyCreated"])
      notification.waitSubText(self.browser, notification.Type.Error, i18n.get()["eventLogger"]["RuleFailed"].replace("__who__", ruleName))
      
      print '  Check rule was inserted in rules table'
      rulesTable = dashboard.automation.waitRulesTableHasNRules(self.browser, 1)

      ruleNumber = 0
      
      print '  Check rule data in rules table'
      self.assertEqual(len(dashboard.automation.getRuleDatas(rulesTable, ruleNumber)), 5)
      self.assertEqual(dashboard.automation.getRuleName(rulesTable, ruleNumber), ruleName)
      self.assertEqual(dashboard.automation.getRuleDescription(rulesTable, ruleNumber), ruleDescription)
      self.assertTrue(dashboard.automation.getRuleAutoStart(rulesTable, ruleNumber))

      buttons = dashboard.automation.getRuleButtons(rulesTable, ruleNumber)
      self.assertEqual(len(buttons), 4)
      self.assertTrue(tools.waitUntil(lambda: dashboard.automation.getRuleStartStopButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-enableDisable btn-success"))
      self.assertEqual(dashboard.automation.getRuleEditButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-edit btn-primary")
      self.assertEqual(dashboard.automation.getRuleRemoveButton(rulesTable, ruleNumber).get_attribute("class"), "btn btn-delete btn-danger")
      
      self.assertTrue(tools.waitUntil(lambda: dashboard.automation.getRuleState(rulesTable, ruleNumber) == dashboard.automation.RuleState.Error))
      
      print '  Check rule was created on disk (corresponding script file)'
      self.assertTrue(scripts.checkLocalRuleCodeById(1, ruleCode))
      self.assertTrue(tools.waitUntil(lambda: scripts.checkLocalRuleLogById(1, ruleLog)))
def __validate_environment():
   '''
   Checks to see if the current environment is valid to run this script in.
   If it is not, an error message is displayed to explain the problem.
   
   Returns True if the current environment is valid, False if it is not.
   '''
   
   # the minimum versions required for a valid environment
   REQUIRED_MAJOR=0
   REQUIRED_MINOR=9
   REQUIRED_BUILD=165
   
   valid_environment = True
   try:
      version = re.split(r'\.', ComicRack.App.ProductVersion) 
      def hash( major, minor, build ):
         return float(sstr(major * 5000 + minor) + "." + sstr(build)) 
      
      valid_environment = \
         hash(int(version[0]),int(version[1]), int(version[2])) >= \
            hash(REQUIRED_MAJOR, REQUIRED_MINOR, REQUIRED_BUILD)
         
      if not valid_environment:
         log.debug("WARNING: script requires ComicRack ", REQUIRED_MAJOR, '.',
            REQUIRED_MINOR, '.', REQUIRED_BUILD, ' or higher.  Exiting...')
         MessageBox.Show( ComicRack.MainWindow, i18n.get("ComicRackOODText"),
            i18n.get("ComicRackOODTitle"), MessageBoxButtons.OK, 
            MessageBoxIcon.Warning)
         
   except:
      log.debug_exc("WARNING: couldn't validate comicrack version")
      valid_environment = True
      
   return valid_environment
Пример #7
0
def clean(rule, dirObj):
    """
    Clean the files produced by this rule
    """
    
    adagio.logInfo(rule, dirObj, 'Cleaning')

    # Get the files to process
    toProcess = glob.glob(os.path.join(dirObj.current_dir, '*.xcf'))
    if toProcess == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return

    # Loop over the source files to see if an execution is needed
    dstFiles = []
    dstDir = dirObj.getProperty(rule, 'src_dir')
    for datafile in toProcess:

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFile = os.path.splitext(os.path.basename(datafile))[0] + '.png'
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        if not os.path.exists(dstFile):
            continue

        rules.remove(dstFile)

    return
Пример #8
0
def getProperty(config, rule, option):
    """
    Function that given a rule name of the form 'a.b.c.d' and an option name,
    gets the value obtained from the given config. The procedure works
    hierarchically. It first checks for the option value in the given rule,
    and if not found, it keeps asking for the values in the rules obtained by
    dropping the last suffix (from the last dot until the end of the rule
    name.
    """

    global _adagio_given_definiton_rule_name

    # If the rule is a.b.c, loop asking if we have the option a.b.c.option,
    # then a.b.option, and then a.option.
    partialRule = rule
    while partialRule != '':
        if config.has_option(_adagio_given_definiton_rule_name,
                             partialRule + '.' + option):
            result = config.get(partialRule, option)
            return result
        partialRule = partialRule.rpartition('.')[0]

    # If no hit so far, need to make one more test to see if the value is in the
    # DEFAULT rule
    try:
        result = config.get(rule, option)
        # Yes, the value is stored as in  DEFAULT
        return result
    except ConfigParser.InterpolationMissingOptionError, e:
        print i18n.get('incorrect_variable_reference').format(option)
        sys.exit(1)
Пример #9
0
def clean(rule, dirObj):
    """
    Clean the files produced by this rule
    """

    adagio.logInfo(rule, dirObj, 'Cleaning')

    # Get the files to process
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        return

    # Loop over all source files to process
    dstDir = dirObj.getProperty(rule, 'dst_dir')
    nupOption = dirObj.getProperty(rule, 'nup')
    for datafile in toProcess:

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFile = os.path.splitext(os.path.basename(datafile))[0] + \
            '-' + nupOption + os.path.splitext(os.path.basename(datafile))[1]
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        if not os.path.exists(dstFile):
            continue

        rules.remove(dstFile)

    return
Пример #10
0
def findOrAddTransform(styleFile, styleList, paths = None):
    """
    Simple dictionary storing XSL Transforms. The key is the given styleFile (which
    could be a string)
    """
    global _createdTransforms
    global _xml_parser
    
    theKey = ' '.join(styleList)

    # Get the last modification time of the given file to detect changes. First
    # filter files because there could be some URLs
    fileStyleList = [x for x in styleList if os.path.exists(x)]
    ftime = sys.float_info.max
    if fileStyleList != []:
        ftime = max([os.path.getmtime(x) for x in fileStyleList])

    (transform, tstamp) = _createdTransforms.get(theKey, (None, None))
    if (transform != None) and (ftime <= tstamp):
        # HIT
        adagio.logDebug('treecache', None, 'HIT: ' + str(styleFile))
        return transform

    # expand includes and create transformation object
    try:
        transform = etree.parse(styleFile, _xml_parser)
    except etree.XMLSyntaxError, e:
        print i18n.get('severe_parse_error').format(styleFile)
        print str(e)
        sys.exit(1)
Пример #11
0
def obtainXincludes(files):
    """
    Obtain the files included using xinclude in the given file. Return a list
    with the absolute filenames
    """

    # Remember the old current directory because we are going to modify it
    old_cwd = os.getcwd()

    result = set([])
    for fileName in files:
        # We only accept absolute paths
        if not os.path.isabs(fileName):
            fileName = os.path.abspath(fileName)

        # Get the directory where the file is located and change cwd
        fDir = os.path.dirname(fileName)
	os.chdir(fDir)

        # Get the file parsed without expanding the xincludes
        root = treecache.findOrAddTree(fileName, False)

        # Path to locate the includes and dir of the given file
        includePath = '//{http://www.w3.org/2001/XInclude}include'

        # Obtain the included files
        includeFiles = \
            set([os.path.join(
                    x.attrib.get('{http://www.w3.org/XML/1998/namespace}base',
                                 ''),
                    x.attrib.get('href'))
                 for x in root.findall(includePath)
                 if x.attrib.get('href') != None and \
                     (x.attrib.get('parse') == None or
                      x.attrib.get('parse') == 'xml')])

        # Traverse all the include files
        for includeFile in includeFiles:
            # Locate the file applying Adagio search rules
            # locatedFile = dependency.locateFile(includeFile, [fDir])
            locatedFile = treecache.xml_resolver.resolve_file(includeFile)

            # If not found, notify and terminate
            if locatedFile == None:
                print i18n.get('file_not_found').format(includeFile)
                print i18n.get('included_from'), fileName
                sys.exit(1)

            if os.path.dirname(os.path.abspath(locatedFile)) == fDir:
                # If it is in the same dir, prepare to traverse
                files.append(locatedFile)
            else:
                # If in another dir, append to the result
                result.add(os.path.abspath(locatedFile))

    # restore the original cwd
    os.chdir(old_cwd)

    return result
Пример #12
0
def Execute(rule, dirObj):
    """
    Execute the rule in the given directory
    """

    global has_executable

    if has_executable == '':
	has_executable = adagio.findExecutable(rule, dirObj)

    # If the executable is not present, notify and terminate
    if not has_executable:
        print i18n.get('no_executable').format(dirObj.options.get(rule, 'exec'))
        if dirObj.options.get(rule, 'partial') == '0':
            sys.exit(1)
        return

    # Get the files to process, if empty, terminate
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return

    # Loop over all source files to process
    executable = dirObj.getProperty(rule, 'exec')
    extraArgs = dirObj.getProperty(rule, 'extra_arguments')
    # The command is soffice --nologo --invisible --headless
    #                        --convert-to pdf *.doc
    command = [executable, '--nologo', '--invisible', '--headless',
               '--convert-to', 'pdf']
    command.extend(extraArgs.split())
    dstDir = dirObj.getProperty(rule, 'src_dir')
    for datafile in toProcess:
        adagio.logDebug(rule, dirObj, ' EXEC ' + datafile)

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFileName = os.path.splitext(os.path.basename(datafile))[0] + \
            '.pdf'
        dstFile = os.path.abspath(os.path.join(dstDir, dstFileName))

        # Perform the execution
        command.append(datafile)
        # command.append('macro:///Tools.MSToPDF.ConvertMSToPDF(' + datafile + ')')

        rules.doExecution(rule, dirObj, command, datafile, dstFile,
                            stdout = adagio.userLog)
        command.pop(-1)

    # End of loop over all src files

    return
Пример #13
0
    def __init__(self, path = os.getcwd(), givenOptions = []):
        # Initial values
        self.previous_dir =   os.getcwd()
        self.current_dir =    os.path.abspath(path)
        self.givenOptions =   ''
        self.options =        None
        self.rule_list =      []
        self.alias =          {}
        self.current_rule =   None
        self.executing =      False
        self.executed_rules = set([])
        self.option_files =   set([])

        adagio.logInfo('Directory', None, 
                       'New dir object in ' + self.current_dir)

        configDefaults = adagio.getConfigDefaults(self.current_dir)

        # Compute the project home
        os.chdir(self.current_dir)
        detected_project_home = findProjectDir(configDefaults['project_file'], 
                                               self.current_dir)
        configDefaults['project_home'] = detected_project_home
        os.chdir(self.previous_dir)

        # Compute the relative_basedir (relative path from basedir to
        # project_home
        configDefaults['relative_basedir'] = \
            os.path.relpath(self.current_dir, detected_project_home)

        # Safe parser to store the options, the defaults are loaded here
        self.options = properties.initialConfig(configDefaults)

        #
        # STEP 1: Load the default options from the Rule files
        #
        adagio.LoadDefaults(self.options)

        #
        # STEP 2: Load the ~/.adagiorc if any
        #
        userAdagioConfig = os.path.normpath(os.path.join(os.path.expanduser('~'),
                                                         '.adagiorc'))
        if os.path.isfile(userAdagioConfig):
            # Swallow user file on top of global options, and if trouble, report
            # up
            try:
                (newFiles, b) = properties.loadConfigFile(self.options,
                                                          userAdagioConfig,
                                                          self.alias)
                self.option_files.update(newFiles)
            except ValueError, e:
                print i18n.get('severe_parse_error').format(userAdagioConfig)
                print str(e)
                sys.exit(3)
Пример #14
0
def prepareRule(rule, dirObj):
    """
    Obtain the directories to process, calculate the options to set in the
    remote execution and obtain the remote rules.

    Return:

    (list of dirs to process, remote rules, options to set in the remote exec)
    """

    # Get the directories to process from the files option
    toProcess = []
    for srcDir in dirObj.getProperty(rule, 'files').split():
        newDirs = glob.glob(srcDir)
        if newDirs == []:
            print i18n.get('file_not_found').format(srcDir)
            sys.exit(1)
        toProcess.extend(glob.glob(srcDir))

    # Add the files included in files_included_from
    filesIncluded = \
        obtainXincludes(dirObj.getProperty(rule, 'files_included_from').split())

    # The list of dirs is extended with a set to avoid duplications
    toProcess.extend(set(map(lambda x: os.path.dirname(x), filesIncluded)))

    # If there are no files to process stop
    if toProcess == []:
        adagio.logDebug(rule, dirObj, i18n.get('no_file_to_process'))
        return (toProcess, [], None, '')

    # Translate all paths to absolute paths
    toProcess = map(lambda x: os.path.abspath(x), toProcess)

    # Rules to execute in the remote directory
    remoteRules = dirObj.getProperty(rule, 'rules').split()

    # Create the option dict for the remote directories
    optionsToSet = []
    newExportDir = dirObj.getProperty(rule, 'export_dst')
    if newExportDir != '':
        # If a new dst_dir has been specified, include the options to modify
        # that variable for each of the rules
        if remoteRules != []:
            # If there are some given rules, use them
            optionsToSet = [x + ' dst_dir ' + newExportDir
                            for x in remoteRules if x.startswith('export')]
        else:
            # If no rule is given, leave the option in the export.dst_dir
            # to its default value default
            optionsToSet = ['export dst_dir ' + newExportDir]

    adagio.logInfo(rule, dirObj, 'NEW Options = ' + ', '.join(optionsToSet))

    return (toProcess, remoteRules, optionsToSet, newExportDir)
Пример #15
0
def Execute(rule, dirObj):
    """
    Execute the rule in the given directory
    """

    global has_executable

    if has_executable == '':
	has_executable = adagio.findExecutable(rule, dirObj)

    # If the executable is not present, notify and terminate
    if not has_executable:
        print i18n.get('no_executable').format(dirObj.options.get(rule, 'exec'))
        if dirObj.options.get(rule, 'partial') == '0':
            sys.exit(1)
        return

    # Get the files to process, if empty, terminate
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        return


    # Prepare the command to execute
    executable = dirObj.getProperty(rule, 'exec')
    dstDir = dirObj.getProperty(rule, 'dst_dir')
    nupOption = dirObj.getProperty(rule, 'nup')
    # Loop over all source files to process
    for datafile in toProcess:
        adagio.logDebug(rule, dirObj, ' EXEC ' + datafile)

        # If file not found, terminate
        if not os.path.isfile(datafile):
            print i18n.get('file_not_found').format(datafile)
            sys.exit(1)

        # Derive the destination file name
        dstFile = os.path.splitext(os.path.basename(datafile))[0] + \
            '-' + nupOption + os.path.splitext(os.path.basename(datafile))[1]
        dstFile = os.path.abspath(os.path.join(dstDir, dstFile))

        # Add the input file to the command
        command = [executable]
        if nupOption != '':
            command.extend(['--outfile', dstFile])
        command.extend(dirObj.getProperty(rule,
                                                'extra_arguments').split())
        command.append(datafile)

        # Perform the execution
        rules.doExecution(rule, dirObj, command, datafile, dstFile,
                            adagio.userLog, adagio.userLog)

    return
Пример #16
0
 def delegate():
    # NOTE: now we're on the ComicForm Application Thread
    self.__current_book = book
    self.__current_page = 0
    self.__current_page_count = page_count
    self.__label.Text = i18n.get("ComicFormScrapingLabel") + book_name
    self.__pbox_panel.set_image(page_image) # cover image may be None
    self.__progbar.PerformStep()
    self.__progbar.Maximum = self.__progbar.Value + num_remaining
    self.__cancel_button.Text=\
       i18n.get("ComicFormCancelButton").format(sstr(num_remaining))
    self.Update()
Пример #17
0
def treatTemplate(config, filename, newOptions, sname, aliasDict, includeChain):
    """
    Process template and parse the required files.

    - Config what you have so far
    - filename file where the template is found
    - NewOptions is the new config
    - sname is the rule name where the template was detected
    - includeChain are the files that are included

    Returns the pair (set of files processed, list of rules detected)
    """

    # Get the pairs in the template rule that are not in the defaults
    # dictionary
    fileItem = [(a, b) for (a, b) in newOptions.items(sname)
                if not a in newOptions.defaults()]

    # There must be a single option with name 'files'
    if len(fileItem) != 1:
        print i18n.get('template_error').format(filename)
        sys.exit(1)

    # The option must have name files
    if fileItem[0][0] != 'files':
        print i18n.get('incorrect_option_in_file').format(fileItem[0][0],
                                                          filename)
        sys.exit(1)

    # Add template rule to the given config to evaluate the files assignment
    templateFiles = setProperty(config, sname, 'files', fileItem[0][1],
                                fileName = filename,
                                createRule = True,
                                createOption = True).split()

    # Remove rule from the original config:
    config.remove_section(sname)

    # Process the template files recursively!
    result = (set([]), [])
    for fname in templateFiles:
        # Get the full path of the template
        if os.path.isabs(fname):
            templateFile = fname
        else:
            templateFile = os.path.abspath(os.path.join(os.path.dirname(filename), fname))

        (a, b) = loadConfigFile(config, 
                                os.path.normpath(templateFile), 
                                aliasDict, includeChain)
        result[0].update(a)
        result[1].extend(b)
    return result
Пример #18
0
def checkDateFormat(d, f):
    """
    Check if the date d is compliant with the format f. If not, terminate with a
    message.

    Returns the datetime object with the date
    """
    try:
       result = datetime.datetime.strptime(d, f)
    except ValueError, e:
       print i18n.get('date_incorrect_format').format(d, f)
       print str(e)
       sys.exit(1)
Пример #19
0
def doShuffle(toProcess, dirObj):
    # Every source file given is processed to know how many permutations will be
    # produced.
    rawFiles = []
    for fname in toProcess:
        # Get the result files
        resultFiles = doGetShuffledFiles(fname)

        # Accumulate the list
        rawFiles.extend(resultFiles)

        # Update the dependencies (apply update to all elements in resultFiles)
        try:
            sources = set([fname])
            sources.update(dirObj.option_files)
            map(lambda x: dependency.update(x, sources), resultFiles)
        except etree.XMLSyntaxError, e:
            print i18n.get('severe_parse_error').format(fName)
            print e
            sys.exit(1)

        # If all the permutation files are up to date, no need to process
        if reduce(lambda x, y: x and y,
                  [dependency.isUpToDate(x) for x in resultFiles]):
            print i18n.get('testexam_no_shuffle_required').format(fname)
            continue

        print i18n.get('testexam_shuffling').format(fname)
        permutations = testshuffle.main(fname, adagio.userLog)

        if permutations == 0:
            print i18n.get('testexam_no_permutations').format(fname)
            sys.exit(1)
Пример #20
0
   def __build_skip_label(self, skipped_n):
      ''' 
      Builds and returns the 'number skipped' Label for this form.
      'skipped_n' -> the number of books that were skipped. 
      '''

      label = Label()
      label.UseMnemonic = False
      label.Location = Point(10, 30) 
      label.Size = Size(280, 13)
      label.TextAlign = ContentAlignment.MiddleCenter
      label.Text = i18n.get("FinishFormSkippedSingle") if skipped_n==1 else \
         i18n.get("FinishFormSkippedPlural").format(skipped_n)
      return label
Пример #21
0
def Execute(rule, dirObj):
    """
    Execute the rule in the given directory
    """

    # Get the files to process, if empty, terminate
    toProcess = rules.getFilesToProcess(rule, dirObj)
    if toProcess == []:
        return

    # Every source file given is processed to know how many permutations will be
    # rawFiles contains the list of files produced that need to be processed
    rawFiles = doShuffle(toProcess, dirObj)

    # Prepare the style transformation
    styleFiles = dirObj.getProperty(rule, 'styles')
    styleTransform = xsltproc.createStyleTransform(styleFiles.split())
    if styleTransform == None:
        print i18n.get('no_style_file')
        return

    # Create the dictionary of stylesheet parameters
    styleParams = xsltproc.createParameterDict(rule, dirObj)

    # Create a list with the param dictionaries to use in the different versions
    # to be created.
    paramDict = []
    produceValues = set(dirObj.getProperty(rule, 'produce').split())
    if 'regular' in produceValues:
        # Create the regular version, no additional parameters needed
        paramDict.append(({}, ''))
    if 'solution' in produceValues:
        paramDict.append(({'solutions.include.guide': "'yes'",
                           'adagio.testquestions.include.solutions': "'yes'"},
                          '_solution'))
    if 'pguide' in produceValues:
        paramDict.append(({'solutions.include.guide': "'yes'",
                           'adagio.testquestions.include.solutions': "'yes'",
                           'professorguide.include.guide': "'yes'",
                           'adagio.testquestions.include.id': "'yes'",
                           'adagio.testquestions.include.history': "'yes'"},
                          '_pguide'))

    # Apply all these transformations.
    xsltproc.doTransformations(styleFiles.split(), styleTransform, styleParams,
                               rawFiles, rule, dirObj, paramDict)

    return
Пример #22
0
def setProperty(config, rule, option, value, fileName = None,
                createRule = None, createOption = None):
    """
    Function that sets the given value for the rule.option in the given
    config and returns the resulting value (after interpolation). createRule
    and createOption is the boolean allowing the creation of both.
    """

    # Obtain the rule prefix
    rulePrefix = rule.split('.')[0]

    # Check if the rule is allowed,
    if (not createRule) and (not config.has_section(rulePrefix)):
        # Rule prefix does not exist in config, and creation is not allowed
        raise ValueError('Rule ' + rulePrefix + ' not allowed.')

    # Create the rule if needed
    if not config.has_section(rule):
        config.add_section(rule)

    # See if the option is already present in the config
    try:
        optionPresent = True
        getProperty(config, rule, option)
    except ConfigParser.NoOptionError:
        optionPresent = False

    # Check if option is allowed
    if (not createOption) and (not optionPresent):
        # Option does not exist in config, and creation is not allowed
        raise ValueError('Option ' + option + ' not allowed.')

    # Insert the option
    config.set(rule, option, value)

    # Register the rule.option also in the __ADAGIO_GIVEN_RULE_NAME
    config.set(_adagio_given_definiton_rule_name,
               rule + '.' + option, value)

    # Get the option just inserted to verify interpolation errors
    try:
        finalValue = config.get(rule, option)
    except (ConfigParser.InterpolationDepthError,
            ConfigParser.InterpolationMissingOptionError), e:
        if fileName != None:
            print i18n.get('severe_parse_error').format(fileName)
        print i18n.get('incorrect_variable_reference').format(value)
        sys.exit(3)
Пример #23
0
def handle_error(error):
   '''
   Handles the given error object (a python or .net exception) by formatting it
   nicely and then printing it to the debug log.   If the 'app_window' provided
   to the 'install' method was not None, an "unexpected error" message 
   will also be displayed for the user in a modal dialog owned by the
   app_window.
   
   This method should be an application's normal way to handle unexpected
   errors and exceptions.
   '''
   
    
   global __logger, __app_window
   if not __logger:
      return
   
   # if none, do current python exception.  else sstr() the given exception
   if isinstance(error, Exception):
      debug("------------------- PYTHON ERROR ------------------------")
      debug_exc() # a python exception
   else:
      debug("-------------------- .NET ERROR -------------------------")
      debug(utils.sstr(error).replace('\r','')) # a .NET exception 
   
   
   if __app_window:     
      handled = False
      if type(error) == DatabaseConnectionError:  
         # if this is a DatabaseConnectionError, then it is a semi-expected 
         # error that may get a special error message
         if error.get_error_code_s() == "100": # coryhigh: i18n
            MessageBox.Show(__app_window,  # invalid api key
               i18n.get("LogDBErrorApiKeyText").format(error.get_db_name_s()), 
               i18n.get("LogDBErrorTitle"), MessageBoxButtons.OK, 
               MessageBoxIcon.Warning)
            handled = True
         elif error.get_error_code_s() == "107":
            MessageBox.Show(__app_window,  # rate limit reached
               i18n.get("LogDBErrorRateText").format(error.get_db_name_s()), 
               i18n.get("LogDBErrorTitle"), MessageBoxButtons.OK, 
               MessageBoxIcon.Warning)
            handled = True
         elif error.get_error_code_s() == "0":
            MessageBox.Show(__app_window,  # generic 
               i18n.get("LogDBErrorText").format(error.get_db_name_s()), 
               i18n.get("LogDBErrorTitle"), MessageBoxButtons.OK, 
               MessageBoxIcon.Warning)
            handled = True
         
      if not handled:
         # all other errors are considered "unexpected", and handled generically
         result = MessageBox.Show(__app_window, i18n.get("LogErrorText"),
            i18n.get("LogErrorTitle"),  MessageBoxButtons.YesNo, 
            MessageBoxIcon.Error)
      
         if result == DialogResult.Yes:
            save(True)
Пример #24
0
    def __was_deactivated(self, sender, args):
        """ Called whenever this form gets deactivated, for any reason """

        # unhighlight the skip button bold whenever we deactivate
        if self.__pressing_controlkey:
            self.__pressing_controlkey = False
            self.__skip_button.Text = i18n.get("IssueFormSkip")
Пример #25
0
    def __key_was_released(self, sender, args):
        """ Called whenever the user releases any key on this form. """

        # unhighlight the skip button bold whenever the user releases control key
        if args.KeyCode == Keys.ControlKey:
            self.__pressing_controlkey = False
            self.__skip_button.Text = i18n.get("IssueFormSkip")
Пример #26
0
    def __key_was_pressed(self, sender, args):
        """ Called whenever the user presses any key on this form. """

        # highlight the skip button whenever the user presses control key
        if args.KeyCode == Keys.ControlKey and not self.__pressing_controlkey:
            self.__pressing_controlkey = True
            self.__skip_button.Text = "- " + i18n.get("IssueFormSkip") + " -"
Пример #27
0
    def __build_label(self, series_ref):
        """ builds and returns the main text label for this form """

        # 1. compute the best possible full name for the given SeriesRef
        name_s = series_ref.series_name_s
        publisher_s = series_ref.publisher_s
        vol_year_n = series_ref.volume_year_n
        vol_year_s = sstr(vol_year_n) if vol_year_n > 0 else ""
        fullname_s = ""
        if name_s:
            if publisher_s:
                if vol_year_s:
                    fullname_s = "'" + name_s + "' (" + publisher_s + ", " + vol_year_s + ")"
                else:
                    fullname_s = "'" + name_s + "' (" + publisher_s + ")"
            else:
                fullname_s = "'" + name_s + "'"

        label = Label()
        label.UseMnemonic = False
        sep = "  " if len(fullname_s) > 40 else "\n"
        label.Text = i18n.get("IssueFormChooseText").format(fullname_s, sep)

        if self.__config.show_covers_b:
            label.Location = Point(218, 20)
            label.Size = Size(480, 40)
        else:
            label.Location = Point(10, 20)
            label.Size = Size(680, 40)

        return label
Пример #28
0
   def __build_gui(self):
      ''' Constructs and initializes the gui for this form. '''
      
      # 1. --- build each gui component
      self.__ok_button = self.__build_okbutton()
      self.__cancel_button = self.__build_cancel_button()
      self.__restore_button = self.__build_restore_button()
      self.__tabcontrol = self.__build_tabcontrol()
         
      # 2. -- configure this form, and add all the gui components to it
      self.AutoScaleMode = AutoScaleMode.Font
      self.ClientSize = Size(416, 375)
      self.Text = i18n.get("ConfigFormTitle")
   
      self.Controls.Add(self.__ok_button)                                     
      self.Controls.Add(self.__cancel_button)                                 
      self.Controls.Add(self.__restore_button)                                
      self.Controls.Add(self.__tabcontrol)                             
      
      # 3. -- define the keyboard focus tab traversal ordering
      self.__ok_button.TabIndex = 0                                        
      self.__cancel_button.TabIndex = 1                                    
      self.__restore_button.TabIndex = 2
      self.__tabcontrol.TabIndex = 3                                 

      self.__fired_update_gui()  
Пример #29
0
   def __build_label(self, books):
      ''' 
      Builds and returns the Label for this form.
      'books' -> a list of all the comic books being scraped. 
      '''

      plural = len(books) != 1
      
      label = Label()
      label.UseMnemonic = False
      label.AutoSize = True
      label.Location = Point(9, 10)
      label.Size = Size(319, 13)
      label.Text = i18n.get("WelcomeFormTextPlural").format(len(books)) \
         if plural else i18n.get("WelcomeFormTextSingle")
      return label
Пример #30
0
def versionToInteger(version):
    """
    Fucntion that given a ??.??.?? version (all digits), produces an integer.
    """

    match = re.match('^(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<pt>[0-9]+)$',
                     version)
    if not match:
        print i18n.get('incorrect_version_format').version
        sys.exit(3)

    result = 0
    result = 1000000 * int(match.group('major')) + \
        10000 * int(match.group('minor')) + int(match.group('pt'))

    return result