Skip to content

Make this program itself a polyglot #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions bin/merge
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
1 // (lambda: exec(open("bin/merge.py").read(), globals()) or 1)()
lambda: eval("(function(){const fs=require('node:fs');const data=fs.readFileSync('bin/merge.js','utf8');return eval(data)})();")
5 changes: 3 additions & 2 deletions bin/merge.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#!/usr/bin/env node

import fs from 'fs/promises';
import path from 'path';
const fs = require('fs/promises');
const path = require('path');

async function main() {
const args = process.argv.slice(2);
console.log("This script is running in JavaScript");

if (args.length < 2) {
console.error('Usage: polycompiler <file1> <file2> [output-file]');
Expand Down
82 changes: 82 additions & 0 deletions bin/merge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env python3

import os
import sys
import pathlib

def merge_files(python_content, js_content):
# Escape backslashes first, then newlines, then quotes
escaped_python_content = python_content.replace('\\', '\\\\').replace('\n', '\\n').replace('"""', '\\"\\"\\"')

# Escape backslashes first, then newlines, then quotes
escaped_js_content = js_content.replace('\\', '\\\\').replace('\n', '\\n').replace('"', '\\"')

return '1 // (lambda: exec("""' + escaped_python_content + '""", globals()) or 1)()\nlambda: eval("' + escaped_js_content + '")'

def main():
args = sys.argv[1:]

print("This script runs in Python")

if len(args) < 2:
print('Usage: polycompiler <file1> <file2> [output-file]')
sys.exit(1)

file1_path = args[0]
file2_path = args[1]
output_path = args[2] if len(args) > 2 else 'out/result.py.js'

# Check if files exist
if not os.path.exists(file1_path) or not os.path.exists(file2_path):
print('Error: One or more input files do not exist.')
sys.exit(1)

# Get file extensions
ext1 = pathlib.Path(file1_path).suffix.lower()
ext2 = pathlib.Path(file2_path).suffix.lower()

# Check if one is Python and one is JavaScript
def is_python(ext):
return ext in ['.py']

def is_javascript(ext):
return ext in ['.js', '.cjs', '.mjs']

has_python = is_python(ext1) or is_python(ext2)
has_js = is_javascript(ext1) or is_javascript(ext2)

if not (has_python and has_js):
print(f"Merging {ext1[1:]} and {ext2[1:]} is not supported. Only Python and JavaScript files can be merged.")
sys.exit(1)

# Read file contents
with open(file1_path, 'r', encoding='utf-8') as f:
content1 = f.read()

with open(file2_path, 'r', encoding='utf-8') as f:
content2 = f.read()

# Determine which file is Python and which is JavaScript
python_content = content1 if is_python(ext1) else content2
js_content = content1 if is_javascript(ext1) else content2

# Merge the files
merged = merge_files(python_content, js_content)

# Ensure the output directory exists
output_dir = os.path.dirname(output_path)
if output_dir:
os.makedirs(output_dir, exist_ok=True)

# Write the result to the output file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(merged)

print(f"Merged files written to {output_path}")

if __name__ == "__main__":
try:
main()
except Exception as err:
print(f"Error: {err}")
sys.exit(1)
38 changes: 17 additions & 21 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
{
"name": "polycompiler",
"version": "1.0.0",
"description": "Merge Python and JS code into one file that can be run in both languages.",
"license": "GPL-3.0-only",
"author": "",
"type": "module",
"bin": {
"polycompiler": "bin/merge.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/EvanZhouDev/polycompiler.git"
},
"homepage": "https://github.com/EvanZhouDev/polycompiler",
"keywords": [
"js",
"python"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
}
"name": "polycompiler",
"version": "1.0.0",
"description": "Merge Python and JS code into one file that can be run in both languages.",
"license": "GPL-3.0-only",
"author": "",
"bin": {
"polycompiler": "bin/merge"
},
"repository": {
"type": "git",
"url": "git+https://github.com/EvanZhouDev/polycompiler.git"
},
"homepage": "https://github.com/EvanZhouDev/polycompiler",
"keywords": [
"js",
"python"
]
}
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.