Beispiel #1
0
                for fname in files:
                    fileExtension = fname[fname.rfind('.') + 1:]
                    eachFile = os.path.join(root, fname)
                    basePart = eachFile[len(targetPath):]
                    if fileExtension in cExtendstionSet and basefilelist.IsNewOrChanged(
                            eachFile) and filter.CheckFileInclusion(basePart):
                        nsiqcppstyle_reporter.StartFile(
                            os.path.dirname(basePart), fname)
                        ProcessFile(ruleManager, eachFile, analyzedFiles,
                                    ciMode)
                        nsiqcppstyle_reporter.EndFile()
            ruleManager.RunProjectRules(targetPath)
            nsiqcppstyle_reporter.EndTarget()

        nsiqcppstyle_reporter.ReportSummaryToScreen(analyzedFiles,
                                                    _nsiqcppstyle_state,
                                                    filter, ciMode)
        nsiqcppstyle_reporter.CloseReport(_nsiqcppstyle_state.output_format)
        return _nsiqcppstyle_state.error_count

    except Usage, err:
        print >> sys.stderr, err.msg
        print >> sys.stderr, "for help use --help"
        sys.exit(-1)


#################################################################################################3


def ProcessFile(ruleManager, file, analyzedFiles, ciMode):
    if not ciMode: print "Processing: ", file
