dmarx / bench-warmers

DigThatData's Public Brainstorming space
https://github.com/dmarx/bench-warmers/tree/main#readme
MIT License
62 stars 6 forks source link

auto-TOC for README #1

Closed dmarx closed 2 years ago

dmarx commented 2 years ago

picturing this as a script that runs as a github action

  1. script runs for any commit that isn't just a change to certain specific files
  2. script walks through files in the project, collecting metadata from files that are tagged appropriately (e.g. *.md file that starts with an H1 annotation)
  3. reformat metadata into links to files and write to a new file
  4. insert this file contents into the README and commit (...in a fashion that won't trigger the gh action that launches this process)
dmarx commented 2 years ago

most of the way there:

from pathlib import Path
import subprocess

def get_last_modified_date(fpath, verbose=False):
    cmd = "git log -n 1 --pretty=format:%as --".split( )
    cmd += [str(fpath)]
    if verbose:
        print(cmd)
    response = subprocess.run(cmd, capture_output=True)
    return response.stdout.decode()

md_files = Path('.').glob('*.md')
TOC = []
for fpath in list(md_files):
    with open(fpath) as f: 
        header = f.readline()
        if header.startswith('# '):
            d_ = {'fpath':fpath}
            d_['title'] = header[2:].strip()
            d_['last_modified'] = get_last_modified_date(fpath)
            TOC.append(d_)

TOC = sorted(TOC, key=lambda x:x['last_modified'])[::-1]

url_root = "https://github.com/dmarx/bench-warmers/blob/main/"

header= "|last_modified|title|\n|:---|:---|\n"
recs = [f"|{d['last_modified']}|[{d['title']}]({url_root}{d['fpath']})|" for d in TOC]
toc_str= header + '\n'.join(recs)

readme="# title \n\n text goes here\n\n{TOC}\n\n# another section"
print(readme.replace('{TOC}',toc_str))

to do:

dmarx commented 2 years ago

https://github.community/t/can-github-actions-directly-edit-files-in-a-repository/17884/7