1. 配置模塊python
默認配置,
markdown
用戶自定義配置,spa
命令行配置命令行
優先級從地到高code
resolved_egrc_path = get_priority(args.egrc_path, '~/.egrc', None) egrc_config = get_config_tuple_from_egrc(resolved_egrc_path)
獲得的egrc_config配置,
字符串
而後和命令行,默認配置遺棄比較。get
resolved_examples_dir = get_priority( args.examples_dir, egrc_config.examples_dir, DEFAULT_EXAMPLES_DIR )
color_config有點特殊,
cmd
color_config = None if resolved_use_color: default_color_config = get_default_color_config() color_config = merge_color_configs( egrc_config.color_config, default_color_config )
而後得出最後解析的config,string
result = Config( examples_dir=resolved_examples_dir, custom_dir=resolved_custom_dir, color_config=color_config, use_color=resolved_use_color, pager_cmd=resolved_pager_cmd )
2. 尋找命令文件
it
會從兩個目錄下分別找相應的markdown文件。
example_dir, custome_dir
def has_default_entry_for_program(program, config): """Return True if has standard examples for program, else False.""" if config.examples_dir: file_path = get_file_path_for_program( program, config.examples_dir ) return os.path.isfile(file_path) else: return False
經過將program加'.md'字符串, os.path.isfile判斷是否存在。
file_data = '' if custom_file_path: file_data += _get_contents_of_file(custom_file_path) if default_file_path: file_data += _get_contents_of_file(default_file_path) if use_color: colorizer = color.EgColorizer(color_config) file_data = colorizer.colorize_text(file_data) page_string(file_data, pager_cmd)
直接讀取文件內容, 最後調用colorizer將文本彩色畫。
3. 文本彩色化
def colorize_heading(self, text): return self._color_helper( text, '(^#+)(.*)$', ( self.color_config.pound + r'\1' + self.color_config.pound_reset + self.color_config.heading + r'\2' + self.color_config.heading_reset ) ) def _color_helper(self, text, pattern, repl): # < 2.7 didn't have the flags named argument. if sys.version_info[1] < 7: compiled_pattern = re.compile(pattern, re.MULTILINE) return re.sub( compiled_pattern, repl, text ) else: return re.sub( pattern, repl, text, flags=re.MULTILINE )
彩色畫文本,實質上是將某些文本先後加上特定字符串,輸出就達到彩色的效果。
以colorize_heading爲例,是調用re.sub,用正則匹配,而後添加特定字符串。
這裏re.sub的用法比較特殊, 使用了'\1', '\2',表示以前的捕獲組