File: common.py

package info (click to toggle)
mkdocs-test 0.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 436 kB
  • sloc: python: 938; sh: 34; makefile: 5
file content (364 lines) | stat: -rw-r--r-- 10,852 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"""
Fixtures utilities for the testing of Mkdocs-Macros (pytest)
Part of the test package.

Not all are used, but they are maintained here for future reference.


(C) Laurent Franceschetti 2024
"""

import os
import re
from io import StringIO
import inspect
import subprocess
import yaml
from typing import List, Dict, Tuple

import markdown
import pandas as pd
from bs4 import BeautifulSoup

from super_collections import SuperDict


# ------------------------------------------
# Initialization
# ------------------------------------------
# the test plugin's name
TEST_PLUGIN = 'test'

# the directory where the export files must go
TEST_DIRNAME = '__test__'

"The default docs directory"
DOCS_DEFAULT_DIRNAME = 'docs'

"The mapping file (communication between plugin and test)"
PAGE_MAP = 'page_map.json'

# ---------------------------
# Print functions
# ---------------------------
std_print = print
from rich import print
from rich.panel import Panel
from rich.table import Table

TITLE_COLOR = 'green'
def h1(s:str, color:str=TITLE_COLOR):
    "Color print a 1st level title to the console"
    print()
    print(Panel(f"[{color} bold]{s}", style=color, width=80))

def h2(s:str, color:str=TITLE_COLOR):
    "Color print a 2nd level title to the consule"
    print()
    print(f"[green bold underline]{s}")

def h3(s:str, color:str=TITLE_COLOR):
    "Color print a 2nd level title to the consule"
    print()
    print(f"[green underline]{s}")


# ---------------------------
# Low-level functions
# ---------------------------



def strip_ansi_colors(text):
    "Strip ANSI color instructions"
    ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
    return ansi_escape.sub('', text)



def find_after(s:str, word:str, pattern:str):
    """
    Find the the first occurence of a pattern after a word
    (Both word and pattern can be regex, and the matching
    is case insensitive.)
    """
    word_pattern = re.compile(word, re.IGNORECASE)
    parts = word_pattern.split(s, maxsplit=1)
    # parts = s.split(word, 1)
    
    if len(parts) > 1:
        # Strip the remainder and search for the pattern
        remainder = parts[1].strip()
        match = re.search(pattern, remainder, flags=re.IGNORECASE)
        return match.group(0) if match else None
    else:
        return None
    
def find_page(name:str, filenames:List) -> str:
    """
    Find a name in list of filenames
    using a name (full or partial, with or without extension).
    """
    for filename in filenames:
        # give priority to exact matches
        # print("Checking:", filename)
        if name == filename:
            return filename
        # try without extension
        stem, _ = os.path.splitext(filename)
        # print("Checking:", stem)
        if name == stem:
            return filename
    # try again without full path
    for filename in filenames:
        if filename.endswith(name):
            return filename
        stem, _ = os.path.splitext(filename)
        # print("Checking:", stem)
        if stem.endswith(name):
            return filename

def list_markdown_files(directory:str):
    """
    Makes a list of markdown files in a directory
    """
    markdown_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.md') or file.endswith('.markdown'):
                relative_path = os.path.relpath(os.path.join(root, file), directory)
                markdown_files.append(relative_path)
    return markdown_files


def markdown_to_html(markdown_text):
    """Convert markdown text to HTML."""
    html = markdown.markdown(markdown_text, extensions=["tables"])
    return html


def style_dataframe(df:pd.DataFrame):
    """
    Apply beautiful and colorful styling to any dataframe
    (patches the dataframe).
    """
    def _rich_str(self):
        table = Table(show_header=True, header_style="bold magenta")

        # Add columns
        for col in self.columns:
            table.add_column(col, style="dim", width=12)

        # Add rows
        for row in self.itertuples(index=False):
            table.add_row(*map(str, row))

        return table

    # reassign str to rich (to avoid messing up when rich.print is used)
    df.__rich__ = _rich_str.__get__(df)


# --------------------------------------------
# Smart find/extraction functions (HTML)
# --------------------------------------------


