topmindspace/topmind-writing-skills / topmind-wechat-post
topmind-wechat-post
Verified创作、整理和排版公众号文章;支持工具/插件推荐结构、产品实测评测、深度解读与叙事随笔,从选题或底稿到 Markdown,按需导出内联 HTML、预览与上传清单。公众号短文用 topmind-briefs,独立改稿用 topmind-revise。
scripts/push-to-topstream.py
View on GitHub#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""push-to-topstream.py — 反向回推:公众号稿 → topstream/notes 纯 Markdown。
反向链路的最后一公里最容易出错:`::: 容器`、`==高亮==`、`[!徽章]` 等公众号专用语法
绝不能写进 notes/(仓库原文保持纯 Markdown)。本脚本做「降级转换」并生成 README 索引条目。
降级规则:
- 剥离 frontmatter
- `:::` 围栏行删除,容器内文本原样保留
- `==高亮==` → 去掉 `==`
- `[!徽章]` / `[!xxx]` → 整段删除
- `[文字](url)` 外链保留(GitHub markdown 支持)
- 中英文盘古之白保留(对 notes 同样适用)
Usage:
python3 push-to-topstream.py <包目录> [--target notes/xxx.md] [--apply]
# 默认 dry-run:打印降级预览 + 语法统计 + README 索引条目,不写盘
"""
import argparse
import os
import re
import shutil
import sys
sys.dont_write_bytecode = True # 同目录模块 import,不留 __pycache__
from wechat_paths import find_draft, require_base, resolve_topstream # 同目录模块:路径解析不写死个人路径/编号/年份
CONTAINER_RE = re.compile(r"^:::\s*\w*\s*$")
HIGHLIGHT_RE = re.compile(r"==([^=]+)==")
BADGE_RE = re.compile(r"\[![^\]]*\]")
def split_fm(text):
if not text.startswith("---\n"):
return None, text
i = text.find("\n---", 3)
if i < 0:
return None, text
return text[4:i], text[i + 4:].lstrip("\n")
def get_field(fm, key, default=""):
if not fm:
return default
m = re.search(r"^%s:\s*(.*)$" % re.escape(key), fm, re.M)
if not m:
return default
v = m.group(1).strip()
return v.strip('"').strip("'") if v else default
def downgrade(body):
"""公众号稿正文 → notes 纯 Markdown。返回 (文本, 统计)"""
stats = {"container": 0, "highlight": 0, "badge": 0}
out = []
for line in body.split("\n"):
if CONTAINER_RE.match(line.strip()):
stats["container"] += 1
continue
if BADGE_RE.search(line):
stats["badge"] += len(BADGE_RE.findall(line))
line = BADGE_RE.sub("", line).strip()
if not line:
continue
line, n = HIGHLIGHT_RE.subn(r"\1", line)
stats["highlight"] += n
out.append(line)
return "\n".join(out).strip("\n") + "\n", stats
IMG_REF_RE = re.compile(r"(!\[[^\]]*\]\()(images/[^)\s]+)(\))")
def push_assets(body_md, pkg_path, topstream, note_target, name_map, dry=False):
"""把正文引用的本地图片搬进 topstream 并改写为仓库约定路径。
`notes/xxx.md` 里写 `images/xx.png` 在 GitHub 上是死链——仓库没有 `notes/images/`。
仓库既有约定:图放 `assets/images/<note-slug>/`,正文用 `../assets/images/<slug>/xx.png`。
返回 (新正文, 搬移明细, 未找到的源图)。
"""
slug = os.path.splitext(os.path.basename(note_target))[0]
dst_dir = os.path.join(topstream, "assets", "images", slug)
moved, missing = [], []
def repl(m):
src = m.group(2)
base = os.path.basename(src)
src_path = os.path.join(pkg_path, src)
if not os.path.exists(src_path):
missing.append(src)
return m.group(0)
new_name = name_map.get(base, base)
if not dry: # dry-run 只看映射,不落盘
os.makedirs(dst_dir, exist_ok=True)
shutil.copy2(src_path, os.path.join(dst_dir, new_name))
moved.append((base, new_name))
return m.group(1) + "../assets/images/%s/%s" % (slug, new_name) + m.group(3)
return IMG_REF_RE.sub(repl, body_md), moved, missing
def make_readme_entry(title, target, tags):
tag_str = " ".join("`%s`" % t for t in tags)
return (
"- [**%s**](%s) \n"
" 描述:<一句话介绍这篇文章解决了什么问题、读者能带走什么> \n"
" %s\n" % (title, target, tag_str)
)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("pkg", help="包目录名(相对 base)或绝对路径")
ap.add_argument("--base", default=None, help="交付包根(pkg 为相对名时用);缺省按 wechat_paths.py 规则解析")
ap.add_argument("--workspace", default=None, help="topmind 工作区根(缺省读 TOPMIND_WORKSPACE)")
ap.add_argument("--topstream", default=None, help="topstream 仓库路径(缺省读 TOPSTREAM_ROOT)")
ap.add_argument("--target", help="回推目标 notes/xxx.md(缺省读 frontmatter target_file)")
ap.add_argument("--apply", action="store_true", help="实际写盘(默认只预览)")
ap.add_argument("--force", action="store_true", help="目标已存在时覆盖")
ap.add_argument("--assets", action="store_true",
help="把正文图片搬进 <topstream>/assets/images/<note-slug>/ 并改写引用(GitHub 必需)")
ap.add_argument("--asset-slug", default="", help="覆盖资源子目录名(默认取 note 文件名)")
ap.add_argument("--asset-names", default="",
help='文件名重命名映射,如 "00-封面.jpg=01-cover.jpg,01-分工.png=02-division-of-labor.png"')
args = ap.parse_args()
args.topstream = resolve_topstream(args.topstream)
if not args.topstream:
print("✗ 需要 topstream 仓库路径:--topstream <path> 或 export TOPSTREAM_ROOT=<path>")
return 1
pkg_path = args.pkg if os.path.isabs(args.pkg) else os.path.join(require_base(args.base, args.workspace), args.pkg)
draft, _layout = find_draft(pkg_path) # 新结构 <文章名>/<文章名>.md,旧结构 公众号稿.md
if not draft:
print("✗ 找不到源稿(<文章名>.md 或 公众号稿.md):%s" % pkg_path)
return 1
text = open(draft, encoding="utf-8").read()
fm, body = split_fm(text)
title = get_field(fm, "title") or get_field(fm, "title", "")
status = get_field(fm, "status", "草稿")
target_file = get_field(fm, "target_file", "")
tags = []
mt = re.search(r"^tags:\s*\[(.*)\]$", fm or "", re.M)
if mt:
tags = [t.strip().strip('"').strip("'") for t in mt.group(1).split(",") if t.strip()]
tags = [t for t in tags if t not in ("公众号", "排版")]
target = args.target or (target_file if target_file != "pending" else "")
if not target:
print("✗ 需要回推目标:--target notes/xxx.md(frontmatter target_file 仍为 pending)")
return 1
if not target.startswith("notes/"):
print("✗ target 应以 notes/ 开头:%s" % target)
return 1
body_md, stats = downgrade(body)
name_map = {}
for pair in args.asset_names.split(","):
if "=" in pair:
k, v = pair.split("=", 1)
name_map[k.strip()] = v.strip()
if args.assets:
if args.asset_slug:
target = os.path.join(os.path.dirname(target), args.asset_slug + ".md")
body_md, moved, missing = push_assets(
body_md, pkg_path, args.topstream, target, name_map,
dry=not args.apply)
else:
moved, missing = [], []
# 确保有 H1 标题开头
if not body_md.lstrip().startswith("# "):
body_md = "# %s\n\n%s" % (title, body_md)
out_path = os.path.join(args.topstream, target)
print("回推预览:%s" % os.path.basename(pkg_path))
print(" 标题 : %s" % title)
print(" 状态 : %s" % status)
print(" 目标 : %s" % target)
print(" 降级统计 : 容器 %d · 高亮 %d · 徽章 %d"
% (stats["container"], stats["highlight"], stats["badge"]))
if status != "定稿":
print(" ⚠ status=%s,回推前应先定稿(sync-status.py --set 定稿)" % status)
print("")
if moved or missing:
print(" 图片搬运 : %d 张 → assets/images/%s/"
% (len(moved), os.path.splitext(os.path.basename(target))[0]))
for zh, en in moved:
if zh != en:
print(" %s → %s" % (zh, en))
non_ascii = [en for _, en in moved if not en.isascii()]
if non_ascii:
print(" ⚠ 文件名含非 ASCII 字符:%s" % "、".join(non_ascii))
print(" 仓库约定用 ASCII(--asset-names 传映射,如 \"00-封面.jpg=01-cover.jpg\")")
if missing:
print(" ✗ 源图缺失(引用仍是 images/,会 404):%s" % "、".join(missing))
elif "images/" in body_md:
print(" ⚠ 正文引用了本地图但未加 --assets:GitHub 上 images/ 是死链,请补 --assets")
print("")
print("—— README 索引条目(复制到 topstream/README.md 的「研析心得」段)——")
print(make_readme_entry(title, target, tags))
if args.apply:
os.makedirs(os.path.dirname(out_path), exist_ok=True)
if os.path.exists(out_path) and not args.force:
print("✗ 目标已存在,加 --force 覆盖:%s" % out_path)
return 1
with open(out_path, "w", encoding="utf-8") as fh:
fh.write(body_md)
print("")
print("✓ 已写入 %s(%d 字节)" % (out_path, len(body_md.encode("utf-8"))))
print(" 下一步:把上面的 README 条目插进 topstream/README.md;")
print(" (图片已按上面明细落 assets/,正文引用已改写为 ../assets/...)")
print(" 然后回本包改 frontmatter:target_file 从 pending 改为 %s" % target)
print(" (可用:sync-status.py 之外手动改 target_file 字段,或用编辑器)")
else:
print("")
print("[dry-run] 加 --apply 实际写盘。写盘不会自动改 README 与 frontmatter,")
print(" 这两步由你/agent 手工完成,保证索引不漂移。")
return 0
if __name__ == "__main__":
sys.exit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |