markpact 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
markpact/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """Markpact – Executable Markdown Runtime"""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .converter import convert_markdown_to_markpact, ConversionResult
6
+ from .parser import parse_blocks
7
+ from .runner import run_cmd, ensure_venv
8
+ from .sandbox import Sandbox
9
+
10
+ __all__ = [
11
+ "parse_blocks",
12
+ "run_cmd",
13
+ "ensure_venv",
14
+ "Sandbox",
15
+ "convert_markdown_to_markpact",
16
+ "ConversionResult",
17
+ "__version__",
18
+ ]
markpact/cli.py ADDED
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env python3
2
+ """Markpact CLI"""
3
+
4
+ import argparse
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+ from .converter import convert_markdown_to_markpact, print_conversion_report
10
+ from .parser import parse_blocks
11
+ from .runner import install_deps, run_cmd
12
+ from .sandbox import Sandbox
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ parser = argparse.ArgumentParser(
17
+ prog="markpact",
18
+ description="Executable Markdown Runtime – run projects from README.md",
19
+ )
20
+ parser.add_argument("readme", nargs="?", default="README.md", help="Path to README.md")
21
+ parser.add_argument("--sandbox", "-s", help="Sandbox directory (default: ./sandbox)")
22
+ parser.add_argument("--dry-run", "-n", action="store_true", help="Show what would be done")
23
+ parser.add_argument("--convert", "-c", action="store_true",
24
+ help="Convert regular Markdown to markpact format on-the-fly")
25
+ parser.add_argument("--convert-only", action="store_true",
26
+ help="Only convert and print result, don't execute")
27
+ parser.add_argument("--save-converted", metavar="FILE",
28
+ help="Save converted markpact to file")
29
+ parser.add_argument("--auto", "-a", action="store_true",
30
+ help="Auto-detect and convert if no markpact blocks found")
31
+ parser.add_argument("--version", "-V", action="version", version=f"%(prog)s {__version__}")
32
+ parser.add_argument("--quiet", "-q", action="store_true", help="Suppress output")
33
+
34
+ args = parser.parse_args(argv)
35
+ readme = Path(args.readme)
36
+
37
+ if not readme.exists():
38
+ print(f"[markpact] ERROR: {readme} not found", file=sys.stderr)
39
+ return 1
40
+
41
+ sandbox = Sandbox(args.sandbox)
42
+ verbose = not args.quiet
43
+
44
+ # Read original content
45
+ original_text = readme.read_text()
46
+ text_to_parse = original_text
47
+
48
+ # Check if conversion is needed
49
+ has_markpact = "```markpact:" in original_text
50
+
51
+ if args.convert or args.convert_only or (args.auto and not has_markpact):
52
+ if verbose:
53
+ print(f"[markpact] Converting {readme} to markpact format...")
54
+
55
+ result = convert_markdown_to_markpact(original_text)
56
+
57
+ if verbose or args.convert_only:
58
+ print_conversion_report(result)
59
+
60
+ if args.save_converted:
61
+ save_path = Path(args.save_converted)
62
+ save_path.write_text(result.converted_text)
63
+ print(f"[markpact] Saved converted file to {save_path}")
64
+
65
+ if args.convert_only:
66
+ # Print converted content and exit
67
+ print("\n--- CONVERTED CONTENT ---\n")
68
+ print(result.converted_text)
69
+ return 0
70
+
71
+ text_to_parse = result.converted_text
72
+
73
+ elif not has_markpact and verbose:
74
+ # Suggest conversion
75
+ print(f"[markpact] WARNING: No markpact blocks found in {readme}")
76
+ print(f"[markpact] TIP: Use --convert or --auto to convert regular Markdown")
77
+ print(f"[markpact] markpact {readme} --convert")
78
+ print()
79
+
80
+ if verbose:
81
+ print(f"[markpact] Parsing {readme}")
82
+
83
+ blocks = parse_blocks(text_to_parse)
84
+ deps: list[str] = []
85
+ run_command: str | None = None
86
+
87
+ for block in blocks:
88
+ if block.kind == "bootstrap":
89
+ continue # skip bootstrap itself
90
+
91
+ if block.kind == "file":
92
+ path = block.get_path()
93
+ if not path:
94
+ print(f"[markpact] ERROR: markpact:file requires path=..., got: {block.meta}", file=sys.stderr)
95
+ return 1
96
+ if args.dry_run:
97
+ print(f"[markpact] Would write {sandbox.path / path}")
98
+ else:
99
+ f = sandbox.write_file(path, block.body)
100
+ if verbose:
101
+ print(f"[markpact] wrote {f}")
102
+
103
+ elif block.kind == "deps" and "python" in block.meta:
104
+ deps.extend(line.strip() for line in block.body.splitlines() if line.strip())
105
+
106
+ elif block.kind == "run":
107
+ run_command = block.body
108
+
109
+ if deps:
110
+ if args.dry_run:
111
+ print(f"[markpact] Would install: {', '.join(deps)}")
112
+ else:
113
+ install_deps(deps, sandbox, verbose)
114
+
115
+ if run_command:
116
+ if args.dry_run:
117
+ print(f"[markpact] Would run: {run_command}")
118
+ else:
119
+ run_cmd(run_command, sandbox, verbose)
120
+ elif verbose:
121
+ print("[markpact] No run command defined")
122
+
123
+ return 0
124
+
125
+
126
+ if __name__ == "__main__":
127
+ sys.exit(main())
markpact/converter.py ADDED
@@ -0,0 +1,282 @@
1
+ """Markdown to Markpact converter.
2
+
3
+ Analyzes regular Markdown files and converts code blocks to markpact format
4
+ based on heuristics (file paths, package lists, shell commands).
5
+ """
6
+
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+
11
+ # Patterns for detecting block types
12
+ PATTERNS = {
13
+ "deps_python": [
14
+ r"^(fastapi|flask|django|uvicorn|gunicorn|requests|pandas|numpy|pydantic)",
15
+ r"^[a-z][a-z0-9_-]*[=<>]=?\d", # package==version
16
+ r"^-r\s+requirements", # -r requirements.txt
17
+ ],
18
+ "deps_node": [
19
+ r'"(dependencies|devDependencies)":\s*\{',
20
+ r"^(express|react|vue|next|typescript|webpack)",
21
+ ],
22
+ "file_python": [
23
+ r"^(import |from .+ import |def |class |@app\.|@router\.)",
24
+ r"^#!/usr/bin/env python",
25
+ ],
26
+ "file_javascript": [
27
+ r"^(const |let |var |function |import |export |require\()",
28
+ r"^#!/usr/bin/env node",
29
+ ],
30
+ "file_html": [
31
+ r"^<!DOCTYPE|^<html|^<head|^<body",
32
+ ],
33
+ "file_css": [
34
+ r"^(\.|#|@media|@import|body|html)\s*\{",
35
+ ],
36
+ "file_json": [
37
+ r'^\s*\{\s*"',
38
+ ],
39
+ "file_yaml": [
40
+ r"^[a-z_]+:\s*([-\d\"\']|$)",
41
+ ],
42
+ "run": [
43
+ r"^(python|python3|uvicorn|gunicorn|flask|npm|node|streamlit|pytest)",
44
+ r"^(pip install|npm install|yarn)",
45
+ ],
46
+ }
47
+
48
+ # Language to file extension mapping
49
+ LANG_EXTENSIONS = {
50
+ "python": ".py",
51
+ "py": ".py",
52
+ "javascript": ".js",
53
+ "js": ".js",
54
+ "typescript": ".ts",
55
+ "ts": ".ts",
56
+ "html": ".html",
57
+ "css": ".css",
58
+ "json": ".json",
59
+ "yaml": ".yaml",
60
+ "yml": ".yaml",
61
+ "bash": ".sh",
62
+ "sh": ".sh",
63
+ "sql": ".sql",
64
+ "toml": ".toml",
65
+ "ini": ".ini",
66
+ }
67
+
68
+
69
+ @dataclass
70
+ class ConvertedBlock:
71
+ """A converted markpact block."""
72
+ original_lang: str
73
+ markpact_tag: str
74
+ meta: str
75
+ body: str
76
+ confidence: float
77
+ reason: str
78
+
79
+
80
+ @dataclass
81
+ class ConversionResult:
82
+ """Result of converting a Markdown file."""
83
+ original_text: str
84
+ converted_text: str
85
+ blocks: list[ConvertedBlock] = field(default_factory=list)
86
+ has_markpact: bool = False
87
+ changes: list[str] = field(default_factory=list)
88
+
89
+
90
+ def detect_block_type(lang: str, body: str) -> tuple[str, str, float, str]:
91
+ """
92
+ Detect the markpact block type based on language and content.
93
+
94
+ Returns: (markpact_tag, meta, confidence, reason)
95
+ """
96
+ body_lower = body.lower()
97
+ first_lines = "\n".join(body.split("\n")[:10])
98
+
99
+ # Check for deps patterns
100
+ for pattern in PATTERNS["deps_python"]:
101
+ if re.search(pattern, body, re.MULTILINE | re.IGNORECASE):
102
+ # Looks like Python dependencies
103
+ if lang in ("", "text", "txt") or "requirements" in body_lower:
104
+ return "deps", "python", 0.9, f"Detected Python dependencies (pattern: {pattern[:30]})"
105
+
106
+ for pattern in PATTERNS["deps_node"]:
107
+ if re.search(pattern, body, re.MULTILINE):
108
+ if lang in ("json", "") and '"dependencies"' in body:
109
+ return "deps", "node", 0.8, "Detected Node.js package.json"
110
+
111
+ # Check for run commands
112
+ for pattern in PATTERNS["run"]:
113
+ if re.search(pattern, first_lines, re.MULTILINE):
114
+ if lang in ("bash", "sh", "shell", "console", ""):
115
+ return "run", lang or "bash", 0.85, f"Detected run command (pattern: {pattern[:30]})"
116
+
117
+ # Check for file patterns
118
+ for file_type, patterns in PATTERNS.items():
119
+ if not file_type.startswith("file_"):
120
+ continue
121
+ for pattern in patterns:
122
+ if re.search(pattern, first_lines, re.MULTILINE):
123
+ detected_lang = file_type.replace("file_", "")
124
+ return "file", detected_lang, 0.8, f"Detected {detected_lang} file content"
125
+
126
+ # Fallback: if language is specified, assume it's a file
127
+ if lang and lang not in ("bash", "sh", "shell", "console", "text", "txt", ""):
128
+ return "file", lang, 0.6, f"Assuming file based on language tag: {lang}"
129
+
130
+ return "", "", 0.0, "Could not determine block type"
131
+
132
+
133
+ def suggest_filename(lang: str, body: str, index: int) -> str:
134
+ """Suggest a filename for a file block."""
135
+ ext = LANG_EXTENSIONS.get(lang, f".{lang}" if lang else ".txt")
136
+
137
+ # Try to detect class/function name for Python
138
+ if lang in ("python", "py"):
139
+ # Check for Flask/FastAPI app
140
+ if re.search(r"app\s*=\s*(Flask|FastAPI)\(", body):
141
+ return f"app{ext}"
142
+ # Check for class definition
143
+ match = re.search(r"^class\s+(\w+)", body, re.MULTILINE)
144
+ if match:
145
+ return f"{match.group(1).lower()}{ext}"
146
+ # Check for main block
147
+ if '__name__' in body and '__main__' in body:
148
+ return f"main{ext}"
149
+
150
+ # Check for HTML structure
151
+ if lang in ("html",):
152
+ if "<title>" in body:
153
+ match = re.search(r"<title>([^<]+)</title>", body)
154
+ if match:
155
+ name = match.group(1).lower().replace(" ", "_")[:20]
156
+ return f"{name}.html"
157
+ return "index.html"
158
+
159
+ # Default naming
160
+ return f"file_{index}{ext}"
161
+
162
+
163
+ def convert_markdown_to_markpact(text: str, verbose: bool = True) -> ConversionResult:
164
+ """
165
+ Convert regular Markdown to markpact format.
166
+
167
+ Analyzes code blocks and converts them to markpact:* format based on heuristics.
168
+ """
169
+ result = ConversionResult(original_text=text, converted_text=text)
170
+
171
+ # Check if already has markpact blocks
172
+ if "```markpact:" in text:
173
+ result.has_markpact = True
174
+ result.changes.append("File already contains markpact blocks")
175
+ return result
176
+
177
+ # Find all fenced code blocks
178
+ pattern = re.compile(
179
+ r"^```(\w*)\n(.*?)\n^```",
180
+ re.MULTILINE | re.DOTALL
181
+ )
182
+
183
+ file_index = 0
184
+ deps_found = False
185
+ run_found = False
186
+
187
+ def replace_block(match: re.Match) -> str:
188
+ nonlocal file_index, deps_found, run_found
189
+
190
+ lang = match.group(1) or ""
191
+ body = match.group(2)
192
+
193
+ # Detect block type
194
+ tag, meta, confidence, reason = detect_block_type(lang, body)
195
+
196
+ if not tag or confidence < 0.5:
197
+ # Keep original if uncertain
198
+ return match.group(0)
199
+
200
+ # Build markpact tag
201
+ if tag == "deps":
202
+ if meta == "python" and deps_found:
203
+ # Already have deps, skip
204
+ return match.group(0)
205
+ deps_found = True
206
+ new_tag = f"```markpact:deps {meta}"
207
+ result.changes.append(f"[CONVERT] ```{lang} → ```markpact:deps {meta} ({reason})")
208
+
209
+ elif tag == "run":
210
+ if run_found:
211
+ # Already have run, skip
212
+ return match.group(0)
213
+ run_found = True
214
+ new_tag = f"```markpact:run {meta}"
215
+ result.changes.append(f"[CONVERT] ```{lang} → ```markpact:run {meta} ({reason})")
216
+
217
+ elif tag == "file":
218
+ filename = suggest_filename(meta, body, file_index)
219
+ file_index += 1
220
+ new_tag = f"```markpact:file {meta} path={filename}"
221
+ result.changes.append(f"[CONVERT] ```{lang} → ```markpact:file {meta} path={filename} ({reason})")
222
+
223
+ else:
224
+ return match.group(0)
225
+
226
+ # Create converted block record
227
+ result.blocks.append(ConvertedBlock(
228
+ original_lang=lang,
229
+ markpact_tag=tag,
230
+ meta=meta,
231
+ body=body,
232
+ confidence=confidence,
233
+ reason=reason,
234
+ ))
235
+
236
+ return f"{new_tag}\n{body}\n```"
237
+
238
+ result.converted_text = pattern.sub(replace_block, text)
239
+
240
+ if not result.changes:
241
+ result.changes.append("No convertible code blocks found")
242
+
243
+ return result
244
+
245
+
246
+ def print_conversion_report(result: ConversionResult) -> None:
247
+ """Print a report of the conversion."""
248
+ print("\n" + "=" * 60)
249
+ print("MARKPACT CONVERSION REPORT")
250
+ print("=" * 60)
251
+
252
+ if result.has_markpact:
253
+ print("\n✓ File already contains markpact blocks. No conversion needed.")
254
+ return
255
+
256
+ if not result.blocks:
257
+ print("\n⚠ No convertible code blocks found.")
258
+ print(" Add code blocks with language tags for better detection.")
259
+ return
260
+
261
+ print(f"\n✓ Converted {len(result.blocks)} block(s):\n")
262
+
263
+ for change in result.changes:
264
+ print(f" {change}")
265
+
266
+ print("\n" + "-" * 60)
267
+ print("Summary:")
268
+
269
+ deps = [b for b in result.blocks if b.markpact_tag == "deps"]
270
+ files = [b for b in result.blocks if b.markpact_tag == "file"]
271
+ runs = [b for b in result.blocks if b.markpact_tag == "run"]
272
+
273
+ if deps:
274
+ print(f" • Dependencies: {len(deps)} block(s)")
275
+ if files:
276
+ print(f" • Files: {len(files)} file(s)")
277
+ for f in files:
278
+ print(f" - {f.meta}")
279
+ if runs:
280
+ print(f" • Run command: {len(runs)} block(s)")
281
+
282
+ print("=" * 60 + "\n")
markpact/parser.py ADDED
@@ -0,0 +1,33 @@
1
+ """Markpact codeblock parser"""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+
6
+ CODEBLOCK_RE = re.compile(
7
+ r"^```markpact:(?P<kind>\w+)(?:\s+(?P<meta>[^\n]+))?\n(?P<body>.*?)\n^```[ \t]*$",
8
+ re.DOTALL | re.MULTILINE,
9
+ )
10
+
11
+
12
+ @dataclass
13
+ class Block:
14
+ kind: str
15
+ meta: str
16
+ body: str
17
+
18
+ def get_path(self) -> str | None:
19
+ """Extract path= from meta"""
20
+ m = re.search(r"\bpath=(\S+)", self.meta)
21
+ return m[1] if m else None
22
+
23
+
24
+ def parse_blocks(text: str) -> list[Block]:
25
+ """Parse all markpact:* codeblocks from markdown text"""
26
+ return [
27
+ Block(
28
+ kind=m.group("kind"),
29
+ meta=(m.group("meta") or "").strip(),
30
+ body=m.group("body").strip(),
31
+ )
32
+ for m in CODEBLOCK_RE.finditer(text)
33
+ ]
markpact/runner.py ADDED
@@ -0,0 +1,42 @@
1
+ """Command execution"""
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from .sandbox import Sandbox
9
+
10
+
11
+ def run_cmd(cmd: str, sandbox: Sandbox, verbose: bool = True) -> int:
12
+ """Run command in sandbox with venv-aware PATH"""
13
+ if verbose:
14
+ print(f"[markpact] RUN: {cmd}")
15
+
16
+ env = os.environ.copy()
17
+ if sandbox.venv_bin.exists():
18
+ env["VIRTUAL_ENV"] = str(sandbox.venv_bin.parent)
19
+ env["PATH"] = f"{sandbox.venv_bin}:{env.get('PATH', '')}"
20
+
21
+ return subprocess.check_call(cmd, shell=True, cwd=sandbox.path, env=env)
22
+
23
+
24
+ def ensure_venv(sandbox: Sandbox, verbose: bool = True) -> None:
25
+ """Create venv in sandbox if not exists and not disabled"""
26
+ if os.environ.get("MARKPACT_NO_VENV") == "1":
27
+ return
28
+ if sandbox.has_venv():
29
+ return
30
+ run_cmd(f"{sys.executable} -m venv .venv", sandbox, verbose)
31
+
32
+
33
+ def install_deps(deps: list[str], sandbox: Sandbox, verbose: bool = True) -> None:
34
+ """Install Python dependencies in sandbox"""
35
+ if not deps:
36
+ return
37
+
38
+ ensure_venv(sandbox, verbose)
39
+ sandbox.write_requirements(deps)
40
+
41
+ pip = ".venv/bin/pip" if sandbox.venv_pip.exists() else "pip"
42
+ run_cmd(f"{pip} install -r requirements.txt", sandbox, verbose)
markpact/sandbox.py ADDED
@@ -0,0 +1,46 @@
1
+ """Sandbox management"""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+
7
+ class Sandbox:
8
+ """Manages sandbox directory for markpact execution"""
9
+
10
+ def __init__(self, path: str | Path | None = None):
11
+ self.path = Path(path or os.environ.get("MARKPACT_SANDBOX", "./sandbox"))
12
+ self.path.mkdir(parents=True, exist_ok=True)
13
+
14
+ @property
15
+ def venv_bin(self) -> Path:
16
+ return self.path / ".venv" / "bin"
17
+
18
+ @property
19
+ def venv_pip(self) -> Path:
20
+ return self.venv_bin / "pip"
21
+
22
+ @property
23
+ def venv_python(self) -> Path:
24
+ return self.venv_bin / "python"
25
+
26
+ def has_venv(self) -> bool:
27
+ return self.venv_python.exists()
28
+
29
+ def write_file(self, rel_path: str, content: str) -> Path:
30
+ """Write file to sandbox, creating directories as needed"""
31
+ full = self.path / rel_path
32
+ full.parent.mkdir(parents=True, exist_ok=True)
33
+ full.write_text(content)
34
+ return full
35
+
36
+ def write_requirements(self, deps: list[str]) -> Path:
37
+ """Write requirements.txt"""
38
+ req = self.path / "requirements.txt"
39
+ req.write_text("\n".join(deps))
40
+ return req
41
+
42
+ def clean(self):
43
+ """Remove sandbox directory"""
44
+ import shutil
45
+ if self.path.exists():
46
+ shutil.rmtree(self.path)
@@ -0,0 +1,302 @@
1
+ Metadata-Version: 2.4
2
+ Name: markpact
3
+ Version: 0.1.0
4
+ Summary: Executable Markdown Runtime – run projects from README.md
5
+ Project-URL: Homepage, https://github.com/wronai/markpact
6
+ Project-URL: Repository, https://github.com/wronai/markpact
7
+ Project-URL: Issues, https://github.com/wronai/markpact/issues
8
+ Author: wronai
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: executable,markdown,readme,runtime,sandbox
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Build Tools
22
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
23
+ Requires-Python: >=3.10
24
+ Provides-Extra: dev
25
+ Requires-Dist: build; extra == 'dev'
26
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
27
+ Requires-Dist: pytest>=7.0; extra == 'dev'
28
+ Requires-Dist: ruff>=0.1; extra == 'dev'
29
+ Requires-Dist: twine; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ ![img_2.png](img_2.png)
33
+
34
+ # markpact
35
+
36
+ [![PyPI version](https://img.shields.io/pypi/v/markpact.svg)](https://pypi.org/project/markpact/)
37
+ [![Python](https://img.shields.io/pypi/pyversions/markpact.svg)](https://pypi.org/project/markpact/)
38
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
39
+ [![Tests](https://github.com/wronai/markpact/actions/workflows/tests.yml/badge.svg)](https://github.com/wronai/markpact/actions)
40
+ [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)
41
+
42
+ Markpact to minimalny runtime, który pozwala trzymać cały projekt w jednym `README.md`.
43
+ Runtime ignoruje zwykły Markdown, a wykonuje wyłącznie codeblocki `markpact:*`.
44
+
45
+ ## 📚 Dokumentacja
46
+
47
+ - [Pełna dokumentacja](docs/README.md)
48
+ - [Kontrakt markpact:*](docs/contract.md)
49
+ - [CI/CD Integration](docs/ci-cd.md)
50
+ - [Współpraca z LLM](docs/llm.md)
51
+
52
+ ## 🎯 Przykłady
53
+
54
+ | Przykład | Opis | Uruchomienie |
55
+ |----------|------|--------------|
56
+ | [FastAPI Todo](examples/fastapi-todo/) | REST API z bazą danych | `markpact examples/fastapi-todo/README.md` |
57
+ | [Flask Blog](examples/flask-blog/) | Aplikacja webowa z szablonami | `markpact examples/flask-blog/README.md` |
58
+ | [CLI Tool](examples/cli-tool/) | Narzędzie linii poleceń | `markpact examples/cli-tool/README.md` |
59
+ | [Streamlit Dashboard](examples/streamlit-dashboard/) | Dashboard danych | `markpact examples/streamlit-dashboard/README.md` |
60
+ | [Kivy Mobile](examples/kivy-mobile/) | Aplikacja mobilna | `markpact examples/kivy-mobile/README.md` |
61
+ | [Electron Desktop](examples/electron-desktop/) | Aplikacja desktopowa | `markpact examples/electron-desktop/README.md` |
62
+ | [Markdown Converter](examples/markdown-converter/) | Konwersja zwykłego MD | `markpact examples/markdown-converter/sample.md --convert` |
63
+
64
+ ## 🔄 Konwersja zwykłego Markdown
65
+
66
+ Markpact może automatycznie konwertować zwykłe pliki Markdown (bez tagów `markpact:*`) do formatu wykonywalnego:
67
+
68
+ ```bash
69
+ # Podgląd konwersji
70
+ markpact README.md --convert-only
71
+
72
+ # Konwersja i uruchomienie
73
+ markpact README.md --convert
74
+
75
+ # Auto-detekcja (konwertuj jeśli brak markpact blocks)
76
+ markpact README.md --auto
77
+
78
+ # Zapisz skonwertowany plik
79
+ markpact README.md --convert-only --save-converted output.md
80
+ ```
81
+
82
+ Konwerter analizuje code blocks i na podstawie heurystyk wykrywa:
83
+ - **Zależności** → `markpact:deps` (pakiety Python/Node)
84
+ - **Pliki źródłowe** → `markpact:file` (importy, klasy, funkcje)
85
+ - **Komendy** → `markpact:run` (python, uvicorn, npm, etc.)
86
+
87
+ ## 1️⃣ Cel projektu
88
+
89
+ - **Jedno README jako źródło prawdy**
90
+ - **Możliwość uruchomienia projektu bez ręcznego tworzenia struktury plików**
91
+ - **Automatyzacja**
92
+ Bootstrap tworzy pliki w sandboxie, instaluje zależności i uruchamia komendę startową.
93
+
94
+ ## 2️⃣ Kontrakt README (codeblocki `markpact:*`)
95
+
96
+ - **`markpact:bootstrap <lang>`**
97
+ Dokładnie jeden bootstrap na README. Odpowiada za parsowanie codeblocków i uruchomienie.
98
+ - **`markpact:deps <scope>`**
99
+ Lista zależności dla danego scope (np. `python`).
100
+ - **`markpact:file <lang> path=...`**
101
+ Zapisuje plik do sandboxu pod ścieżką `path=...`.
102
+ - **`markpact:run <lang>`**
103
+ Jedna komenda uruchomieniowa wykonywana w sandboxie.
104
+
105
+ ---
106
+ ```markpact:bootstrap python
107
+ #!/usr/bin/env python3
108
+ """MARKPACT v0.1 – Executable Markdown Runtime"""
109
+ import os, re, subprocess, sys
110
+ from pathlib import Path
111
+
112
+ README = Path(sys.argv[1] if len(sys.argv) > 1 else "README.md")
113
+ SANDBOX = Path(os.environ.get("MARKPACT_SANDBOX", "./sandbox"))
114
+ SANDBOX.mkdir(parents=True, exist_ok=True)
115
+ RE = re.compile(r"^```markpact:(?P<kind>\w+)(?:\s+(?P<meta>[^\n]+))?\n(?P<body>.*?)\n^```[ \t]*$", re.DOTALL | re.MULTILINE)
116
+
117
+ def run(cmd):
118
+ print(f"[markpact] RUN: {cmd}")
119
+ env = os.environ.copy()
120
+ venv = SANDBOX / ".venv" / "bin"
121
+ if venv.exists():
122
+ env.update(VIRTUAL_ENV=str(venv.parent), PATH=f"{venv}:{env.get('PATH','')}")
123
+ subprocess.check_call(cmd, shell=True, cwd=SANDBOX, env=env)
124
+
125
+ def main():
126
+ deps, run_cmd = [], None
127
+ for m in RE.finditer(README.read_text()):
128
+ kind, meta, body = m.group("kind"), (m.group("meta") or "").strip(), m.group("body").strip()
129
+ if kind == "file":
130
+ p = re.search(r"\bpath=(\S+)", meta)
131
+ if not p: raise ValueError(f"markpact:file requires path=..., got {meta!r}")
132
+ f = SANDBOX / p[1]
133
+ f.parent.mkdir(parents=True, exist_ok=True)
134
+ f.write_text(body)
135
+ print(f"[markpact] wrote {f}")
136
+ elif kind == "deps" and meta == "python":
137
+ deps.extend(line.strip() for line in body.splitlines() if line.strip())
138
+ elif kind == "run":
139
+ run_cmd = body
140
+ if deps:
141
+ venv_pip = SANDBOX / ".venv" / "bin" / "pip"
142
+ if os.environ.get("MARKPACT_NO_VENV") != "1" and not venv_pip.exists():
143
+ run(f"{sys.executable} -m venv .venv")
144
+ (SANDBOX / "requirements.txt").write_text("\n".join(deps))
145
+ run(f"{'.venv/bin/pip' if venv_pip.exists() else 'pip'} install -r requirements.txt")
146
+ if run_cmd:
147
+ run(run_cmd)
148
+ else:
149
+ print("[markpact] No run command defined")
150
+
151
+ if __name__ == "__main__":
152
+ main()
153
+ ```
154
+
155
+ ## 3️⃣ Instalacja
156
+
157
+ ### Opcja A: Pakiet pip (zalecane)
158
+
159
+ ```bash
160
+ pip install markpact
161
+ ```
162
+
163
+ Użycie:
164
+
165
+ ```bash
166
+ markpact README.md # uruchom projekt
167
+ markpact README.md --dry-run # podgląd bez wykonywania
168
+ markpact README.md -s ./my-sandbox # własny katalog sandbox
169
+ ```
170
+
171
+ ### Opcja B: Instalacja lokalna (dev)
172
+
173
+ ```bash
174
+ git clone https://github.com/wronai/markpact.git
175
+ cd markpact
176
+ make install # lub: pip install -e .
177
+ ```
178
+
179
+ ### Opcja C: Ekstrakcja bootstrapu (zero dependencies)
180
+
181
+ - **Ekstrakcja bootstrapu do pliku**
182
+
183
+ Ten wariant jest odporny na przypadek, gdy w samym bootstrapie występują znaki ``` (np. w regexie):
184
+
185
+ ```bash
186
+ sed -n '/^```markpact:bootstrap/,/^```[[:space:]]*$/p' README.md | sed '1d;$d' > markpact.py
187
+ ```
188
+
189
+ - **Uruchomienie**
190
+
191
+ ```bash
192
+ python3 markpact.py
193
+ ```
194
+
195
+ - **Konfiguracja (env vars)**
196
+
197
+ ```bash
198
+ MARKPACT_PORT=8001 MARKPACT_SANDBOX=./.markpact-sandbox python3 markpact.py
199
+ ```
200
+
201
+ ## 4️⃣ Sandbox i środowisko
202
+
203
+ - **`MARKPACT_SANDBOX`**
204
+ Zmienia katalog sandboxu (domyślnie `./sandbox`).
205
+ - **`MARKPACT_NO_VENV=1`**
206
+ Wyłącza tworzenie `.venv` w sandboxie (przydatne, jeśli CI/Conda zarządza środowiskiem).
207
+ - **Port zajęty (`[Errno 98] address already in use`)**
208
+ Ustaw `MARKPACT_PORT` na inny port lub zatrzymaj proces, który używa `8000`.
209
+
210
+ ## 5️⃣ Dependency management
211
+
212
+ - **Python**
213
+ Bootstrap zbiera `markpact:deps python`, zapisuje `requirements.txt` w sandboxie i instaluje zależności.
214
+
215
+ ## 6️⃣ Uruchamianie i workflow
216
+
217
+ - **Wejście**
218
+ `python3 markpact.py [README.md]`
219
+ - **Kolejność**
220
+ Bootstrap parsuje wszystkie codeblocki, zapisuje pliki i dopiero na końcu uruchamia `markpact:run`.
221
+
222
+ ## 6.1 Konwencje i format metadanych
223
+
224
+ - **Nagłówek codeblocka**
225
+ ` ```markpact:<kind> <lang> <meta>`
226
+
227
+ Minimalnie wymagane jest `markpact:<kind>`.
228
+ `lang` jest opcjonalny i pełni rolę informacyjną (bootstrap może go ignorować).
229
+
230
+ - **Metadane**
231
+ Dla `markpact:file` wymagane jest `path=...`.
232
+ Metadane mogą zawierać dodatkowe tokeny (np. w przyszłości `mode=...`, `chmod=...`).
233
+
234
+ ## 6.2 CI/CD
235
+
236
+ - **Rekomendacja**
237
+ Uruchamiaj bootstrap w czystym środowisku (np. job CI) i ustaw sandbox na katalog roboczy joba.
238
+
239
+ - **Przykład (shell)**
240
+
241
+ ```bash
242
+ export MARKPACT_SANDBOX=./.markpact-sandbox
243
+ export MARKPACT_PORT=8001
244
+ python3 markpact.py README.md
245
+ ```
246
+
247
+ - **Wskazówki**
248
+ - **Deterministyczność**
249
+ Pinuj wersje w `markpact:deps` (np. `fastapi==...`).
250
+ - **Bezpieczeństwo**
251
+ Traktuj `markpact:run` jak skrypt uruchomieniowy repo: w CI odpalaj tylko zaufane README.
252
+ - **Cache**
253
+ Jeśli CI wspiera cache, cache’uj katalog `MARKPACT_SANDBOX/.venv`.
254
+
255
+ ## 6.3 Współpraca z LLM
256
+
257
+ - **Zasada**
258
+ LLM może generować/edytować projekt poprzez modyfikacje README (codeblocki `markpact:file`, `markpact:deps`, `markpact:run`).
259
+ - **Oczekiwania**
260
+ - `markpact:file` zawsze zawiera pełną zawartość pliku.
261
+ - Każda zmiana zależności idzie przez `markpact:deps`.
262
+ - Jedna komenda startowa w `markpact:run`.
263
+
264
+ ## 7️⃣ Najlepsze praktyki
265
+
266
+ - **Bootstrap jako pierwszy fenced codeblock w README**
267
+ - **Każdy plik w osobnym `markpact:file`**
268
+ - **Zależności tylko w `markpact:deps`**
269
+ - **Jedna komenda startowa w `markpact:run`**
270
+ - **Ekstrakcja bootstrapu**
271
+ Nie używaj zakresu `/,/```/` (bo ``` może wystąpić w treści, np. w regexie). Używaj `^```$` na końcu.
272
+
273
+ ## 8️⃣ Działający przykład (FastAPI)
274
+
275
+ ## 1️⃣ Dependencies
276
+
277
+ ```markpact:deps python
278
+ fastapi
279
+ uvicorn
280
+ ```
281
+
282
+ ---
283
+
284
+ ## 2️⃣ Application Files
285
+
286
+ ```markpact:file python path=app/main.py
287
+ from fastapi import FastAPI
288
+
289
+ app = FastAPI()
290
+
291
+ @app.get("/")
292
+ def root():
293
+ return {"message": "Hello from Executable Markdown"}
294
+ ```
295
+
296
+ ---
297
+
298
+ ## 3️⃣ Run Command
299
+
300
+ ```markpact:run python
301
+ uvicorn app.main:app --host 0.0.0.0 --port ${MARKPACT_PORT:-8088}
302
+ ```
@@ -0,0 +1,11 @@
1
+ markpact/__init__.py,sha256=4UTDPl1roPua6x5qnuHA8we05we6kvKSf0qvB1I6EOM,407
2
+ markpact/cli.py,sha256=rPb4_S1ysQ4nW7vSsawqUkX_lp27JS99MscdTgFVaw0,4555
3
+ markpact/converter.py,sha256=s9FgHF2bq_PNI39R2I9k3mawrAj1Bc5ugM-gW5mwv9s,9037
4
+ markpact/parser.py,sha256=TrVCuQPTVzNY-CaS1xjI1M6C6InKNjzM3u3zqOGae3k,776
5
+ markpact/runner.py,sha256=h9dHjaZy5lUwrbkmUn9zxPBzASZCvGC5A17XrrWfSaM,1242
6
+ markpact/sandbox.py,sha256=M3VsEXLAYAqvCtd9wGdi1eAxUuKw0LYbCBASYYAr66U,1295
7
+ markpact-0.1.0.dist-info/METADATA,sha256=v8kbO7fgwBoBpfOAyjXZ97Nt2ISQWYH94vZp0FkfcWk,10323
8
+ markpact-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
9
+ markpact-0.1.0.dist-info/entry_points.txt,sha256=eGkiCSFxRDcaQBQbk_-Z0ozxsQnsh3zZDAid0ymNOp4,47
10
+ markpact-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
11
+ markpact-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ markpact = markpact.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.