This commit is contained in:
302
generators.py
Normal file
302
generators.py
Normal file
@@ -0,0 +1,302 @@
|
||||
"""
|
||||
Code generators for different programming languages.
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Optional
|
||||
from .parser import ParsedCurl
|
||||
|
||||
|
||||
class CodeGenerators:
|
||||
def generate(self, parsed: ParsedCurl, language: str) -> str:
|
||||
"""Generate code snippet for the given language."""
|
||||
generators = {
|
||||
'python': self._generate_python,
|
||||
'javascript': self._generate_javascript,
|
||||
'go': self._generate_go,
|
||||
'ruby': self._generate_ruby,
|
||||
'php': self._generate_php,
|
||||
'java': self._generate_java,
|
||||
}
|
||||
|
||||
generator = generators.get(language)
|
||||
if not generator:
|
||||
raise ValueError(f"Unsupported language: {language}")
|
||||
|
||||
return generator(parsed)
|
||||
|
||||
def _generate_python(self, parsed: ParsedCurl) -> str:
|
||||
"""Generate Python code using requests library."""
|
||||
code = ["import requests\n"]
|
||||
|
||||
if parsed.auth:
|
||||
code.append(f"response = requests.{parsed.method.lower()}(")
|
||||
else:
|
||||
code.append(f"response = requests.{parsed.method.lower()}(")
|
||||
|
||||
code.append(f" '{parsed.url}'\n")
|
||||
|
||||
if parsed.headers:
|
||||
code.append(f" headers={json.dumps(parsed.headers, indent=8)}\n")
|
||||
|
||||
if parsed.data:
|
||||
if parsed.content_type and 'application/json' in parsed.content_type:
|
||||
try:
|
||||
json_data = json.loads(parsed.data)
|
||||
code.append(f" json={json.dumps(json_data, indent=8)}\n")
|
||||
except json.JSONDecodeError:
|
||||
code.append(f" data='{parsed.data}'\n")
|
||||
else:
|
||||
data_str = parsed.data.replace("'", "\\'")
|
||||
code.append(f" data='{data_str}'\n")
|
||||
|
||||
if parsed.auth:
|
||||
code.append(f" auth={parsed.auth}\n")
|
||||
|
||||
code.append(")\n")
|
||||
code.append(f"\nprint(response.status_code)")
|
||||
code.append(f"\nprint(response.text)")
|
||||
|
||||
return ''.join(code)
|
||||
|
||||
def _generate_javascript(self, parsed: ParsedCurl) -> str:
|
||||
"""Generate JavaScript code using fetch API."""
|
||||
code = ["const fetchData = async () => {\n"]
|
||||
code.append(" try {\n")
|
||||
|
||||
options_parts = [f"method: '{parsed.method}'"]
|
||||
|
||||
if parsed.headers:
|
||||
options_parts.append(f"headers: {json.dumps(parsed.headers)}")
|
||||
|
||||
if parsed.data:
|
||||
if parsed.content_type and 'application/json' in parsed.content_type:
|
||||
options_parts.append(f"body: JSON.stringify({parsed.data})")
|
||||
else:
|
||||
data_str = parsed.data.replace("'", "\\'")
|
||||
options_parts.append(f"body: '{data_str}'")
|
||||
|
||||
code.append(" const options = {\n")
|
||||
for i, part in enumerate(options_parts):
|
||||
if i > 0:
|
||||
code.append(",\n")
|
||||
code.append(f" {part}")
|
||||
code.append("\n };\n\n")
|
||||
|
||||
code.append(f" const response = await fetch('{parsed.url}', options);\n")
|
||||
code.append(" const data = await response.json();\n")
|
||||
code.append(" console.log(data);\n")
|
||||
code.append(" return data;\n")
|
||||
code.append(" } catch (error) {\n")
|
||||
code.append(" console.error('Error:', error);\n")
|
||||
code.append(" }\n")
|
||||
code.append("}\n\n")
|
||||
code.append("fetchData();")
|
||||
|
||||
return ''.join(code)
|
||||
|
||||
def _generate_go(self, parsed: ParsedCurl) -> str:
|
||||
"""Generate Go code using net/http package."""
|
||||
code = ["package main\n\n"]
|
||||
code.append("import (\n")
|
||||
code.append(' "bytes"\n')
|
||||
code.append(' "encoding/json"\n')
|
||||
code.append(' "fmt"\n')
|
||||
code.append(' "io/ioutil"\n')
|
||||
code.append(' "net/http"\n')
|
||||
code.append(')\n\n')
|
||||
|
||||
code.append("func main() {\n")
|
||||
code.append(f" url := \"{parsed.url}\"\n\n")
|
||||
|
||||
if parsed.method == "GET":
|
||||
code.append(" req, err := http.NewRequest(\"GET\", url, nil)\n")
|
||||
else:
|
||||
data_str = parsed.data if parsed.data else ""
|
||||
code.append(f" jsonData := `{data_str}`\n")
|
||||
code.append(" req, err := http.NewRequest(\"POST\", url, bytes.NewBuffer([]byte(jsonData)))\n")
|
||||
|
||||
code.append(" if err != nil {\n")
|
||||
code.append(" panic(err)\n")
|
||||
code.append(" }\n\n")
|
||||
|
||||
if parsed.headers:
|
||||
for key, value in parsed.headers.items():
|
||||
code.append(f' req.Header.Set(\"{key}\", \"{value}\")\n')
|
||||
code.append("\n")
|
||||
|
||||
if parsed.auth:
|
||||
code.append(f' req.SetBasicAuth(\"{parsed.auth[0]}\", \"{parsed.auth[1]}\")\n\n')
|
||||
|
||||
code.append(" client := &http.Client{}\n")
|
||||
code.append(" resp, err := client.Do(req)\n")
|
||||
code.append(" if err != nil {\n")
|
||||
code.append(" panic(err)\n")
|
||||
code.append(" }\n")
|
||||
code.append(" defer resp.Body.Close()\n\n")
|
||||
|
||||
code.append(" body, err := ioutil.ReadAll(resp.Body)\n")
|
||||
code.append(" if err != nil {\n")
|
||||
code.append(" panic(err)\n")
|
||||
code.append(" }\n\n")
|
||||
|
||||
code.append(" fmt.Println(string(body))\n")
|
||||
code.append("}\n")
|
||||
|
||||
return ''.join(code)
|
||||
|
||||
def _generate_ruby(self, parsed: ParsedCurl) -> str:
|
||||
"""Generate Ruby code using Net::HTTP."""
|
||||
code = ["require 'net/http'\n"]
|
||||
code.append("require 'uri'\n")
|
||||
code.append("require 'json'\n\n")
|
||||
|
||||
code.append(f"uri = URI.parse(\"{parsed.url}\")\n\n")
|
||||
|
||||
code.append("http = Net::HTTP.new(uri.host, uri.port)\n")
|
||||
code.append("http.use_ssl = true if uri.scheme == 'https'\n\n")
|
||||
|
||||
if parsed.method == "GET":
|
||||
code.append("request = Net::HTTP::Get.new(uri)\n")
|
||||
elif parsed.method == "POST":
|
||||
code.append("request = Net::HTTP::Post.new(uri)\n")
|
||||
elif parsed.method == "PUT":
|
||||
code.append("request = Net::HTTP::Put.new(uri)\n")
|
||||
elif parsed.method == "DELETE":
|
||||
code.append("request = Net::HTTP::Delete.new(uri)\n")
|
||||
else:
|
||||
code.append(f"request = Net::HTTP::#{parsed.method}.new(uri)\n")
|
||||
|
||||
for key, value in parsed.headers.items():
|
||||
code.append(f'request[\"{key}\"] = \"{value}\"\n')
|
||||
|
||||
if parsed.data:
|
||||
if parsed.content_type and 'application/json' in parsed.content_type:
|
||||
code.append(f"request.body = {parsed.data}\n")
|
||||
else:
|
||||
data_str = parsed.data.replace('"', '\\"')
|
||||
code.append(f"request.body = \"{data_str}\"\n")
|
||||
|
||||
if parsed.auth:
|
||||
code.append(f'request.basic_auth \"{parsed.auth[0]}\", \"{parsed.auth[1]}\"\n')
|
||||
|
||||
code.append("\nresponse = http.request(request)\n")
|
||||
code.append("puts response.code\n")
|
||||
code.append("puts response.body\n")
|
||||
|
||||
return ''.join(code)
|
||||
|
||||
def _generate_php(self, parsed: ParsedCurl) -> str:
|
||||
"""Generate PHP code using cURL."""
|
||||
code = ["<?php\n\n"]
|
||||
code.append("$url = \"" + parsed.url + ";\n\n")
|
||||
|
||||
code.append("$ch = curl_init();\n\n")
|
||||
|
||||
code.append("curl_setopt($ch, CURLOPT_URL, $url);\n")
|
||||
code.append(f"curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n")
|
||||
|
||||
if parsed.method == "POST":
|
||||
code.append("curl_setopt($ch, CURLOPT_POST, true);\n")
|
||||
if parsed.data:
|
||||
data_str = parsed.data.replace('"', '\\"')
|
||||
code.append(f"curl_setopt($ch, CURLOPT_POSTFIELDS, \"{data_str}\");\n")
|
||||
elif parsed.method != "GET":
|
||||
code.append(f"curl_setopt($ch, CURLOPT_CUSTOMREQUEST, \"{parsed.method}\");\n")
|
||||
if parsed.data:
|
||||
data_str = parsed.data.replace('"', '\\"')
|
||||
code.append(f"curl_setopt($ch, CURLOPT_POSTFIELDS, \"{data_str}\");\n")
|
||||
|
||||
code.append("curl_setopt($ch, CURLOPT_HTTPHEADER, [\n")
|
||||
headers_lines = []
|
||||
for key, value in parsed.headers.items():
|
||||
headers_lines.append(f" \"{key}: {value}\"")
|
||||
if headers_lines:
|
||||
code.append(",\n".join(headers_lines) + "\n")
|
||||
code.append("]);\n\n")
|
||||
|
||||
if parsed.auth:
|
||||
code.append(f'curl_setopt($ch, CURLOPT_USERPWD, \"{parsed.auth[0]}:{parsed.auth[1]}\");\n\n')
|
||||
|
||||
code.append("$response = curl_exec($ch);\n\n")
|
||||
|
||||
code.append("if (curl_errno($ch)) {\n")
|
||||
code.append(" echo 'Error:' . curl_error($ch);\n")
|
||||
code.append("}\n\n")
|
||||
|
||||
code.append("curl_close($ch);\n\n")
|
||||
code.append("echo $response;\n")
|
||||
code.append("?>\n")
|
||||
|
||||
return ''.join(code)
|
||||
|
||||
def _generate_java(self, parsed: ParsedCurl) -> str:
|
||||
"""Generate Java code using HttpURLConnection."""
|
||||
code = ["import java.io.*;\n"]
|
||||
code.append("import java.net.*;\n")
|
||||
code.append("import java.nio.charset.StandardCharsets;\n\n")
|
||||
|
||||
code.append("public class ApiClient {\n")
|
||||
code.append(" public static void main(String[] args) {\n")
|
||||
code.append(" try {\n")
|
||||
code.append(f" String url = \"{parsed.url}\";\n\n")
|
||||
|
||||
code.append(" URL obj = new URL(url);\n")
|
||||
code.append(" HttpURLConnection con = (HttpURLConnection) obj.openConnection();\n\n")
|
||||
|
||||
code.append(f" con.setRequestMethod(\"{parsed.method}\");\n\n")
|
||||
|
||||
for key, value in parsed.headers.items():
|
||||
code.append(f' con.setRequestProperty(\"{key}\", \"{value}\");\n')
|
||||
|
||||
if parsed.auth:
|
||||
code.append(f' String auth = \"{parsed.auth[0]}:{parsed.auth[1]}\";\n')
|
||||
code.append(' String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));\n')
|
||||
code.append(' con.setRequestProperty(\"Authorization\", \"Basic \" + encodedAuth);\n')
|
||||
|
||||
if parsed.data:
|
||||
code.append("\n String urlParameters = ")
|
||||
data_str = parsed.data.replace('"', '\\"')
|
||||
code.append(f'"{data_str}";\n')
|
||||
code.append("\n con.setDoOutput(true);\n")
|
||||
code.append(" try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {\n")
|
||||
code.append(" wr.writeBytes(urlParameters);\n")
|
||||
code.append(" wr.flush();\n")
|
||||
code.append(" }\n")
|
||||
|
||||
code.append("\n int responseCode = con.getResponseCode();\n")
|
||||
code.append(" System.out.println(\"Response Code: \" + responseCode);\n\n")
|
||||
|
||||
code.append(" try (BufferedReader in = new BufferedReader(\n")
|
||||
code.append(" new InputStreamReader(con.getInputStream()))) {\n")
|
||||
code.append(" String inputLine;\n")
|
||||
code.append(" StringBuffer response = new StringBuffer();\n")
|
||||
code.append(" while ((inputLine = in.readLine()) != null) {\n")
|
||||
code.append(" response.append(inputLine);\n")
|
||||
code.append(" }\n")
|
||||
code.append(" System.out.println(response.toString());\n")
|
||||
code.append(" }\n")
|
||||
|
||||
code.append(" } catch (Exception e) {\n")
|
||||
code.append(" e.printStackTrace();\n")
|
||||
code.append(" }\n")
|
||||
code.append(" }\n")
|
||||
code.append("}\n")
|
||||
|
||||
return ''.join(code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parsed = ParsedCurl(
|
||||
url="https://api.example.com/data",
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json", "Authorization": "Bearer token"},
|
||||
data='{"key": "value"}',
|
||||
auth=("user", "pass")
|
||||
)
|
||||
gen = CodeGenerators()
|
||||
print("Python:")
|
||||
print(gen._generate_python(parsed))
|
||||
print("\n" + "="*50 + "\n")
|
||||
print("JavaScript:")
|
||||
print(gen._generate_javascript(parsed))
|
||||
Reference in New Issue
Block a user