def extract_tables_from_html(html:str, formatter:callable=None):
    """
    Extract tables from an HTML source and convert them into dataframes
    """
    soup = BeautifulSoup(html, 'html.parser')
    tables = soup.find_all('table')
    
    dataframes = {}
    unnamed_table_count = 0
    for table in tables:
        print("Found a table")
        # Find the nearest header
        header = table.find_previous(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
        if header:
            header_text = header.get_text()
        else:
            unnamed_table_count += 1
            header_text = f"Unnamed Table {unnamed_table_count}"
        
        # Convert HTML table to DataFrame
        df = pd.read_html(StringIO(str(table)))[0]
        if formatter:
            formatter(df)
        # Add DataFrame to dictionary with header as key
        dataframes[header_text] = df
    
    return dataframes


def find_in_html(html: str, 
                 pattern: str, 
                 header: str = None, header_level: int = None) -> str:
    """
    Find a text or regex pattern in a HTML document (case-insensitive)
    
    Arguments
    ---------
    - html: the html string
    - pattern: the text or regex
    - header (text or regex): if specified, it finds it first,
    and then looks for the text between that header and the next one
    (any level).
    - header_level: you can speciy it, if there is a risk of ambiguity.

    Returns
    -------
    The line where the pattern was found, or None
    """
    if not isinstance(pattern, str):
        pattern = str(pattern)

    soup = BeautifulSoup(html, 'html.parser')
    
    # Compile regex patterns with case-insensitive flag
    pattern_regex = re.compile(pattern, re.IGNORECASE)
    
    if header:
        header_regex = re.compile(header, re.IGNORECASE)
        
        # Find all headers (h1 to h6)
        headers = soup.find_all(re.compile('^h[1-6]$', re.IGNORECASE))
        
        for hdr in headers:
            if header_regex.search(hdr.text):
                # Check if header level is specified and matches
                if header_level and hdr.name != f'h{header_level}':
                    continue
                
                # Extract text until the next header
                text = []
                for sibling in hdr.find_next_siblings():
                    if sibling.name and re.match('^h[1-6]$', sibling.name, re.IGNORECASE):
                        break
                    text.append(sibling.get_text(separator='\n', strip=True))
                
                full_text = '\n'.join(text)
                
                # Search for the pattern in the extracted text
                match = pattern_regex.search(full_text)
                if match:
                    # Find the full line containing the match
                    lines = full_text.split('\n')
                    for line in lines:
                        if pattern_regex.search(line):
                            return line
    else:
        # Extract all text from the document
        full_text = soup.get_text(separator='\n', strip=True)
        
        # Search for the pattern in the full text
        match = pattern_regex.search(full_text)
        if match:
            # Find the full line containing the match
            lines = full_text.split('\n')
            for line in lines:
                if pattern_regex.search(line):
                    return line
    
    return None



# --------------------------------------------
# Smart find/extraction functions (Markdown)
# --------------------------------------------

def get_frontmatter(text:str) -> Tuple[str, dict]:
    """
    Get the front matter from a markdown file.

    Returns
    -------
        - markdown
        - frontmatter
        - metadata
    """
    # Split the content to extract the YAML front matter
    parts = text.split('---',maxsplit=2)
    if len(parts) > 1:
        frontmatter = parts[1].strip()
        metadata = SuperDict(yaml.safe_load(frontmatter))
        try:
            markdown = parts[2]
        except IndexError:
            markdown = ''
        return (markdown.strip(), frontmatter, metadata)
    else:
        return (text, '', {})
    



    



def get_first_h1(markdown_text: str):
    """
    Get the first h1 in a markdown file, 
    ignoring YAML frontmatter and comments.
    """
    # Remove YAML frontmatter
    yaml_frontmatter_pattern = re.compile(r'^---\s*\n(.*?\n)?---\s*\n', 
                                          re.DOTALL)
    markdown_text = yaml_frontmatter_pattern.sub('', markdown_text)
    # Regular expression to match both syntaxes for level 1 headers
    h1_pattern = re.compile(r'^(# .+|.+\n=+)', re.MULTILINE)
    match = h1_pattern.search(markdown_text)
    if match:
        header = match.group(0)
        # Remove formatting
        if header.startswith('#'):
            return header.lstrip('# ').strip()
        else:
            return header.split('\n')[0].strip()
    return None



def get_tables(markdown_text:str) -> Dict[str, pd.DataFrame]:
    """
    Convert markdown text to HTML, extract tables, 
    and convert them to dataframes.
    """
    html = markdown_to_html(markdown_text)
    dataframes = extract_tables_from_html(html, 
                                          formatter=style_dataframe)
    return dataframes



# ---------------------------
# OS Functions
# ---------------------------
def run_command(command, *args) -> subprocess.CompletedProcess:
    "Execute a command"
    full_command = [command] + list(args)
    return subprocess.run(full_command, capture_output=True, text=True)

def get_caller_directory():
    "Get the caller's directory name (to be called from a function)"
    # Get the current frame
    current_frame = inspect.currentframe()
    # Get the caller's frame
    caller_frame = inspect.getouterframes(current_frame, 2)
    # Get the file name of the caller
    caller_file = caller_frame[1].filename
    # Get the absolute path of the directory containing the caller file
    directory_abspath = os.path.abspath(os.path.dirname(caller_file))
    return directory_abspath


def is_in_dir(pathname: str, parent: str) -> bool:
    "Check if a pathname is in a parent directory"
    # Normalize and resolve both paths
    pathname = os.path.abspath(pathname)
    parent = os.path.abspath(parent)
    return os.path.commonpath([pathname, parent]) == parent