def doCheckWithPythonFile(f, module): global fileCounter, okCounter, errorCounter caseName = os.path.splitext(f)[0] plugin = __import__(module + caseName, fromlist=[module + caseName]) pluginMethod = None if hasattr(plugin, 'doTest'): pluginMethod = getattr(plugin, 'doTest') else: console.error('doTest should exist in %s' % f) if pluginMethod is None: return pluginMethod() getResults = None if hasattr(plugin, 'getResults'): getResults = getattr(plugin, 'getResults') else: console.error('[TOOL] %s should import asserts.py' % f) if getResults is None: return fileCounter = fileCounter + 1 results = getResults() for result in results: if result[0] == False: errorCounter = errorCounter + 1 console.show('[UnitTest] [' + f + ']' + result[1]) else: okCounter = okCounter + 1
def doCheckWithPythonFile(f, module): global fileCounter, okCounter, errorCounter caseName = os.path.splitext(f)[0] plugin = __import__(module + caseName, fromlist = [module + caseName]) pluginMethod = None if hasattr(plugin, 'doTest'): pluginMethod = getattr(plugin, 'doTest') else: console.error('doTest should exist in %s' % f) if pluginMethod is None: return pluginMethod() getResults = None if hasattr(plugin, 'getResults'): getResults = getattr(plugin, 'getResults') else: console.error('[TOOL] %s should import asserts.py' % f) if getResults is None: return fileCounter = fileCounter + 1 results = getResults() for result in results: if result[0] == False: errorCounter = errorCounter + 1 console.show('[UnitTest] [' + f + ']' + result[1]) else: okCounter = okCounter + 1
def getConfigFile(value): value = value.strip() if value == '': console.error('no config file, ckstyle.ini path should be after -c.\n') return None if os.path.exists(value) and value.endswith('.ini'): return value else: console.error('%s does not exist, or is not a ".ini" file' % value) return None
def doCombine(name, props): pluginName = camelCase(name) + 'Combiner' pluginClass = NullCombiner try: plugin = __import__('ckstyle.plugins.combiners.' + pluginName, fromlist = [pluginName]) if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('%s should exist in %s.py' % (pluginName, pluginName)) except ImportError, e: pass
def getNameAndVersion(args): argLen = len(args) if argLen < 3 or argLen > 4: console.error('wrong arg length, use "ckstyle -h" to see help.') return None, None pluginName = args[2] version = '' if argLen == 4: version = args[3] return pluginName, version
def doValidate(name, value): pluginName = camelCase(name) + 'Validator' pluginClass = NullValidator try: plugin = __import__('ckstyle.plugins.validators.' + pluginName, fromlist = [pluginName]) #plugin = __import__(pluginName, fromlist = [pluginName]) if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('%s should exist in %s.py' % (pluginName, pluginName)) except ImportError, e: pass
def remember(self, errorLevel, errorMsg): '''记录代码中的问题''' if errorLevel == ERROR_LEVEL.LOG: if self.config.errorLevel > 1: self.logMsgs.append(errorMsg) elif errorLevel == ERROR_LEVEL.WARNING: if self.config.errorLevel > 0: self.warningMsgs.append(errorMsg) elif errorLevel == ERROR_LEVEL.ERROR: self.errorMsgs.append(errorMsg) else: console.error('[TOOL] wrong ErrorLevel for ' + errorMsg)
def checkExtraRule(ruleSet): for checker in self.extraCheckers: if not hasattr(checker, 'check'): continue result = checker.check(ruleSet, self.config) if isBoolean(result): if not result: self.logRuleSetMessage(checker, ruleSet) elif isList(result) and len(result) != 0: self.logRuleSetMessage(checker, ruleSet, result) else: console.error('check should be boolean/list, %s is not.' % checker.id)
def logStyleSheetMessage(self, checker, styleSheet, errors = None): '''记录StyleSheet的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: if errorMsg is None or errorMsg == '': console.error('[TOOL] no errorMsg in your plugin, please check it') if errorMsg.find('${file}') == -1: errorMsg = errorMsg + ' (from "' + styleSheet.getFile() + '")' else: errorMsg = errorMsg.replace('${file}', styleSheet.getFile()) self.remember(errorLevel, errorMsg);
def checkRuleSet(ruleSet): for checker in self.ruleSetCheckers: if not hasattr(checker, 'check'): continue result = checker.check(ruleSet, self.config) if isBoolean(result): if not result: self.logRuleSetMessage(checker, ruleSet) elif isList(result) and len(result) != 0: self.logRuleSetMessage(checker, ruleSet, result) else: console.error('check should be boolean/list, %s is not.' % checker.id)
def checkRule(ruleSet): for checker in self.ruleCheckers: for rule in ruleSet.getRules(): if not hasattr(checker, 'check'): continue result = checker.check(rule, self.config) if isBoolean(result): if not result: self.logRuleMessage(checker, rule) elif isList(result) and len(result) != 0: self.logRuleMessage(checker, rule, result) else: console.error('check should be boolean/list, %s is not.' % checker.id)
def doCombine(name, props): pluginName = camelCase(name) + 'Combiner' pluginClass = NullCombiner try: plugin = __import__('ckstyle.plugins.combiners.' + pluginName, fromlist=[pluginName]) if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('%s should exist in %s.py' % (pluginName, pluginName)) except ImportError, e: pass
def getErrorLevel(value): if value.strip() == '': return None try: realValue = string.atoi(value) errorLevel = realValue if errorLevel > 2: errorLevel = 2 elif errorLevel < 0: errorLevel = 0 return errorLevel except ValueError: console.error('--errorLevel option should be number\n') return None
def logStyleSheetMessage(self, checker, styleSheet, errors=None): '''记录StyleSheet的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: if errorMsg is None or errorMsg == '': console.error( '[TOOL] no errorMsg in your plugin, please check it') if errorMsg.find('${file}') == -1: errorMsg = errorMsg + ' (from "' + styleSheet.getFile() + '")' else: errorMsg = errorMsg.replace('${file}', styleSheet.getFile()) self.remember(errorLevel, errorMsg)
def logRuleMessage(self, checker, rule, errors = None): '''记录一条key/value的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: if errorMsg is None or errorMsg == '': console.error('[TOOL] no errorMsg in your plugin, please check it') if errorMsg.find('${selector}') == -1: errorMsg = errorMsg + ' (from "' + rule.selector + '")' else: errorMsg = errorMsg.replace('${selector}', rule.selector) errorMsg = errorMsg.replace('${name}', rule.roughName.strip()) errorMsg = errorMsg.replace('${value}', rule.value.strip()) self.remember(errorLevel, errorMsg);
def logRuleMessage(self, checker, rule, errors=None): '''记录一条key/value的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: if errorMsg is None or errorMsg == '': console.error( '[TOOL] no errorMsg in your plugin, please check it') if errorMsg.find('${selector}') == -1: errorMsg = errorMsg + ' (from "' + rule.selector + '")' else: errorMsg = errorMsg.replace('${selector}', rule.selector) errorMsg = errorMsg.replace('${name}', rule.roughName.strip()) errorMsg = errorMsg.replace('${value}', rule.value.strip()) self.remember(errorLevel, errorMsg)
def doValidate(name, value): pluginName = camelCase(name) + 'Validator' pluginClass = NullValidator try: plugin = __import__('ckstyle.plugins.validators.' + pluginName, fromlist=[pluginName]) #plugin = __import__(pluginName, fromlist = [pluginName]) if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('%s should exist in %s.py' % (pluginName, pluginName)) except ImportError as e: pass instance = pluginClass(name, value) return instance.validate()
def loadFromSubFiles(self, pluginDir): '''从plugins目录动态载入检查类''' # ids = {} include = self.config.include exclude = self.config.exclude safeMode = self.config.safeMode safeModeExcludes = 'combine-same-rulesets' for filename in os.listdir(pluginDir): if not filename.endswith('.py') or filename.startswith('_'): continue if filename == 'Base.py' or filename == 'helper.py': continue pluginName = os.path.splitext(filename)[0] # 获取plugins的引用 plugin = __import__("ckstyle.plugins." + pluginName, fromlist=[pluginName]) pluginClass = None if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('[TOOL] class %s should exist in %s.py' % (pluginName, pluginName)) continue # 构造plugin的类 instance = pluginClass() # 如果是private,则说明不论是否选择都需要的规则 if not hasattr(instance, 'private') or getattr( instance, 'private') is not True: if include != 'all' and include.find(instance.id) == -1: continue elif exclude != 'none' and exclude.find(instance.id) != -1: continue elif safeMode and safeModeExcludes.find(instance.id) != -1: continue #if instance.errorMsg.find(';') != -1 or instance.errorMsg.find('\n') != -1: # console.error(r'[TOOL] errorMsg should not contain ";" or "\n" in %s.py' % pluginName) # continue # 注册到检查器中 self.registerChecker(instance)
def runTestsInDir(filePath, module): global fileCounter for filename in os.listdir(filePath): if (os.path.isdir(os.path.join(filePath, filename))): runTestsInDir(os.path.join(filePath, filename), module + filename + '.') continue if filename == 'asserts.py' or filename == 'helper.py' or filename.startswith( '_'): continue if filename.endswith('.py'): doCheckWithPythonFile(filename, module) continue if not filename.endswith('.css'): continue testFileName = realpath(filePath, filename) fileContent = open(testFileName).read() checker = doCheck(fileContent, filename) styleSheet = checker.getStyleSheet() testErrorSet = styleSheet.getRuleSetBySelector('@unit-test-expecteds') if testErrorSet is None: console.error('no @unit-test-expecteds in %s' % testFileName) continue expectedErrors = testErrorSet.getRules() if expectedErrors is None: console.error('no error instance in @unit-test-expecteds, %s' % testFileName) continue fileCounter = fileCounter + 1 logs = {} errors = {} warnings = {} fillDicts(logs, warnings, errors, expectedErrors) realLogs, realWarnings, realErrors = checker.errors() checkUnitTestResult(logs, realLogs, '2', filename) checkUnitTestResult(warnings, realWarnings, '1', filename) checkUnitTestResult(errors, realErrors, '0', filename)
def loadFromSubFiles(self, pluginDir): '''从plugins目录动态载入检查类''' modulePath = self.getModulePath(pluginDir) for filename in os.listdir(pluginDir): if not filename.endswith('.py') or filename.startswith('_'): continue if filename == 'Base.py' or filename == 'helper.py': continue pluginName = os.path.splitext(filename)[0] # 获取plugins的引用 plugin = __import__(modulePath + pluginName, fromlist = [pluginName]) pluginClass = None if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('[TOOL] class %s should exist in %s.py' % (pluginName, pluginName)) continue self.registerPluginClass(pluginClass)
def logStyleSheetMessage(self, checker, styleSheet, errors = None): '''记录StyleSheet的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: obj = {} if errorMsg is None or errorMsg == '': console.error('[TOOL] no errorMsg in your plugin, please check it') #if errorMsg.find('${file}') == -1: # errorMsg = errorMsg + ' (from "' + styleSheet.getFile() + '")' #else: # errorMsg = errorMsg.replace('${file}', styleSheet.getFile()) obj["errorMsg"] = errorMsg obj["file"] = styleSheet.getFile() obj["level"] = 'stylesheet' self.remember(errorLevel, obj);
def logStyleSheetMessage(self, checker, styleSheet, errors=None): '''记录StyleSheet的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: obj = {} if errorMsg is None or errorMsg == '': console.error( '[TOOL] no errorMsg in your plugin, please check it') #if errorMsg.find('${file}') == -1: # errorMsg = errorMsg + ' (from "' + styleSheet.getFile() + '")' #else: # errorMsg = errorMsg.replace('${file}', styleSheet.getFile()) obj["errorMsg"] = errorMsg obj["file"] = styleSheet.getFile() obj["level"] = 'stylesheet' self.remember(errorLevel, obj)
def loadFromSubFiles(self, pluginDir): '''从plugins目录动态载入检查类''' modulePath = self.getModulePath(pluginDir) for filename in os.listdir(pluginDir): if not filename.endswith('.py') or filename.startswith('_'): continue if filename == 'Base.py' or filename == 'helper.py': continue pluginName = os.path.splitext(filename)[0] # 获取plugins的引用 plugin = __import__(modulePath + pluginName, fromlist=[pluginName]) pluginClass = None if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('[TOOL] class %s should exist in %s.py' % (pluginName, pluginName)) continue self.registerPluginClass(pluginClass)
def loadPlugins(self, pluginDir): '''从plugins目录动态载入检查类''' # ids = {} include = self.config.include exclude = self.config.exclude for filename in os.listdir(pluginDir): if not filename.endswith('.py') or filename.startswith('_'): continue if filename == 'Base.py' or filename == 'helper.py': continue pluginName = os.path.splitext(filename)[0] # 获取plugins的引用 plugin = __import__("ckstyle.plugins." + pluginName, fromlist=[pluginName]) pluginClass = None if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('[TOOL] class %s should exist in %s.py' % (pluginName, pluginName)) continue # 构造plugin的类 instance = pluginClass() # ids[instance.id] = pluginName if include != 'all' and include.find(instance.id) == -1: continue elif exclude != 'none' and exclude.find(instance.id) != -1: continue if instance.errorMsg.find(';') != -1 or instance.errorMsg.find( '\n') != -1: console.error( r'[TOOL] errorMsg should not contain ";" or "\n" in %s.py' % pluginName) continue # 注册到检查器中 self.registerChecker(instance)
def runTestsInDir(filePath, module): global fileCounter for filename in os.listdir(filePath): if (os.path.isdir(os.path.join(filePath, filename))): runTestsInDir(os.path.join(filePath, filename), module + filename + '.') continue if filename == 'asserts.py' or filename == 'helper.py' or filename.startswith('_'): continue if filename.endswith('.py'): doCheckWithPythonFile(filename, module) continue if not filename.endswith('.css'): continue testFileName = realpath(filePath, filename) fileContent = open(testFileName).read() checker = doCheck(fileContent, filename) styleSheet = checker.getStyleSheet() testErrorSet = styleSheet.getRuleSetBySelector('@unit-test-expecteds') if testErrorSet is None: console.error('no @unit-test-expecteds in %s' % testFileName) continue expectedErrors = testErrorSet.getRules() if expectedErrors is None: console.error('no error instance in @unit-test-expecteds, %s' % testFileName) continue fileCounter = fileCounter + 1 logs = {} errors = {} warnings = {} fillDicts(logs, warnings, errors, expectedErrors) realLogs, realWarnings, realErrors = checker.errors() checkUnitTestResult(logs, realLogs, '2', filename) checkUnitTestResult(warnings, realWarnings, '1', filename) checkUnitTestResult(errors, realErrors, '0', filename)
def loadFromSubFiles(self, pluginDir): '''从plugins目录动态载入检查类''' # ids = {} include = self.config.include exclude = self.config.exclude safeMode = self.config.safeMode safeModeExcludes = 'combine-same-rulesets' for filename in os.listdir(pluginDir): if not filename.endswith('.py') or filename.startswith('_'): continue if filename == 'Base.py' or filename == 'helper.py': continue pluginName = os.path.splitext(filename)[0] # 获取plugins的引用 plugin = __import__("ckstyle.plugins." + pluginName, fromlist = [pluginName]) pluginClass = None if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('[TOOL] class %s should exist in %s.py' % (pluginName, pluginName)) continue # 构造plugin的类 instance = pluginClass() # 如果是private,则说明不论是否选择都需要的规则 if not hasattr(instance, 'private') or getattr(instance, 'private') is not True: if include != 'all' and include.find(instance.id) == -1: continue elif exclude != 'none' and exclude.find(instance.id) != -1: continue elif safeMode and safeModeExcludes.find(instance.id) != -1: continue #if instance.errorMsg.find(';') != -1 or instance.errorMsg.find('\n') != -1: # console.error(r'[TOOL] errorMsg should not contain ";" or "\n" in %s.py' % pluginName) # continue # 注册到检查器中 self.registerChecker(instance)
def logRuleMessage(self, checker, rule, errors = None): '''记录一条key/value的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: obj = {} if errorMsg is None or errorMsg == '': console.error('[TOOL] no errorMsg in your plugin, please check it') #if errorMsg.find('${selector}') == -1: # errorMsg = errorMsg + ' (from "' + rule.selector + '")' #else: # errorMsg = errorMsg.replace('${selector}', rule.selector) #errorMsg = errorMsg.replace('${name}', rule.roughName.strip()) #errorMsg = errorMsg.replace('${value}', rule.value.strip()) obj["errorMsg"] = errorMsg obj["selector"] = rule.selector obj["name"] = rule.roughName.strip() obj["value"] = rule.value.strip() obj["level"] = 'rule' self.remember(errorLevel, obj);
def _handle(options, dirHandler, fileHandler, argsParser, operation): try: opts, args = getopt.getopt(sys.argv[1:], "hrpc:", options) except getopt.GetoptError as e: console.error('[option] %s ' % e.msg) return configFile = getConfigFilePath() if len(args) == 0 and len(opts) == 0: config = getDefaultConfig(configFile) dirHandler(os.getcwd(), config=config) return config = argsParser(configFile, opts, args) config.operation = operation filePath = None if len(args) == 0: filePath = os.getcwd() else: filePath = args[0] if not os.path.exists(filePath): console.error('%s not exist' % filePath) return if filePath.endswith('.css'): fileHandler(filePath, config=config) elif os.path.isdir(filePath): dirHandler(filePath, config=config) else: console.error('%s aborted! because "%s" is neither css file, nor dir' % (operation, filePath))
def _handle(options, dirHandler, fileHandler, argsParser, operation): try: opts, args = getopt.getopt(sys.argv[1:], "hrpc:", options) except getopt.GetoptError as e: console.error('[option] %s ' % e.msg) return configFile = getConfigFilePath() if len(args) == 0 and len(opts) == 0: config = getDefaultConfig(configFile) dirHandler(os.getcwd(), config = config) return config = argsParser(configFile, opts, args) config.operation = operation filePath = None if len(args) == 0: filePath = os.getcwd() else: filePath = args[0] if not os.path.exists(filePath): console.error('%s not exist' % filePath) return if filePath.endswith('.css'): fileHandler(filePath, config = config) elif os.path.isdir(filePath): dirHandler(filePath, config = config) else: console.error('%s aborted! because "%s" is neither css file, nor dir' % (operation, filePath))
def logRuleMessage(self, checker, rule, errors=None): '''记录一条key/value的问题''' errorLevel = checker.getLevel() if errors is None: errors = [checker.getMsg()] for errorMsg in errors: obj = {} if errorMsg is None or errorMsg == '': console.error( '[TOOL] no errorMsg in your plugin, please check it') #if errorMsg.find('${selector}') == -1: # errorMsg = errorMsg + ' (from "' + rule.selector + '")' #else: # errorMsg = errorMsg.replace('${selector}', rule.selector) #errorMsg = errorMsg.replace('${name}', rule.roughName.strip()) #errorMsg = errorMsg.replace('${value}', rule.value.strip()) obj["errorMsg"] = errorMsg obj["selector"] = rule.selector obj["name"] = rule.roughName.strip() obj["value"] = rule.value.strip() obj["level"] = 'rule' self.remember(errorLevel, obj)
def loadPlugins(self, pluginDir): '''从plugins目录动态载入检查类''' # ids = {} include = self.config.include exclude = self.config.exclude for filename in os.listdir(pluginDir): if not filename.endswith('.py') or filename.startswith('_'): continue if filename == 'Base.py' or filename == 'helper.py': continue pluginName = os.path.splitext(filename)[0] # 获取plugins的引用 plugin = __import__("ckstyle.plugins." + pluginName, fromlist = [pluginName]) pluginClass = None if hasattr(plugin, pluginName): pluginClass = getattr(plugin, pluginName) else: console.error('[TOOL] class %s should exist in %s.py' % (pluginName, pluginName)) continue # 构造plugin的类 instance = pluginClass() # ids[instance.id] = pluginName if include != 'all' and include.find(instance.id) == -1: continue elif exclude != 'none' and exclude.find(instance.id) != -1: continue if instance.errorMsg.find(';') != -1 or instance.errorMsg.find('\n') != -1: console.error(r'[TOOL] errorMsg should not contain ";" or "\n" in %s.py' % pluginName) continue # 注册到检查器中 self.registerChecker(instance)
def _handle(options, dirHandler, fileHandler, argsParser, operation): try: opts, args = getopt.getopt(sys.argv[1:], "hrpc:", options) except getopt.GetoptError, e: console.error('[option] %s ' % e.msg) return
def doCheck(self): # 忽略的规则集(目前只忽略单元测试的selector) ignoreRuleSets = self.config.ignoreRuleSets def findInArray(array, value): return value in array or value.strip() in array def isBoolean(value): return type(value) == type(True) def isList(value): return isinstance(value, list) # 检查规则集 def checkRuleSet(ruleSet): for checker in self.ruleSetCheckers: if not hasattr(checker, 'check'): continue result = checker.check(ruleSet, self.config) if isBoolean(result): if not result: self.logRuleSetMessage(checker, ruleSet) elif isList(result) and len(result) != 0: self.logRuleSetMessage(checker, ruleSet, result) else: console.error('check should be boolean/list, %s is not.' % checker.id) # 检查规则 def checkRule(ruleSet): for checker in self.ruleCheckers: for rule in ruleSet.getRules(): if not hasattr(checker, 'check'): continue result = checker.check(rule, self.config) if isBoolean(result): if not result: self.logRuleMessage(checker, rule) elif isList(result) and len(result) != 0: self.logRuleMessage(checker, rule, result) else: console.error('check should be boolean/list, %s is not.' % checker.id) # 检查规则 def checkExtraRule(ruleSet): for checker in self.extraCheckers: if not hasattr(checker, 'check'): continue result = checker.check(ruleSet, self.config) if isBoolean(result): if not result: self.logRuleSetMessage(checker, ruleSet) elif isList(result) and len(result) != 0: self.logRuleSetMessage(checker, ruleSet, result) else: console.error('check should be boolean/list, %s is not.' % checker.id) # 检查样式表 styleSheet = self.parser.styleSheet for checker in self.styleSheetCheckers: if not hasattr(checker, 'check'): continue result = checker.check(styleSheet, self.config) if isBoolean(result): if not result: self.logStyleSheetMessage(checker, styleSheet) elif isList(result) and len(result) != 0: self.logStyleSheetMessage(checker, styleSheet, result) else: console.error('check should be boolean/list, %s is not.' % checker.id) for ruleSet in styleSheet.getRuleSets(): if ruleSet.extra: checkExtraRule(ruleSet) continue # 判断此规则是否忽略 if findInArray(ignoreRuleSets, ruleSet.selector): continue checkRuleSet(ruleSet) checkRule(ruleSet)
def doCheck(self): # 忽略的规则集(目前只忽略单元测试的selector) ignoreRuleSets = self.config.ignoreRuleSets def findInArray(array, value): return value in array or value.strip() in array def isBoolean(value): return type(value) == type(True) def isList(value): return isinstance(value, list) # 检查规则集 def checkRuleSet(ruleSet): for checker in self.ruleSetCheckers: if not hasattr(checker, 'check'): continue result = checker.check(ruleSet, self.config) if isBoolean(result): if not result: self.logRuleSetMessage(checker, ruleSet) elif isList(result) and len(result) != 0: self.logRuleSetMessage(checker, ruleSet, result) else: console.error('check should be boolean/list, %s is not.' % checker.id) # 检查规则 def checkRule(ruleSet): for checker in self.ruleCheckers: for rule in ruleSet.getRules(): if not hasattr(checker, 'check'): continue result = checker.check(rule, self.config) if isBoolean(result): if not result: self.logRuleMessage(checker, rule) elif isList(result) and len(result) != 0: self.logRuleMessage(checker, rule, result) else: console.error( 'check should be boolean/list, %s is not.' % checker.id) # 检查样式表 styleSheet = self.parser.styleSheet for checker in self.styleSheetCheckers: if not hasattr(checker, 'check'): continue result = checker.check(styleSheet, self.config) if isBoolean(result): if not result: self.logStyleSheetMessage(checker, styleSheet) elif isList(result) and len(result) != 0: self.logStyleSheetMessage(checker, styleSheet, result) else: console.error('check should be boolean/list, %s is not.' % checker.id) for ruleSet in styleSheet.getRuleSets(): if ruleSet.extra: continue # 判断此规则是否忽略 if findInArray(ignoreRuleSets, ruleSet.selector): continue checkRuleSet(ruleSet) checkRule(ruleSet)
if len(args) == 0 and len(opts) == 0: parser = CommandFileParser.CommandFileParser(configFile) config = parser.args dirHandler(os.getcwd(), config = config) return config = argsParser(configFile, opts, args) filePath = None if len(args) == 0: filePath = os.getcwd() else: filePath = args[0] if not os.path.exists(filePath): console.error('%s not exist' % filePath) return if filePath.endswith('.css'): fileHandler(filePath, config = config) elif os.path.isdir(filePath): dirHandler(filePath, config = config) else: console.error('%s aborted! because "%s" is neither css file, nor dir' % (operation, filePath)) def handleCkStyleCmdArgs(): options = ["help", "config=", "errorLevel=", "extension=", "include=", "exclude="] dirHandler = checkDir fileHandler = checkFile argsParser = parseCkStyleCmdArgs operation = 'ckstyle'
def main(arg = None): if len(sys.argv) == 1: console.error('at least two args') else: if checkCssFileByOpm(sys.argv[1]): console.show('no error in %s' % sys.argv[1])
if len(args) == 0 and len(opts) == 0: parser = CommandFileParser.CommandFileParser(configFile) config = parser.args dirHandler(os.getcwd(), config=config) return config = argsParser(configFile, opts, args) filePath = None if len(args) == 0: filePath = os.getcwd() else: filePath = args[0] if not os.path.exists(filePath): console.error('%s not exist' % filePath) return if filePath.endswith('.css'): fileHandler(filePath, config=config) elif os.path.isdir(filePath): dirHandler(filePath, config=config) else: console.error('%s aborted! because "%s" is neither css file, nor dir' % (operation, filePath)) def handleCkStyleCmdArgs(): options = [ "help", "config=", "errorLevel=", "extension=", "include=", "exclude=" ]
def fetch(name, version, url, root, pluginType): if noVersion: version = '' pluginDir = realpath(root, './' + name) replacedVer = '' if version == '' else version.replace('.', '_') if not os.path.exists(pluginDir): os.mkdir(pluginDir) open(realpath(pluginDir, './__init__.py'), 'w').write('') versionDir = pluginDir if version is not None and version != '': versionDir = realpath(pluginDir, './v' + replacedVer) if not os.path.exists(versionDir): os.mkdir(versionDir) open(realpath(versionDir, './__init__.py'), 'w').write('') filePath = realpath(versionDir, './index.py') if debug or not os.path.exists(filePath): realUrl = url % (name, '' if version == '' else ('' + version + '/')) console.showOk('Downloading %s%s from %s' % (name, version, realUrl)) request = urllib.urlopen(realUrl) if request.getcode() != 200: console.showError('Can not download file, status code : ' + str(request.getcode())) return try: f = open(filePath, 'w') f.write(request.read()) console.showOk('%s%s Downloaded in %s' % (name, version, filePath)) if pluginType == 'commands': console.showOk('Download successfully!') console.showOk('Please type "ckstyle %s" to execute.' % name) #urllib.urlretrieve(realUrl, realUrl) except IOError as e: console.error(str(e)) versionPath = '' if replacedVer == '' else '.v' + replacedVer whatIWant = getWhatIWant(pluginType) moduleName = "ckstyle.userplugins.%s.%s%s.index" % (pluginType, name, versionPath) try: plugin = __import__(moduleName, fromlist=["ckstyle.userplugins.%s.%s%s" % (pluginType, name, versionPath)]) except ImportError as e: console.showError(('Can not import plugin %s : ' % name) + str(e)) return filePath = realpath(versionDir, './index.pyc') if os.path.exists(filePath): os.remove(filePath) if pluginType == 'commands': if hasattr(plugin, 'doCommand'): return getattr(plugin, 'doCommand') else: console.showError('%s do not contain %s' % (moduleName, whatIWant)) return None
def fetch(name, version, url, root, pluginType): if noVersion: version = '' pluginDir = realpath(root, './' + name) replacedVer = '' if version == '' else version.replace('.', '_') if not os.path.exists(pluginDir): os.mkdir(pluginDir) open(realpath(pluginDir, './__init__.py'), 'w').write('') versionDir = pluginDir if version is not None and version != '': versionDir = realpath(pluginDir, './v' + replacedVer) if not os.path.exists(versionDir): os.mkdir(versionDir) open(realpath(versionDir, './__init__.py'), 'w').write('') filePath = realpath(versionDir, './index.py') if debug or not os.path.exists(filePath): realUrl = url % (name, '' if version == '' else ('' + version + '/')) console.showOk('Downloading %s%s from %s' % (name, version, realUrl)) request = urllib.urlopen(realUrl) if request.getcode() != 200: console.showError('Can not download file, status code : ' + str(request.getcode())) return try: f = open(filePath, 'w') f.write(request.read()) console.showOk('%s%s Downloaded in %s' % (name, version, filePath)) if pluginType == 'commands': console.showOk('Download successfully!') console.showOk('Please type "ckstyle %s" to execute.' % name) #urllib.urlretrieve(realUrl, realUrl) except IOError as e: console.error(str(e)) versionPath = '' if replacedVer == '' else '.v' + replacedVer whatIWant = getWhatIWant(pluginType) moduleName = "ckstyle.userplugins.%s.%s%s.index" % (pluginType, name, versionPath) try: plugin = __import__(moduleName, fromlist=[ "ckstyle.userplugins.%s.%s%s" % (pluginType, name, versionPath) ]) except ImportError as e: console.showError(('Can not import plugin %s : ' % name) + str(e)) return filePath = realpath(versionDir, './index.pyc') if os.path.exists(filePath): os.remove(filePath) if pluginType == 'commands': if hasattr(plugin, 'doCommand'): return getattr(plugin, 'doCommand') else: console.showError('%s do not contain %s' % (moduleName, whatIWant)) return None