File size: 6,033 Bytes
5bd8526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
collect_manuals.py - Gather all available man pages as a JSON dataset.
NixOS compatible; relies on `manpath` and `man`.
"""
import json
import os
import subprocess
import sys
from pathlib import Path

# ----------------------------------------------------------------------
# 1. Get the man page search paths
# ----------------------------------------------------------------------
def get_manpaths():
    """Return a list of directories that `man` searches for pages."""
    # On NixOS, `manpath` prints the effective MANPATH, including all profile
    # and store paths. Fall back to environment variable or hard-coded defaults.
    try:
        result = subprocess.run(["manpath", "-q"], capture_output=True, text=True, check=True)
        paths = result.stdout.strip().split(":")
        if paths and paths != [""]:
            return paths
    except (FileNotFoundError, subprocess.CalledProcessError):
        pass

    # Fallback: parse MANPATH environment variable
    manpath_env = os.environ.get("MANPATH")
    if manpath_env:
        return manpath_env.split(":")

    # Standard Linux defaults
    return ["/usr/share/man", "/usr/local/share/man"]

# ----------------------------------------------------------------------
# 2. Find all man page files
# ----------------------------------------------------------------------
def find_man_files(manpaths):
    """
    Walk each manpath directory, look inside 'man<section>' subdirs,
    and collect (topic_name, section, full_path).
    """
    # Valid extensions: compressed and raw roff
    ext_list = {".gz", ".bz2", ".xz", ".Z", ".lzma"}
    # Also accept files without compression suffix (e.g., "man1/bash.1")
    entries = []

    for base_dir in manpaths:
        base = Path(base_dir)
        if not base.is_dir():
            continue
        # All man page directories are named man1, man2, man3, manX...
        for man_dir in base.glob("man*"):
            if not man_dir.is_dir():
                continue
            # Extract section from directory name (e.g., "man1" -> "1")
            section = man_dir.name[3:]  # strip "man"
            # Find all files inside (excluding symlinks that point outside)
            for file_path in man_dir.iterdir():
                if not file_path.is_file():
                    continue
                # Resolve symlinks to avoid duplicates from different paths
                real_path = file_path.resolve()
                # Determine name by stripping the extension(s)
                name = file_path.name
                # Remove known compression extensions
                while True:
                    stem, ext = os.path.splitext(name)
                    if ext.lower() in ext_list:
                        name = stem
                    else:
                        break
                # Remove the section suffix if present (e.g., "open.2" -> "open")
                # The section suffix matches the directory section, but we remove it.
                if name.endswith(f".{section}"):
                    name = name[: -(len(section) + 1)]
                # Skip directories, etc.
                if not name:
                    continue
                entries.append((name, section, real_path))
    return entries

# ----------------------------------------------------------------------
# 3. Render a man page to plain text using `man -P cat`
# ----------------------------------------------------------------------
def render_man(topic, section, timeout=5):
    """
    Run `man -P cat <section> <topic>` and return its stdout as a string.
    Returns None on failure.
    """
    cmd = ["man", "-P", "cat", section, topic]
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=timeout,
            # Some systems still pipe through less if MANPAGER is set;
            # environment overrides it.
            env={**os.environ, "MANPAGER": "cat", "PAGER": "cat"},
        )
        if result.returncode != 0:
            # Possibly topic not found in database but file existed; skip.
            return None
        return result.stdout
    except Exception:
        return None

# ----------------------------------------------------------------------
# 4. Main
# ----------------------------------------------------------------------
def main():
    # Collect paths
    paths = get_manpaths()
    print(f"Searching in {len(paths)} man directories...", file=sys.stderr)
    entries = find_man_files(paths)
    print(f"Found {len(entries)} manual page files.", file=sys.stderr)

    # Remove exact duplicates (same topic + section from different paths)
    # Keep the first occurrence, but we still use `man` which picks the first.
    seen = set()
    unique_entries = []
    for name, section, filepath in entries:
        key = (name, section)
        if key not in seen:
            seen.add(key)
            unique_entries.append((name, section))
    print(f"After deduplication: {len(unique_entries)} unique manuals.", file=sys.stderr)

    dataset = []
    # We'll write JSON Lines (one object per line) to avoid holding everything in memory.
    # If you prefer a single JSON array, you can collect all objects first.
    with open("manuals.jsonl", "w", encoding="utf-8") as fout:
        for idx, (name, section) in enumerate(unique_entries, 1):
            text = render_man(name, section)
            if text is None:
                # Could not render – skip or log
                continue
            record = {
                "topic": name,
                "section": section,
                "manual": text,
            }
            # Write as JSON Lines (one per line)
            fout.write(json.dumps(record, ensure_ascii=False) + "\n")

            if idx % 100 == 0:
                print(f"Processed {idx}/{len(unique_entries)}...", file=sys.stderr)

    print("Done. Output written to manuals.jsonl", file=sys.stderr)

if __name__ == "__main__":
    main()