system

the Chamesle handbook, init, live ISO and install helpers
git clone https://github.com/tortr-rs/system
Log | Files | Refs | README | LICENSE

html.py (6726B)


      1 #!/usr/bin/env python3
      2 # handbook.md -> one html page per chapter and a contents page, in the site's style
      3 # python3 html.py OUTDIR [handbook.md]
      4 import html, os, re, sys, time
      5 
      6 out = sys.argv[1]
      7 src = sys.argv[2] if len(sys.argv) > 2 else os.path.join(os.path.dirname(os.path.abspath(__file__)), 'handbook.md')
      8 slugs = ['about', 'preparing', 'installing', 'mag', 'rifle', 'base', 'kernel', 'iso', 'maintaining', 'desktop', 'files']
      9 
     10 NAV = ('<a href="./">Home</a> |\n<a href="download.html">Download</a> |\n<b>Handbook</b> |\n'
     11        '<a href="packages.html">Packages</a> |\n<a href="new.html">News</a> |\n<a href="board.html">Board</a> |\n'
     12        '<a href="chat.html">Chat</a> |\n<a href="source.html">Source</a> |\n'
     13        '<a href="https://x22.chamesle.org/">X22</a> |\n<a href="https://github.com/tortr-rs/mag">mag</a> |\n<a href="about.html">About</a>')
     14 
     15 def page(title, desc, url, body):
     16     t = html.escape(title)
     17     d = html.escape(desc)
     18     return f'''<!doctype html>
     19 <html lang="en">
     20 <head>
     21 <meta charset="utf-8">
     22 <meta name="viewport" content="width=device-width, initial-scale=1">
     23 <title>{t} - Chamesle</title>
     24 <meta name="description" content="{d}">
     25 <link rel="canonical" href="https://chamesle.org/{url}">
     26 <meta property="og:type" content="website">
     27 <meta property="og:site_name" content="Chamesle">
     28 <meta property="og:title" content="{t} - Chamesle">
     29 <meta property="og:description" content="{d}">
     30 <meta property="og:url" content="https://chamesle.org/{url}">
     31 <link rel="stylesheet" href="style.css?20">
     32 <link rel="icon" href="img/logo.png">
     33 </head>
     34 <body>
     35 
     36 <div id="page">
     37 
     38 <div id="top">
     39 <h1><a href="./"><img src="img/banner-dark.png" alt="Chamesle Linux" width="223" height="56"></a></h1>
     40 </div>
     41 
     42 <div id="nav">
     43 {NAV}
     44 </div>
     45 
     46 <main>
     47 {body}
     48 </main>
     49 
     50 <hr>
     51 <div id="foot">
     52 Something wrong on this page? Tell us on the <a href="board.html">board</a>.<br>
     53 Chamesle installs with <code>chamesle-install</code>, or by hand from the <a href="docs.html">handbook</a>.<br>
     54 <a href="https://ko-fi.com/L6N725GI1V">Ko-fi</a><br>
     55 <a href="#" id="edit-link">Edit text</a><br>
     56 $Date: {time.strftime('%Y-%m-%d')} $
     57 </div>
     58 
     59 </div>
     60 
     61 <script src="edit.js"></script>
     62 </body>
     63 </html>
     64 '''
     65 
     66 def inline(s):
     67     s = html.escape(s, quote=False)
     68     s = re.sub(r'`([^`]+)`', r'<code>\1</code>', s)
     69     s = re.sub(r'\*\*([^*]+)\*\*', r'<b>\1</b>', s)
     70     s = re.sub(r'(?<![\w*])\*([^*\s][^*]*)\*(?![\w*])', r'<i>\1</i>', s)
     71     return s
     72 
     73 def ident(h):
     74     m = re.match(r'(\d+(?:\.\d+)*)\.? ', h)
     75     return 's' + m.group(1).replace('.', '-') if m else re.sub(r'\W+', '-', h.lower()).strip('-')
     76 
     77 def render(lines):
     78     o = []
     79     i = 0
     80     n = len(lines)
     81     while i < n:
     82         l = lines[i]
     83         if not l.strip():
     84             i += 1
     85         elif l.startswith('### ') or l.startswith('#### '):
     86             h = l.lstrip('#').strip()
     87             lvl = 2 if l.startswith('### ') else 3
     88             o.append(f'<h{lvl} id="{ident(h)}">{inline(h)}</h{lvl}>')
     89             i += 1
     90         elif l.startswith('    '):
     91             c = []
     92             while i < n and (lines[i].startswith('    ') or (not lines[i].strip() and i + 1 < n and lines[i + 1].startswith('    '))):
     93                 c.append(lines[i][4:])
     94                 i += 1
     95             o.append('<pre>' + html.escape('\n'.join(c)) + '</pre>')
     96         elif l.startswith('|'):
     97             rows = []
     98             while i < n and lines[i].startswith('|'):
     99                 rows.append([c.strip() for c in lines[i].strip().strip('|').split('|')])
    100                 i += 1
    101             head, body = rows[0], [r for r in rows[1:] if not re.fullmatch(r'[-: ]+', ''.join(r))]
    102             t = '<table>\n<tr>' + ''.join(f'<th>{inline(c)}</th>' for c in head) + '</tr>\n'
    103             for r in body:
    104                 t += '<tr>' + ''.join(f'<td>{inline(c)}</td>' for c in r) + '</tr>\n'
    105             o.append(t + '</table>')
    106         elif re.match(r'(\* |\d+\. )', l):
    107             tag = 'ul' if l.startswith('* ') else 'ol'
    108             items = []
    109             while i < n and re.match(r'(\* |\d+\. )', lines[i]):
    110                 it = [re.sub(r'^(\* |\d+\. )', '', lines[i])]
    111                 i += 1
    112                 while i < n and lines[i].strip() and lines[i].startswith('  ') and not re.match(r'\s*(\* |\d+\. )', lines[i]):
    113                     it.append(lines[i].strip())
    114                     i += 1
    115                 items.append(' '.join(it))
    116             o.append(f'<{tag}>\n' + '\n'.join(f'<li>{inline(x)}</li>' for x in items) + f'\n</{tag}>')
    117         else:
    118             p = []
    119             while i < n and lines[i].strip() and not re.match(r'(\* |\d+\. |#|\||    )', lines[i]):
    120                 p.append(lines[i].strip())
    121                 i += 1
    122             if not p:
    123                 p = [l.strip()]
    124                 i += 1
    125             o.append('<p>' + inline(' '.join(p)) + '</p>')
    126     return '\n'.join(o)
    127 
    128 text = open(src).read().split('\n')
    129 chapters = []
    130 for l in text:
    131     if l.startswith('## '):
    132         chapters.append((l[3:].strip(), []))
    133     elif chapters:
    134         chapters[-1][1].append(l)
    135 
    136 assert len(chapters) == len(slugs), 'chapters and slugs do not match'
    137 os.makedirs(out, exist_ok=True)
    138 
    139 def fname(k):
    140     return f'handbook-{slugs[k]}.html'
    141 
    142 toc = ['<h2>The handbook</h2>', '<p><i>How to build, install and run Chamesle.</i></p>', '<ol>']
    143 for k, (title, body) in enumerate(chapters):
    144     name = re.sub(r'^\d+\. ', '', title)
    145     subs = [l[4:].strip() for l in body if l.startswith('### ')]
    146     toc.append(f'<li><a href="{fname(k)}">{html.escape(name)}</a>')
    147     if subs:
    148         toc.append('<ul>' + ''.join(f'<li><a href="{fname(k)}#{ident(s)}">{html.escape(s)}</a></li>' for s in subs) + '</ul>')
    149     toc.append('</li>')
    150 toc.append('</ol>')
    151 open(os.path.join(out, 'docs.html'), 'w').write(page('Handbook', 'The Chamesle handbook, chapter by chapter: preparing, installing, mag, rifle, the base system, the kernel, the live ISO and the files of the system.', 'docs.html', '\n'.join(toc)))
    152 
    153 for k, (title, body) in enumerate(chapters):
    154     name = re.sub(r'^\d+\. ', '', title)
    155     bar = []
    156     if k: bar.append(f'<a href="{fname(k - 1)}">&larr; {html.escape(re.sub(r"^\d+\. ", "", chapters[k - 1][0]))}</a>')
    157     bar.append('<a href="docs.html">Contents</a>')
    158     if k < len(chapters) - 1: bar.append(f'<a href="{fname(k + 1)}">{html.escape(re.sub(r"^\d+\. ", "", chapters[k + 1][0]))} &rarr;</a>')
    159     nav = '<p>' + ' | '.join(bar) + '</p>'
    160     first = next((l for l in body if l.strip() and not l.startswith(('#', ' ', '|', '*'))), name)
    161     desc = re.sub(r'[`*]', '', first)[:200]
    162     b = f'{nav}\n<h2>{html.escape(title)}</h2>\n' + render(body) + f'\n<hr>\n{nav}'
    163     open(os.path.join(out, fname(k)), 'w').write(page(name, desc, fname(k), b))
    164 print(len(chapters) + 1, 'pages in', out)