Last active
December 4, 2021 17:05
-
-
Save qbosen/f832fe27569dd85aa0203dfcab13efbb to your computer and use it in GitHub Desktop.
在logseq笔记目录中搜索目标 homebrew 相关脚本,并导出
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from typing import * | |
import sys | |
import os | |
import re | |
from pathlib import Path | |
def search_and_handle( | |
search_pattern: Union[AnyStr, Pattern], | |
search_dirs: List[Union[AnyStr, os.PathLike[AnyStr]]], | |
search_flags: re.RegexFlag = 0, | |
directory_pattern: Union[AnyStr, Pattern] = r'(?!\.).*', | |
file_pattern: Union[AnyStr, Pattern] = None, | |
handler: Callable[[Match, AnyStr], None] = None, | |
): | |
""" | |
在指定目录中列表中搜索、匹配字符串,并处理 | |
@param search_pattern: 搜索的字符串表达式 | |
@param search_dirs: 搜索字符的目录 | |
@param search_flags: 搜索字符串的正则flag | |
@param directory_pattern: 目录正则表达, None表示所有 | |
@param file_pattern: 文件名正则, None表示所有 | |
@param handler: 匹配类型处理器,接收match object 和 file name | |
""" | |
for search_dir in search_dirs: | |
for root, dirs, files in os.walk(search_dir): | |
if directory_pattern: | |
dirs[:] = [d for d in dirs if re.fullmatch(directory_pattern, d)] | |
for file in files: | |
if handler and (file_pattern is None or re.fullmatch(file_pattern, file)): | |
with open(Path(root, file)) as f: | |
for target in re.finditer(search_pattern, f.read(), search_flags): | |
handler(target, f.name) | |
# 一个demo演示导出笔记中关于 brew install 的脚本 | |
if __name__ == '__main__': | |
if not len(sys.argv): | |
print("第一个参数是logseq目录") | |
sys.exit() | |
lsq_dir = Path(sys.argv[1]).resolve() | |
print(f"Logseq 目录: {lsq_dir}") | |
brew_scripts = [] | |
search_and_handle( | |
r'brew\s+install\s+(-[\w-]+\s+)*((formula|cask)\s+)?\w[\w/-]*', | |
[lsq_dir / 'journals', lsq_dir / 'pages'], | |
file_pattern=r'.+\.md', | |
handler=lambda m, f: brew_scripts.append(re.sub(r'\s+', ' ', m.group(0))) | |
) | |
brew_file = lsq_dir / 'mydata' / 'brew.sh' | |
brew_file.parent.mkdir(parents=True, exist_ok=True) | |
brew_file.write_text('\n'.join(brew_scripts)) | |
print(f"导出brew相关内容到: {brew_file}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
SCRIPT_DIR="$(cd $(dirname "$0") && pwd -P)" | |
LOGSEQ_DIR="$(dirname "$SCRIPT_DIR")" | |
PY_SCRIPT="$(basename "$0" ".sh").py" | |
"$SCRIPT_DIR/$PY_SCRIPT" "$LOGSEQ_DIR" | |
echo 'DONE' | |
read |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment