示例#1
0
    def runPrettyPrinting(self, classes, classesObj):
        "Gather all relevant config settings and pass them to the compiler"

        if not isinstance(self._job.get("pretty-print", False),
                          types.DictType):
            return

        self._console.info("Pretty-printing code...")
        self._console.indent()
        ppsettings = ExtMap(self._job.get(
            "pretty-print"))  # get the pretty-print config settings

        # init options
        parser = optparse.OptionParser()
        compiler.addCommandLineOptions(parser)
        (options, args) = parser.parse_args([])

        # modify according to config
        setattr(options, 'prettyPrint', True)  # turn on pretty-printing
        if ppsettings.get('general/indent-string', False):
            setattr(options, 'prettypIndentString',
                    ppsettings.get('general/indent-string'))
        if ppsettings.get('comments/trailing/keep-column', False):
            setattr(options, 'prettypCommentsTrailingKeepColumn',
                    ppsettings.get('comments/trailing/keep-column'))
        if ppsettings.get('comments/trailing/comment-cols', False):
            setattr(options, 'prettypCommentsTrailingCommentCols',
                    ppsettings.get('comments/trailing/comment-cols'))
        if ppsettings.get('comments/trailing/padding', False):
            setattr(options, 'prettypCommentsInlinePadding',
                    ppsettings.get('comments/trailing/padding'))
        if ppsettings.get('blocks/align-with-curlies', False):
            setattr(options, 'prettypAlignBlockWithCurlies',
                    ppsettings.get('blocks/align-with-curlies'))
        if ppsettings.get('blocks/open-curly/newline-before', False):
            setattr(options, 'prettypOpenCurlyNewlineBefore',
                    ppsettings.get('blocks/open-curly/newline-before'))
        if ppsettings.get('blocks/open-curly/indent-before', False):
            setattr(options, 'prettypOpenCurlyIndentBefore',
                    ppsettings.get('blocks/open-curly/indent-before'))

        self._console.info("Pretty-printing files: ", False)
        numClasses = len(classes)
        for pos, classId in enumerate(classes):
            self._console.progress(pos + 1, numClasses)
            #tree = treeLoader.getTree(classId)
            tree = classesObj[classId].tree()
            compiled = compiler.compile(tree, options)
            filetool.save(self._classes[classId]['path'], compiled)

        self._console.outdent()

        return
示例#2
0
    def runPrettyPrinting(self, classes, classesObj):
        "Gather all relevant config settings and pass them to the compiler"

        if not isinstance(self._job.get("pretty-print", False), types.DictType):
            return

        self._console.info("Pretty-printing code...")
        self._console.indent()
        ppsettings = ExtMap(self._job.get("pretty-print"))  # get the pretty-print config settings

        # init options
        parser  = optparse.OptionParser()
        compiler.addCommandLineOptions(parser)
        (options, args) = parser.parse_args([])

        # modify according to config
        setattr(options, 'prettyPrint', True)  # turn on pretty-printing
        if ppsettings.get('general/indent-string',False):
            setattr(options, 'prettypIndentString', ppsettings.get('general/indent-string'))
        if ppsettings.get('comments/trailing/keep-column',False):
            setattr(options, 'prettypCommentsTrailingKeepColumn', ppsettings.get('comments/trailing/keep-column'))
        if ppsettings.get('comments/trailing/comment-cols',False):
            setattr(options, 'prettypCommentsTrailingCommentCols', ppsettings.get('comments/trailing/comment-cols'))
        if ppsettings.get('comments/trailing/padding',False):
            setattr(options, 'prettypCommentsInlinePadding', ppsettings.get('comments/trailing/padding'))
        if ppsettings.get('blocks/align-with-curlies',False):
            setattr(options, 'prettypAlignBlockWithCurlies', ppsettings.get('blocks/align-with-curlies'))
        if ppsettings.get('blocks/open-curly/newline-before',False):
            setattr(options, 'prettypOpenCurlyNewlineBefore', ppsettings.get('blocks/open-curly/newline-before'))
        if ppsettings.get('blocks/open-curly/indent-before',False):
            setattr(options, 'prettypOpenCurlyIndentBefore', ppsettings.get('blocks/open-curly/indent-before'))

        self._console.info("Pretty-printing files: ", False)
        numClasses = len(classes)
        for pos, classId in enumerate(classes):
            self._console.progress(pos+1, numClasses)
            #tree = treeLoader.getTree(classId)
            tree = classesObj[classId].tree()
            compiled = compiler.compile(tree, options)
            filetool.save(self._classes[classId]['path'], compiled)

        self._console.outdent()

        return