def main(argv=None):
    global filename

    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "o: s: m: hqvrf: ", [
                "help", "csv", "output=", "list_rules", "verbose=", "show-url",
                "no-update", "ci", "quiet", "var=", "noBase"
            ])
        except getopt.error as msg:
            raise ShowMessageAndExit(msg)
            return 0

        outputPath = ""
        _nsiqcppstyle_state.output_format = "vs7"
        filterScope = "default"
        filterPath = ""
        noBase = False
        varMap = {}
        extLangMap = {
            "Html":
            set(["htm", "html"]),
            "Java":
            set(["java"]),
            "Javascript/ActionScript":
            set(["js", "as"]),
            "JSP/PHP":
            set(["jsp", "php", "JSP", "PHP"]),
            "C/C++":
            set(["cpp", "h", "c", "hxx", "cxx", "hpp", "cc", "hh", "m", "mm"])
        }

        updateNsiqCppStyle = False
        for o, a in opts:
            if o in ("-h", "--help"):
                print(title)
                Usage()
            elif o in ("-r", "--list-rules"):
                ShowRuleList()
            elif o == "-o":
                outputPath = a.strip().replace("\"", "")
            elif o == "--update":
                updateNsiqCppStyle = True
            elif o == "--no-update":
                updateNsiqCppStyle = False
            elif o == "-f":
                filterPath = a.strip().replace("\"", "")
            elif o == "-v":
                console.SetLevel(console.Level.Verbose)
            elif o == "-s":
                filterScope = a
            elif o == "--show-url":
                _nsiqcppstyle_state.showUrl = True
            elif o == '--output':
                if not a in ('emacs', 'vs7', 'csv', 'xml', 'eclipse'):
                    print(title)
                    ShowMessageAndExit(
                        'The only allowed output formats are emacs, vs7 and csv.'
                    )
                _nsiqcppstyle_state.output_format = a
            elif o == "--var":
                varMap = GetCustomKeyValueMap(a, "--var=" + a)
            elif o == "--ci":
                console.SetLevel(console.Level.Ci)
            elif o in ("-q", "--quiet"):
                console.SetLevel(console.Level.Error)
            elif o == "--noBase":
                noBase = True

        console.Out.Ci(title)
        runtimePath = GetRuntimePath()
        sys.path.append(runtimePath)
        if updateNsiqCppStyle:
            console.Out.Ci(console.Separator)
            try:
                updateagent.agent.Update(version)
            except Exception as e:
                console.Out.Error(e)

        targetPaths = GetRealTargetPaths(args)
        multipleTarget = True
        if len(targetPaths) == 1:
            multipleTarget = False

        # If multiple target
        if multipleTarget:
            if len(outputPath) == 0:
                ShowMessageAndExit(
                    "OutputPath(-o) should be provided to analyze multiple targets"
                )
        else:
            outputPath = GetOutputPath(targetPaths[0], outputPath)
        ruleManager = nsiqcppstyle_rulemanager.ruleManager

        cExtendstionSet = extLangMap.get("C/C++")

        nsiqcppstyle_reporter.PrepareReport(outputPath,
                                            _nsiqcppstyle_state.output_format)
        analyzedFiles = []
        for targetPath in targetPaths:
            nsiqcppstyle_reporter.StartTarget(targetPath)
            extLangMapCopy = copy.deepcopy(extLangMap)
            targetName = os.path.basename(targetPath)
            console.Out.Ci(console.Separator)
            console.Out.Ci("=  Analyzing %s " % targetName)

            if filterPath != "":
                filefilterPath = filterPath
            elif os.path.isfile(targetPath):
                filefilterPath = os.path.join(os.path.dirname(targetPath),
                                              "filefilter.txt")
            else:
                filefilterPath = os.path.join(targetPath, "filefilter.txt")
            if (noBase):
                basefilelist = NullBaseFileList()
            else:
                basefilelist = BaseFileList(targetPath)

            # Get Active Filter
            filterManager = FilterManager(filefilterPath, extLangMapCopy,
                                          varMap, filterScope)

            if filterScope != filterManager.GetActiveFilter().filterName:
                console.Out.Error(
                    "\n%s filter scope is not available. Instead, use %s\n" %
                    (filterScope, filterManager.GetActiveFilter().filterName))

            filter = filterManager.GetActiveFilter()
            # Load Rule

            if len(filter.nsiqCppStyleRules) == 0:
                ShowMessageAndExit(
                    "Error!. Rules must be set in %s" % filefilterPath, False)
                continue

            ruleManager.LoadRules(filter.nsiqCppStyleRules)
            _nsiqcppstyle_state.checkers = filter.nsiqCppStyleRules
            _nsiqcppstyle_state.varMap = filter.varMap
            nsiqcppstyle_reporter.ReportRules(ruleManager.availRuleNames,
                                              filter.nsiqCppStyleRules)

            console.Out.Info(filter.to_string())
            console.Out.Ci(console.Separator)
            console.Out.Verbose("* run nsiqcppstyle analysis on %s" %
                                targetName)

            # if the target is file, analyze it without condition
            if os.path.isfile(targetPath):
                fileExtension = targetPath[targetPath.rfind('.') + 1:]
                if fileExtension in cExtendstionSet:
                    ProcessFile(ruleManager, targetPath, analyzedFiles)

            # if the target is directory, analyze it with filefilter and
            # basefilelist
            else:
                for root, dirs, files in os.walk(targetPath):
                    if '.cvs' in dirs:
                        dirs.remove('.cvs')
                    if '.svn' in dirs:
                        dirs.remove('.svn')
                    if '.git' in dirs:
                        dirs.remove('.git')
                    if '.hg' in dirs:
                        dirs.remove('.hg')
                    for fname in files:
                        fileExtension = fname[fname.rfind('.') + 1:]
                        eachFile = os.path.join(root, fname)
                        basePart = eachFile[len(targetPath):]
                        if (fileExtension in cExtendstionSet
                                and basefilelist.IsNewOrChanged(eachFile)
                                and filter.CheckFileInclusion(basePart)):
                            nsiqcppstyle_reporter.StartFile(
                                os.path.dirname(basePart), fname)
                            ProcessFile(ruleManager, eachFile, analyzedFiles)
                            nsiqcppstyle_reporter.EndFile()
            ruleManager.RunProjectRules(targetPath)
            nsiqcppstyle_reporter.EndTarget()

        nsiqcppstyle_reporter.ReportSummaryToScreen(analyzedFiles,
                                                    _nsiqcppstyle_state,
                                                    filter)
        nsiqcppstyle_reporter.CloseReport(_nsiqcppstyle_state.output_format)
        return _nsiqcppstyle_state.error_count

    except Exception as err:
        console.Err.Error(err)
        console.Err.Error("for help use --help")
        sys.exit(-1)