LinuxManuals / main.py
Masrkai's picture
Upload 4 files
5bd8526
Raw
History Blame Contribute Delete
6.03 kB
#!/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()