示例#3
0
def main():

    parser = optparse.OptionParser("usage: %prog [options]", option_class=ExtendAction)

    migrator_options = optparse.OptionGroup(parser, "Migrator Options")
    migrator_options.add_option(
        "-m",
        "--from-makefile",
        dest="makefile",
        metavar="MAKEFILE",
        help="Makefile of the skeleton project to migrate (optional)",
    )
    migrator_options.add_option(
        "--from-version",
        dest="from_version",
        metavar="VERSION",
        default="",
        help="qooxdoo version used for the project e.g. '0.7.3'",
    )
    migrator_options.add_option(
        "--migrate-html",
        action="store_true",
        dest="migrateHtml",
        default=False,
        help="Migrates recursively all HTML files. Starting from the current directory.",
    )

    migrator_options.add_option(
        "-i",
        "--input",
        dest="file",
        metavar="FILE.js",
        help="Migrate just one JavaScript file. Writes the generated file to STDOUT.",
    )

    migrator_options.add_option(
        "--class-path",
        action="extend",
        dest="classPath",
        metavar="DIRECTORY",
        type="string",
        default=[],
        help="Define a class path.",
    )
    parser.add_option_group(migrator_options)

    # options from generator.py
    parser.add_option(
        "-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose output mode."
    )
    parser.add_option(
        "--class-encoding",
        action="extend",
        dest="classEncoding",
        metavar="ENCODING",
        type="string",
        default=[],
        help="Encoding of the files to migrate.",
    )

    # Options for pretty printing
    pp_options = optparse.OptionGroup(parser, "Pretty printer options")
    compiler.addCommandLineOptions(pp_options)
    parser.add_option_group(pp_options)

    (options, args) = parser.parse_args()

    default_old_version = "1.1"

    while options.from_version == "":
        choice = raw_input(
            """
NOTE:    To apply only the necessary changes to your project, we
         need to know the qooxdoo version it currently works with.

Please enter your current qooxdoo version [%s] : """
            % default_old_version
        )

        if choice == "":
            options.from_version = default_old_version
        elif re.match(r"\d\.\d(\.\d)?", choice):
            options.from_version = choice

    if not isValidVersion(options.from_version):
        print "\nERROR: The version '%s' is not a valid version string!\n" % options.from_version
        sys.exit(1)

    if MIGRATION_ORDER[-1] == getNormalizedVersion(options.from_version):
        print "\n Nothing to do. Your application is up to date!\n"
        sys.exit()

    # to migrate a single file extract the class path
    if options.classPath == [] and options.file:
        options.classPath = [os.path.dirname(os.path.abspath(options.file))]

    if options.classPath == []:
        print """
ERROR: The class path is empty. Please specify the class pass using the
       --class-path option
"""
        sys.exit(0)

    neededUpdates = getNeededUpdates(options.from_version)

    # check whether tree bases modifications will be used
    hasPatchModule = False
    for version in neededUpdates:
        if getPatchModulePath(version) is not None:
            hasPatchModule = True
            break

    # set options for the loader and migrator
    options.classUri = []
    options.resourceInput = []
    options.resourceOutput = []
    options.cacheDirectory = None
    options.disableInternalCheck = False
    options.prettyPrint = True

    # migrate a single file
    if options.file:
        migrateSingleFile(options.file, options, neededUpdates)
        sys.exit(0)

    # build file database
    fileDb = {}
    listIndex = 0
    for path in options.classPath:
        indexClassPath(path, listIndex, options, fileDb)
        listIndex += 1

    print """
MIGRATION SUMMARY:

Current qooxdoo version:   %s
Upgrade path:              %s

Affected Classes:
    %s""" % (
        options.from_version,
        " -> ".join(neededUpdates),
        "\n    ".join(fileDb.keys()),
    )

    if hasPatchModule:
        print """
WARNING: The JavaScript files will be pretty printed. You can customize the
         pretty printer using the PRETTY_PRINT_OPTIONS variable in your
         Makefile. You can find a complete list of pretty printing options
         at http://qooxdoo.org/documentation/articles/code_style."""

    choice = raw_input(
        """
NOTE:    It is advised to do a 'generate.py distclean' before migrating any files.
         If you choose 'yes', a subprocess will be invoked to run distclean,
         and after completion you will be prompted if you want to
         continue with the migration. If you choose 'no', the distclean
         step will be skipped (which might result in potentially unnecessary
         files being migrated).

Do you want to run 'distclean' now? [yes] : """
    )

    if choice.lower() in ["j", "ja", "y", "yes", ""]:
        os.system("python ./generate.py distclean")

    choice = raw_input(
        """

WARNING: The migration process will update the files in place. Please make
         sure, you have a backup of your project. The complete output of the
         migration process will be logged to '%s'.

Do you want to start the migration now? [no] : """
        % LOGFILE
    )

    if not choice.lower() in ["j", "y", "yes"]:
        sys.exit()

    # start migration
    setupLogging(options.verbose)
    fileLogger = logging.FileHandler(LOGFILE, "w")
    formatter = logging.Formatter("%(message)s")
    fileLogger.setFormatter(formatter)
    fileLogger.setLevel(logging.NOTSET)
    logging.getLogger().addHandler(fileLogger)

    if options.migrateHtml:
        htmlFiles = "."
    else:
        htmlFiles = None

    for version in neededUpdates:
        logging.info("")
        logging.info("UPGRADE TO %s" % (version))
        logging.info("----------------------------------------------------------------------------")

        handle(fileDb, options, getNormalizedVersion(version), htmlFiles, verbose=options.verbose)

    # patch makefile
    if not options.makefile is None:
        patchMakefile(options.makefile, MIGRATION_ORDER[-1], options.from_version)

    print """

The complete output of the migration process has been logged to the file '%s'.

""" % LOGFILE
示例#4
0
def main():

    parser = optparse.OptionParser("usage: %prog [options]",
                                   option_class=ExtendAction)

    migrator_options = optparse.OptionGroup(parser, "Migrator Options")
    migrator_options.add_option(
        "-m",
        "--from-makefile",
        dest="makefile",
        metavar="MAKEFILE",
        help="Makefile of the skeleton project to migrate (optional)")
    migrator_options.add_option(
        "--from-version",
        dest="from_version",
        metavar="VERSION",
        default="",
        help="qooxdoo version used for the project e.g. '0.7.3'")
    migrator_options.add_option(
        "--migrate-html",
        action="store_true",
        dest="migrateHtml",
        default=False,
        help=
        "Migrates recursively all HTML files. Starting from the current directory."
    )

    migrator_options.add_option(
        "-i",
        "--input",
        dest="file",
        metavar="FILE.js",
        help=
        "Migrate just one JavaScript file. Writes the generated file to STDOUT."
    )

    migrator_options.add_option("--class-path",
                                action="extend",
                                dest="classPath",
                                metavar="DIRECTORY",
                                type="string",
                                default=[],
                                help="Define a class path.")
    parser.add_option_group(migrator_options)

    # options from generator.py
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Verbose output mode.")
    parser.add_option("--class-encoding",
                      action="extend",
                      dest="classEncoding",
                      metavar="ENCODING",
                      type="string",
                      default=[],
                      help="Encoding of the files to migrate.")

    # Options for pretty printing
    pp_options = optparse.OptionGroup(parser, "Pretty printer options")
    compiler.addCommandLineOptions(pp_options)
    parser.add_option_group(pp_options)

    (options, args) = parser.parse_args()

    while options.from_version == "":
        choice = raw_input("""
NOTE:    To apply only the necessary changes to your project, we
         need to know the qooxdoo version it currently works with.

Please enter your current qooxdoo version [0.7.3] : """)

        if choice == "":
            options.from_version = "0.7.3"
        elif re.match(r'\d\.\d(\.\d)?', choice):
            options.from_version = choice

    if not isValidVersion(options.from_version):
        print "\nERROR: The version '%s' is not a valid version string!\n" % options.from_version
        sys.exit(1)

    if MIGRATION_ORDER[-1] == getNormalizedVersion(options.from_version):
        print "\n Nothing to do. Your application is up to date!\n"
        sys.exit()

    # to migrate a single file extract the class path
    if options.classPath == [] and options.file:
        options.classPath = [os.path.dirname(os.path.abspath(options.file))]

    if options.classPath == []:
        print """
ERROR: The class path is empty. Please specify the class pass using the
       --class-path option
"""
        sys.exit(0)

    neededUpdates = getNeededUpdates(options.from_version)

    # check whether tree bases modifications will be used
    hasPatchModule = False
    for version in neededUpdates:
        if getPatchModulePath(version) is not None:
            hasPatchModule = True
            break

    # set options for the loader and migrator
    options.classUri = []
    options.resourceInput = []
    options.resourceOutput = []
    options.cacheDirectory = None
    options.disableInternalCheck = False
    options.prettyPrint = True

    # migrate a single file
    if options.file:
        migrateSingleFile(options.file, options, neededUpdates)
        sys.exit(0)

    # build file database
    fileDb = {}
    listIndex = 0
    for path in options.classPath:
        loader.indexClassPath(path, listIndex, options, fileDb)
        listIndex += 1

    print """
MIGRATION SUMMARY:

Current qooxdoo version:   %s
Upgrade path:              %s

Affected Classes:
    %s""" % (options.from_version, " -> ".join(neededUpdates), "\n    ".join(
        fileDb.keys()))

    if hasPatchModule:
        print """
WARNING: The JavaScript files will be pretty printed. You can customize the
         pretty printer using the PRETTY_PRINT_OPTIONS variable in your
         Makefile. You can find a complete list of pretty printing options
         at http://qooxdoo.org/documentation/articles/code_style."""

    choice = raw_input("""
NOTE:    It is advised to do a 'make distclean' before migrating any files.
         If you choose 'yes', a subprocess will be invoked to run distclean,
         and after completion you will be prompted if you want to
         continue with the migration. If you choose 'no', the making distclean
         step will be skipped (which might result in potentially unnecessary
         files being migrated).

Do you want to run 'make distclean' now? [yes] : """)

    if choice.lower() in ["j", "ja", "y", "yes", ""]:
        os.system("python ./generate.py distclean")

    choice = raw_input("""

WARNING: The migration process will update the files in place. Please make
         sure, you have a backup of your project. The complete output of the
         migration process will be logged to '%s'.

Do you want to start the migration now? [no] : """ % LOGFILE)

    if not choice.lower() in ["j", "y", "yes"]:
        sys.exit()

    # start migration
    setupLogging(options.verbose)
    fileLogger = logging.FileHandler(LOGFILE, "w")
    formatter = logging.Formatter('%(message)s')
    fileLogger.setFormatter(formatter)
    fileLogger.setLevel(logging.NOTSET)
    logging.getLogger().addHandler(fileLogger)

    if options.migrateHtml:
        htmlFiles = "."
    else:
        htmlFiles = None

    for version in neededUpdates:
        logging.info("")
        logging.info("UPGRADE TO %s" % (version))
        logging.info(
            "----------------------------------------------------------------------------"
        )

        handle(fileDb,
               options,
               getNormalizedVersion(version),
               htmlFiles,
               verbose=options.verbose)

    # patch makefile
    if not options.makefile is None:
        patchMakefile(options.makefile, MIGRATION_ORDER[-1],
                      options.from_version)

    print """

The complete output of the migration process has been logged to the file '%s'.

""" % LOGFILE