@ohos-ports/curlconverter 4.12.0-beta.0

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.
Files changed (270) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +153 -0
  3. package/dist/src/Headers.d.ts +23 -0
  4. package/dist/src/Headers.js +287 -0
  5. package/dist/src/Headers.js.map +1 -0
  6. package/dist/src/Query.d.ts +8 -0
  7. package/dist/src/Query.js +136 -0
  8. package/dist/src/Query.js.map +1 -0
  9. package/dist/src/Request.d.ts +200 -0
  10. package/dist/src/Request.js +1191 -0
  11. package/dist/src/Request.js.map +1 -0
  12. package/dist/src/Warnings.d.ts +15 -0
  13. package/dist/src/Warnings.js +111 -0
  14. package/dist/src/Warnings.js.map +1 -0
  15. package/dist/src/cli.d.ts +2 -0
  16. package/dist/src/cli.js +333 -0
  17. package/dist/src/cli.js.map +1 -0
  18. package/dist/src/curl/auth.d.ts +12 -0
  19. package/dist/src/curl/auth.js +40 -0
  20. package/dist/src/curl/auth.js.map +1 -0
  21. package/dist/src/curl/form.d.ts +28 -0
  22. package/dist/src/curl/form.js +218 -0
  23. package/dist/src/curl/form.js.map +1 -0
  24. package/dist/src/curl/opts.d.ts +2052 -0
  25. package/dist/src/curl/opts.js +1000 -0
  26. package/dist/src/curl/opts.js.map +1 -0
  27. package/dist/src/curl/url.d.ts +14 -0
  28. package/dist/src/curl/url.js +218 -0
  29. package/dist/src/curl/url.js.map +1 -0
  30. package/dist/src/generators/ansible.d.ts +5 -0
  31. package/dist/src/generators/ansible.js +282 -0
  32. package/dist/src/generators/ansible.js.map +1 -0
  33. package/dist/src/generators/c.d.ts +12 -0
  34. package/dist/src/generators/c.js +1230 -0
  35. package/dist/src/generators/c.js.map +1 -0
  36. package/dist/src/generators/cfml.d.ts +5 -0
  37. package/dist/src/generators/cfml.js +134 -0
  38. package/dist/src/generators/cfml.js.map +1 -0
  39. package/dist/src/generators/clojure.d.ts +7 -0
  40. package/dist/src/generators/clojure.js +436 -0
  41. package/dist/src/generators/clojure.js.map +1 -0
  42. package/dist/src/generators/csharp.d.ts +8 -0
  43. package/dist/src/generators/csharp.js +356 -0
  44. package/dist/src/generators/csharp.js.map +1 -0
  45. package/dist/src/generators/dart.d.ts +5 -0
  46. package/dist/src/generators/dart.js +273 -0
  47. package/dist/src/generators/dart.js.map +1 -0
  48. package/dist/src/generators/elixir.d.ts +8 -0
  49. package/dist/src/generators/elixir.js +296 -0
  50. package/dist/src/generators/elixir.js.map +1 -0
  51. package/dist/src/generators/go.d.ts +5 -0
  52. package/dist/src/generators/go.js +228 -0
  53. package/dist/src/generators/go.js.map +1 -0
  54. package/dist/src/generators/har.d.ts +7 -0
  55. package/dist/src/generators/har.js +115 -0
  56. package/dist/src/generators/har.js.map +1 -0
  57. package/dist/src/generators/http.d.ts +7 -0
  58. package/dist/src/generators/http.js +165 -0
  59. package/dist/src/generators/http.js.map +1 -0
  60. package/dist/src/generators/httpie.d.ts +5 -0
  61. package/dist/src/generators/httpie.js +446 -0
  62. package/dist/src/generators/httpie.js.map +1 -0
  63. package/dist/src/generators/java/httpurlconnection.d.ts +5 -0
  64. package/dist/src/generators/java/httpurlconnection.js +123 -0
  65. package/dist/src/generators/java/httpurlconnection.js.map +1 -0
  66. package/dist/src/generators/java/java.d.ts +8 -0
  67. package/dist/src/generators/java/java.js +247 -0
  68. package/dist/src/generators/java/java.js.map +1 -0
  69. package/dist/src/generators/java/jsoup.d.ts +5 -0
  70. package/dist/src/generators/java/jsoup.js +152 -0
  71. package/dist/src/generators/java/jsoup.js.map +1 -0
  72. package/dist/src/generators/java/okhttp.d.ts +5 -0
  73. package/dist/src/generators/java/okhttp.js +232 -0
  74. package/dist/src/generators/java/okhttp.js.map +1 -0
  75. package/dist/src/generators/javascript/axios.d.ts +5 -0
  76. package/dist/src/generators/javascript/axios.js +332 -0
  77. package/dist/src/generators/javascript/axios.js.map +1 -0
  78. package/dist/src/generators/javascript/got.d.ts +5 -0
  79. package/dist/src/generators/javascript/got.js +277 -0
  80. package/dist/src/generators/javascript/got.js.map +1 -0
  81. package/dist/src/generators/javascript/http.d.ts +8 -0
  82. package/dist/src/generators/javascript/http.js +183 -0
  83. package/dist/src/generators/javascript/http.js.map +1 -0
  84. package/dist/src/generators/javascript/javascript.d.ts +37 -0
  85. package/dist/src/generators/javascript/javascript.js +676 -0
  86. package/dist/src/generators/javascript/javascript.js.map +1 -0
  87. package/dist/src/generators/javascript/jquery.d.ts +15 -0
  88. package/dist/src/generators/javascript/jquery.js +297 -0
  89. package/dist/src/generators/javascript/jquery.js.map +1 -0
  90. package/dist/src/generators/javascript/ky.d.ts +7 -0
  91. package/dist/src/generators/javascript/ky.js +245 -0
  92. package/dist/src/generators/javascript/ky.js.map +1 -0
  93. package/dist/src/generators/javascript/request.d.ts +5 -0
  94. package/dist/src/generators/javascript/request.js +113 -0
  95. package/dist/src/generators/javascript/request.js.map +1 -0
  96. package/dist/src/generators/javascript/superagent.d.ts +10 -0
  97. package/dist/src/generators/javascript/superagent.js +301 -0
  98. package/dist/src/generators/javascript/superagent.js.map +1 -0
  99. package/dist/src/generators/javascript/xhr.d.ts +8 -0
  100. package/dist/src/generators/javascript/xhr.js +147 -0
  101. package/dist/src/generators/javascript/xhr.js.map +1 -0
  102. package/dist/src/generators/json.d.ts +45 -0
  103. package/dist/src/generators/json.js +197 -0
  104. package/dist/src/generators/json.js.map +1 -0
  105. package/dist/src/generators/julia.d.ts +8 -0
  106. package/dist/src/generators/julia.js +365 -0
  107. package/dist/src/generators/julia.js.map +1 -0
  108. package/dist/src/generators/kotlin.d.ts +8 -0
  109. package/dist/src/generators/kotlin.js +325 -0
  110. package/dist/src/generators/kotlin.js.map +1 -0
  111. package/dist/src/generators/lua.d.ts +5 -0
  112. package/dist/src/generators/lua.js +192 -0
  113. package/dist/src/generators/lua.js.map +1 -0
  114. package/dist/src/generators/matlab/common.d.ts +16 -0
  115. package/dist/src/generators/matlab/common.js +238 -0
  116. package/dist/src/generators/matlab/common.js.map +1 -0
  117. package/dist/src/generators/matlab/httpinterface.d.ts +2 -0
  118. package/dist/src/generators/matlab/httpinterface.js +211 -0
  119. package/dist/src/generators/matlab/httpinterface.js.map +1 -0
  120. package/dist/src/generators/matlab/matlab.d.ts +5 -0
  121. package/dist/src/generators/matlab/matlab.js +29 -0
  122. package/dist/src/generators/matlab/matlab.js.map +1 -0
  123. package/dist/src/generators/matlab/webservices.d.ts +2 -0
  124. package/dist/src/generators/matlab/webservices.js +191 -0
  125. package/dist/src/generators/matlab/webservices.js.map +1 -0
  126. package/dist/src/generators/objectivec.d.ts +8 -0
  127. package/dist/src/generators/objectivec.js +269 -0
  128. package/dist/src/generators/objectivec.js.map +1 -0
  129. package/dist/src/generators/ocaml.d.ts +8 -0
  130. package/dist/src/generators/ocaml.js +150 -0
  131. package/dist/src/generators/ocaml.js.map +1 -0
  132. package/dist/src/generators/perl.d.ts +9 -0
  133. package/dist/src/generators/perl.js +209 -0
  134. package/dist/src/generators/perl.js.map +1 -0
  135. package/dist/src/generators/php/guzzle.d.ts +5 -0
  136. package/dist/src/generators/php/guzzle.js +328 -0
  137. package/dist/src/generators/php/guzzle.js.map +1 -0
  138. package/dist/src/generators/php/php.d.ts +8 -0
  139. package/dist/src/generators/php/php.js +217 -0
  140. package/dist/src/generators/php/php.js.map +1 -0
  141. package/dist/src/generators/php/requests.d.ts +5 -0
  142. package/dist/src/generators/php/requests.js +89 -0
  143. package/dist/src/generators/php/requests.js.map +1 -0
  144. package/dist/src/generators/powershell.d.ts +11 -0
  145. package/dist/src/generators/powershell.js +377 -0
  146. package/dist/src/generators/powershell.js.map +1 -0
  147. package/dist/src/generators/python/http.d.ts +5 -0
  148. package/dist/src/generators/python/http.js +128 -0
  149. package/dist/src/generators/python/http.js.map +1 -0
  150. package/dist/src/generators/python/python.d.ts +22 -0
  151. package/dist/src/generators/python/python.js +1693 -0
  152. package/dist/src/generators/python/python.js.map +1 -0
  153. package/dist/src/generators/r/httr.d.ts +10 -0
  154. package/dist/src/generators/r/httr.js +298 -0
  155. package/dist/src/generators/r/httr.js.map +1 -0
  156. package/dist/src/generators/r/httr2.d.ts +5 -0
  157. package/dist/src/generators/r/httr2.js +214 -0
  158. package/dist/src/generators/r/httr2.js.map +1 -0
  159. package/dist/src/generators/ruby/httparty.d.ts +6 -0
  160. package/dist/src/generators/ruby/httparty.js +308 -0
  161. package/dist/src/generators/ruby/httparty.js.map +1 -0
  162. package/dist/src/generators/ruby/ruby.d.ts +14 -0
  163. package/dist/src/generators/ruby/ruby.js +515 -0
  164. package/dist/src/generators/ruby/ruby.js.map +1 -0
  165. package/dist/src/generators/rust.d.ts +8 -0
  166. package/dist/src/generators/rust.js +177 -0
  167. package/dist/src/generators/rust.js.map +1 -0
  168. package/dist/src/generators/swift.d.ts +8 -0
  169. package/dist/src/generators/swift.js +219 -0
  170. package/dist/src/generators/swift.js.map +1 -0
  171. package/dist/src/generators/wget.d.ts +8 -0
  172. package/dist/src/generators/wget.js +472 -0
  173. package/dist/src/generators/wget.js.map +1 -0
  174. package/dist/src/index.d.ts +53 -0
  175. package/dist/src/index.js +54 -0
  176. package/dist/src/index.js.map +1 -0
  177. package/dist/src/parse.d.ts +13 -0
  178. package/dist/src/parse.js +43 -0
  179. package/dist/src/parse.js.map +1 -0
  180. package/dist/src/shell/Parser.d.ts +4 -0
  181. package/dist/src/shell/Parser.js +6 -0
  182. package/dist/src/shell/Parser.js.map +1 -0
  183. package/dist/src/shell/Word.d.ts +48 -0
  184. package/dist/src/shell/Word.js +486 -0
  185. package/dist/src/shell/Word.js.map +1 -0
  186. package/dist/src/shell/tokenizer.d.ts +3 -0
  187. package/dist/src/shell/tokenizer.js +610 -0
  188. package/dist/src/shell/tokenizer.js.map +1 -0
  189. package/dist/src/shell/webParser.d.ts +4 -0
  190. package/dist/src/shell/webParser.js +15 -0
  191. package/dist/src/shell/webParser.js.map +1 -0
  192. package/dist/src/utils.d.ts +6 -0
  193. package/dist/src/utils.js +21 -0
  194. package/dist/src/utils.js.map +1 -0
  195. package/dist/tools/compare-requests.d.ts +2 -0
  196. package/dist/tools/compare-requests.js +448 -0
  197. package/dist/tools/compare-requests.js.map +1 -0
  198. package/dist/tools/gen-test.d.ts +2 -0
  199. package/dist/tools/gen-test.js +114 -0
  200. package/dist/tools/gen-test.js.map +1 -0
  201. package/dist/tree-sitter-bash.wasm +0 -0
  202. package/index.d.ts +3 -0
  203. package/package.json +97 -0
  204. package/src/Headers.ts +334 -0
  205. package/src/Query.ts +147 -0
  206. package/src/Request.ts +1649 -0
  207. package/src/Warnings.ts +154 -0
  208. package/src/cli.ts +561 -0
  209. package/src/curl/auth.ts +45 -0
  210. package/src/curl/form.ts +297 -0
  211. package/src/curl/opts.ts +1417 -0
  212. package/src/curl/url.ts +241 -0
  213. package/src/generators/ansible.ts +364 -0
  214. package/src/generators/c.ts +1371 -0
  215. package/src/generators/cfml.ts +155 -0
  216. package/src/generators/clojure.ts +521 -0
  217. package/src/generators/csharp.ts +383 -0
  218. package/src/generators/dart.ts +293 -0
  219. package/src/generators/elixir.ts +349 -0
  220. package/src/generators/go.ts +269 -0
  221. package/src/generators/har.ts +147 -0
  222. package/src/generators/http.ts +194 -0
  223. package/src/generators/httpie.ts +506 -0
  224. package/src/generators/java/httpurlconnection.ts +151 -0
  225. package/src/generators/java/java.ts +280 -0
  226. package/src/generators/java/jsoup.ts +172 -0
  227. package/src/generators/java/okhttp.ts +257 -0
  228. package/src/generators/javascript/axios.ts +395 -0
  229. package/src/generators/javascript/got.ts +362 -0
  230. package/src/generators/javascript/http.ts +232 -0
  231. package/src/generators/javascript/javascript.ts +825 -0
  232. package/src/generators/javascript/jquery.ts +360 -0
  233. package/src/generators/javascript/ky.ts +315 -0
  234. package/src/generators/javascript/request.ts +152 -0
  235. package/src/generators/javascript/superagent.ts +373 -0
  236. package/src/generators/javascript/xhr.ts +192 -0
  237. package/src/generators/json.ts +293 -0
  238. package/src/generators/julia.ts +398 -0
  239. package/src/generators/kotlin.ts +355 -0
  240. package/src/generators/lua.ts +209 -0
  241. package/src/generators/matlab/common.ts +281 -0
  242. package/src/generators/matlab/httpinterface.ts +284 -0
  243. package/src/generators/matlab/matlab.ts +39 -0
  244. package/src/generators/matlab/webservices.ts +263 -0
  245. package/src/generators/objectivec.ts +297 -0
  246. package/src/generators/ocaml.ts +168 -0
  247. package/src/generators/perl.ts +237 -0
  248. package/src/generators/php/guzzle.ts +368 -0
  249. package/src/generators/php/php.ts +239 -0
  250. package/src/generators/php/requests.ts +103 -0
  251. package/src/generators/powershell.ts +430 -0
  252. package/src/generators/python/http.ts +167 -0
  253. package/src/generators/python/python.ts +1934 -0
  254. package/src/generators/r/httr.ts +328 -0
  255. package/src/generators/r/httr2.ts +268 -0
  256. package/src/generators/ruby/httparty.ts +351 -0
  257. package/src/generators/ruby/ruby.ts +564 -0
  258. package/src/generators/rust.ts +243 -0
  259. package/src/generators/swift.ts +235 -0
  260. package/src/generators/wget.ts +533 -0
  261. package/src/index.ts +89 -0
  262. package/src/parse.ts +72 -0
  263. package/src/shell/Parser.ts +8 -0
  264. package/src/shell/Word.ts +531 -0
  265. package/src/shell/tokenizer.ts +736 -0
  266. package/src/shell/webParser.ts +18 -0
  267. package/src/utils.ts +25 -0
  268. package/tools/compare-requests.ts +571 -0
  269. package/tools/extract_curl_args.py +511 -0
  270. package/tools/gen-test.ts +129 -0
@@ -0,0 +1,349 @@
1
+ import { warnIfPartsIgnored } from "../Warnings.js";
2
+ import { Word, joinWords } from "../shell/Word.js";
3
+ import { parse, COMMON_SUPPORTED_ARGS } from "../parse.js";
4
+ import type { Request, Warnings } from "../parse.js";
5
+ import { parseQueryString } from "../Query.js";
6
+
7
+ export const supportedArgs = new Set([
8
+ ...COMMON_SUPPORTED_ARGS,
9
+ "form",
10
+ "form-string",
11
+ "insecure",
12
+ "no-insecure",
13
+ "next",
14
+ ]);
15
+
16
+ const regexEscape = /"|\\|\p{C}|[^ \P{Z}]|#\{/gu;
17
+
18
+ export function reprStr(s: string): string {
19
+ return (
20
+ '"' +
21
+ s.replace(regexEscape, (c: string): string => {
22
+ switch (c[0]) {
23
+ case "\x00":
24
+ return "\\0";
25
+ case "\x07":
26
+ return "\\a";
27
+ case "\b":
28
+ return "\\b";
29
+ case "\f":
30
+ return "\\f";
31
+ case "\n":
32
+ return "\\n";
33
+ case "\r":
34
+ return "\\r";
35
+ case "\t":
36
+ return "\\t";
37
+ case "\v":
38
+ return "\\v";
39
+ case "\x1B":
40
+ return "\\e";
41
+ case "\\":
42
+ return "\\\\";
43
+ case '"':
44
+ return '\\"';
45
+ case "#":
46
+ return "\\" + c;
47
+ }
48
+ const hex = (c.codePointAt(0) as number).toString(16);
49
+ if (hex.length <= 4) {
50
+ return "\\u" + hex.padStart(4, "0");
51
+ }
52
+ return "\\u{" + hex + "}";
53
+ }) +
54
+ '"'
55
+ );
56
+ }
57
+
58
+ export function repr(w: Word): string {
59
+ const args: string[] = [];
60
+ for (const t of w.tokens) {
61
+ if (typeof t === "string") {
62
+ args.push(reprStr(t));
63
+ } else if (t.type === "variable") {
64
+ args.push("System.get_env(" + reprStr(t.value) + ', "")');
65
+ } else {
66
+ // TODO: strip newline?
67
+ // TODO: use System.cmd(), which needs to be two arguments the command name + list of args
68
+ args.push("elem(System.shell(" + reprStr(t.value) + "), 0)");
69
+ }
70
+ }
71
+ return args.join(" <> ");
72
+ }
73
+
74
+ function addIndent(value: string): string {
75
+ // split on new lines and add 2 spaces of indentation to each line, except empty lines
76
+ return value
77
+ .split("\n")
78
+ .map((line) => (line ? " " + line : line))
79
+ .join("\n");
80
+ }
81
+
82
+ function getCookies(request: Request): string {
83
+ if (!request.cookies || !request.cookies.length) {
84
+ return "";
85
+ }
86
+
87
+ // TODO: this duplicates work, just get it from request.headers
88
+ const cookies = joinWords(
89
+ request.cookies.map((c) => joinWords(c, "=")),
90
+ "; ",
91
+ );
92
+ return `cookie: [${repr(cookies)}]`;
93
+ }
94
+
95
+ function getOptions(request: Request, params: string): [string, string] {
96
+ const hackneyOptions: string[] = [];
97
+
98
+ const auth = getBasicAuth(request);
99
+ if (auth) {
100
+ hackneyOptions.push(auth);
101
+ }
102
+
103
+ if (request.insecure) {
104
+ hackneyOptions.push(":insecure");
105
+ }
106
+
107
+ const cookies = getCookies(request);
108
+ if (cookies) {
109
+ hackneyOptions.push(cookies);
110
+ }
111
+
112
+ let hackneyOptionsString = "";
113
+ if (hackneyOptions.length > 1) {
114
+ hackneyOptionsString = `hackney: [\n ${hackneyOptions.join(
115
+ ",\n ",
116
+ )}\n ]`;
117
+ } else if (hackneyOptions.length) {
118
+ hackneyOptionsString = `hackney: [${hackneyOptions[0]}]`;
119
+ }
120
+
121
+ const optionsWithoutParams = `[${hackneyOptionsString}]`;
122
+ let options = optionsWithoutParams;
123
+ if (params !== "[]") {
124
+ options = "";
125
+ options += "[\n";
126
+ options += " params: " + addIndent(params).trim();
127
+ if (hackneyOptionsString) {
128
+ options += ",\n";
129
+ options += " " + addIndent(hackneyOptionsString).trim();
130
+ }
131
+ options += "\n";
132
+ options += " ]";
133
+ }
134
+ return [options, optionsWithoutParams];
135
+ }
136
+
137
+ function getBasicAuth(request: Request): string {
138
+ if (!request.urls[0].auth) {
139
+ return "";
140
+ }
141
+
142
+ const [user, password] = request.urls[0].auth;
143
+ return `basic_auth: {${repr(user)}, ${repr(password)}}`;
144
+ }
145
+
146
+ function getQueryDict(request: Request): string {
147
+ if (!request.urls[0].queryList || !request.urls[0].queryList.length) {
148
+ return "[]";
149
+ }
150
+ let queryDict = "[\n";
151
+ const queryDictLines: string[] = [];
152
+ for (const [paramName, rawValue] of request.urls[0].queryList) {
153
+ queryDictLines.push(` {${repr(paramName)}, ${repr(rawValue)}}`);
154
+ }
155
+ queryDict += queryDictLines.join(",\n");
156
+ queryDict += "\n ]";
157
+ return queryDict;
158
+ }
159
+
160
+ function getHeadersDict(request: Request): string {
161
+ if (!request.headers.length) {
162
+ return "[]";
163
+ }
164
+ let dict = "[\n";
165
+ const dictLines: string[] = [];
166
+ for (const [headerName, headerValue] of request.headers) {
167
+ dictLines.push(
168
+ ` {${repr(headerName)}, ${repr(headerValue ?? new Word())}}`,
169
+ );
170
+ }
171
+ dict += dictLines.join(",\n");
172
+ dict += "\n ]";
173
+ return dict;
174
+ }
175
+
176
+ function getBody(request: Request): string {
177
+ const formData = getFormDataString(request);
178
+ return formData ? formData : '""';
179
+ }
180
+
181
+ function getFormDataString(request: Request): string {
182
+ if (request.multipartUploads) {
183
+ if (!request.multipartUploads.length) {
184
+ return `{:multipart, []}`;
185
+ }
186
+
187
+ const formParams: string[] = [];
188
+ for (const m of request.multipartUploads) {
189
+ if ("contentFile" in m) {
190
+ formParams.push(
191
+ ` {:file, ${repr(m.contentFile)}, {"form-data", [{:name, ${repr(
192
+ m.name,
193
+ )}}, {:filename, Path.basename(${repr(
194
+ m.filename ?? m.contentFile,
195
+ )})}]}, []}`,
196
+ );
197
+ } else {
198
+ formParams.push(` {${repr(m.name)}, ${repr(m.content)}}`);
199
+ }
200
+ }
201
+
202
+ const formStr = formParams.join(",\n");
203
+ if (formStr) {
204
+ return `{:multipart, [
205
+ ${formStr}
206
+ ]}`;
207
+ }
208
+ }
209
+
210
+ if (request.data) {
211
+ return getDataString(request);
212
+ }
213
+
214
+ return "";
215
+ }
216
+
217
+ function getDataString(request: Request): string {
218
+ if (!request.data) {
219
+ return "";
220
+ }
221
+
222
+ // TODO: JSON with Poison
223
+
224
+ if (!request.isDataRaw && request.data.startsWith("@")) {
225
+ const filePath = request.data.slice(1);
226
+ if (request.isDataBinary) {
227
+ return `File.read!(${repr(filePath)})`;
228
+ } else {
229
+ return `{:file, ${repr(filePath)}}`;
230
+ }
231
+ }
232
+
233
+ const [parsedQuery] = parseQueryString(request.data);
234
+ if (parsedQuery && parsedQuery.length) {
235
+ const data = parsedQuery.map((p) => {
236
+ const [key, value] = p;
237
+ return ` {${repr(key)}, ${repr(value)}}`;
238
+ });
239
+ return `{:form, [\n${data.join(",\n")}\n ]}`;
240
+ }
241
+
242
+ if (
243
+ request.data.isString() &&
244
+ !request.data.includes("|") &&
245
+ request.data.split("\n", 4).length > 3 &&
246
+ // No trailing whitespace, except possibly on the last line
247
+ !request.data.match(/[^\S\r\n]\n/)
248
+ ) {
249
+ return "~s|" + request.data.toString() + "|";
250
+ }
251
+ return repr(request.data);
252
+ }
253
+
254
+ function requestToElixir(request: Request, warnings: Warnings = []): string {
255
+ warnIfPartsIgnored(request, warnings);
256
+ if (request.cookies) {
257
+ request.headers.delete("cookie");
258
+ }
259
+
260
+ // delete!(url, headers \\ [], options \\ [])
261
+ // get!(url, headers \\ [], options \\ [])
262
+ // head!(url, headers \\ [], options \\ [])
263
+ // options!(url, headers \\ [], options \\ [])
264
+ // patch!(url, body, headers \\ [], options \\ [])
265
+ // post!(url, body, headers \\ [], options \\ [])
266
+ // put!(url, body \\ "", headers \\ [], options \\ [])
267
+ const methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"];
268
+ const bodyMethods = ["PATCH", "POST", "PUT"];
269
+ const method = request.urls[0].method;
270
+ const methodStr = method.toString();
271
+ if (!methods.includes(methodStr)) {
272
+ warnings.push([
273
+ "bad-method",
274
+ "Unsupported method " + JSON.stringify(methodStr),
275
+ ]);
276
+ }
277
+
278
+ const isBodyMethod = bodyMethods.includes(methodStr);
279
+ const body = getBody(request);
280
+ const headers = getHeadersDict(request);
281
+ const params = getQueryDict(request);
282
+ // params can go in the options argument, but if we're using the full
283
+ // form, put them as a separate argument.
284
+ const [options, optionsWithoutParams] = getOptions(request, params);
285
+
286
+ if (isBodyMethod || (body === '""' && methods.includes(methodStr))) {
287
+ // Add args backwards. As soon as we see a non-default value, we have to
288
+ // add all preceding arguments.
289
+ let args: string[] = [];
290
+ let keepArgs = false;
291
+ keepArgs ||= options !== "[]";
292
+ if (keepArgs) {
293
+ args.push(options);
294
+ }
295
+ keepArgs ||= headers !== "[]";
296
+ if (keepArgs) {
297
+ args.push(headers);
298
+ }
299
+ keepArgs ||= body !== '""';
300
+ if (keepArgs && isBodyMethod) {
301
+ args.push(body);
302
+ }
303
+ args.push(repr(request.urls[0].urlWithoutQueryList));
304
+ args = args.reverse();
305
+
306
+ let s = "response = HTTPoison." + methodStr.toLowerCase() + "!(";
307
+ if (args.length === 1) {
308
+ // If we just need the method+URL, keep it all on one line
309
+ s += args[0];
310
+ } else {
311
+ s += "\n";
312
+ s += " " + args.join(",\n ");
313
+ s += "\n";
314
+ }
315
+ return s + ")\n";
316
+ }
317
+
318
+ return `request = %HTTPoison.Request{
319
+ method: :${method.toLowerCase().toString()},
320
+ url: ${repr(request.urls[0].urlWithoutQueryList)},
321
+ body: ${body},
322
+ headers: ${headers},
323
+ options: ${optionsWithoutParams},
324
+ params: ${params}
325
+ }
326
+
327
+ response = HTTPoison.request(request)
328
+ `;
329
+ }
330
+
331
+ export function _toElixir(
332
+ requests: Request[],
333
+ warnings: Warnings = [],
334
+ ): string {
335
+ return requests.map((r) => requestToElixir(r, warnings)).join("\n");
336
+ }
337
+
338
+ export function toElixirWarn(
339
+ curlCommand: string | string[],
340
+ warnings: Warnings = [],
341
+ ): [string, Warnings] {
342
+ const requests = parse(curlCommand, supportedArgs, warnings);
343
+ const elixir = _toElixir(requests, warnings);
344
+ return [elixir, warnings];
345
+ }
346
+
347
+ export function toElixir(curlCommand: string | string[]): string {
348
+ return toElixirWarn(curlCommand)[0];
349
+ }
@@ -0,0 +1,269 @@
1
+ import { CCError } from "../utils.js";
2
+ import { Word } from "../shell/Word.js";
3
+ import { parse, getFirst, COMMON_SUPPORTED_ARGS } from "../parse.js";
4
+ import type { Request, Warnings } from "../parse.js";
5
+
6
+ import { reprStr as pyreprStr } from "./python/python.js";
7
+
8
+ export const supportedArgs = new Set([
9
+ ...COMMON_SUPPORTED_ARGS,
10
+ "insecure",
11
+ "no-insecure",
12
+ "compressed",
13
+ "no-compressed",
14
+ "max-time",
15
+ "form",
16
+ "form-string",
17
+ ]);
18
+
19
+ const IF_ERR = "\tif err != nil {\n" + "\t\tlog.Fatal(err)\n" + "\t}\n";
20
+
21
+ // https://go.dev/ref/spec#String_literals
22
+ function reprMaybeBacktick(s: Word, vars: Vars, imports: Set<string>): string {
23
+ return s.isString() && s.includes('"')
24
+ ? reprBacktick(s, vars, imports)
25
+ : repr(s, vars, imports);
26
+ }
27
+ function reprBacktick(s: Word, vars: Vars, imports: Set<string>): string {
28
+ return s.isString() && !s.includes("`") && !s.includes("\r")
29
+ ? "`" + s.toString() + "`"
30
+ : repr(s, vars, imports);
31
+ }
32
+ function reprStr(s: string): string {
33
+ return pyreprStr(s, '"');
34
+ }
35
+ type Vars = { [key: string]: string };
36
+ function repr(w: Word, vars: Vars, imports: Set<string>): string {
37
+ const args: string[] = [];
38
+ for (const t of w.tokens) {
39
+ if (typeof t === "string") {
40
+ args.push(reprStr(t));
41
+ } else if (t.type === "variable") {
42
+ args.push("os.Getenv(" + reprStr(t.value) + ")");
43
+ imports.add("os");
44
+ } else {
45
+ // TODO: Command takes a list of arguments .Command("ls", "-l", "-a")
46
+ // TODO: if there's only one command, it would be nice to name the variable "cmd"
47
+ const execCall = "exec.Command(" + reprStr(t.value) + ").Output()";
48
+ let i = 1;
49
+ let varName = "cmd" + i;
50
+ // We need to check because we often try to represent the same
51
+ // token twice and discard one of the attempts.
52
+ // This is linear time but hopefully there's not that many subcommands.
53
+ while (varName in vars && vars[varName] !== execCall) {
54
+ i++;
55
+ varName = "cmd" + i;
56
+ if (i > Number.MAX_SAFE_INTEGER) {
57
+ throw new CCError("lol");
58
+ }
59
+ }
60
+ vars[varName] = execCall;
61
+ args.push(varName);
62
+ imports.add("os/exec");
63
+ }
64
+ }
65
+ return args.join(" + ");
66
+ }
67
+
68
+ function timeoutAtoi(w: Word, vars: Vars, imports: Set<string>): string {
69
+ if (w.isString()) {
70
+ const asStr = w.toString();
71
+ // TODO: check using curl's syntax and convert to Go's float syntax
72
+ if (/^\d+\.?\d*$/.test(asStr)) {
73
+ return asStr;
74
+ }
75
+ }
76
+ vars["timeout"] = "strconv.Atoi(" + repr(w, vars, imports) + ")";
77
+ imports.add("strconv");
78
+ return "timeout";
79
+ }
80
+
81
+ export function _toGo(requests: Request[], warnings: Warnings = []): string {
82
+ const request = getFirst(requests, warnings);
83
+
84
+ const imports = new Set<string>(["fmt", "io", "log", "net/http"]);
85
+ const vars: Vars = {};
86
+
87
+ let goCode = "";
88
+ if (request.multipartUploads) {
89
+ goCode += "\tform := new(bytes.Buffer)\n";
90
+ goCode += "\twriter := multipart.NewWriter(form)\n";
91
+ imports.add("bytes");
92
+ imports.add("mime/multipart");
93
+
94
+ let firstFile = true;
95
+ let firstField = true;
96
+ for (const m of request.multipartUploads) {
97
+ if ("contentFile" in m) {
98
+ const op = firstFile ? ":=" : "=";
99
+ firstFile = false;
100
+ // TODO: Go sends name=<filename> but curl always sends name="data"
101
+ goCode += `\tfw, err ${op} writer.CreateFormFile(${repr(
102
+ m.name,
103
+ vars,
104
+ imports,
105
+ )}, filepath.Base(${repr(
106
+ m.filename ?? m.contentFile,
107
+ vars,
108
+ imports,
109
+ )}))\n`;
110
+ goCode += IF_ERR;
111
+ imports.add("path/filepath");
112
+
113
+ goCode += `\tfd, err ${op} os.Open(${repr(
114
+ m.contentFile,
115
+ vars,
116
+ imports,
117
+ )})\n`;
118
+ goCode += IF_ERR;
119
+ imports.add("os");
120
+ goCode += "\tdefer fd.Close()\n";
121
+ goCode += "\t_, err = io.Copy(fw, fd)\n";
122
+ goCode += IF_ERR;
123
+ } else {
124
+ const op = firstField ? ":=" : "=";
125
+ firstField = false;
126
+ goCode += `\tformField, err ${op} writer.CreateFormField(${repr(
127
+ m.name,
128
+ vars,
129
+ imports,
130
+ )})\n`;
131
+ goCode += IF_ERR;
132
+ goCode += `\t_, err = formField.Write([]byte(${reprMaybeBacktick(
133
+ m.content,
134
+ vars,
135
+ imports,
136
+ )}))\n`;
137
+ }
138
+ goCode += "\n";
139
+ }
140
+ goCode += "\twriter.Close()\n";
141
+ goCode += "\n";
142
+
143
+ request.headers.delete("content-type");
144
+ }
145
+
146
+ if (request.insecure || request.compressed === false) {
147
+ goCode += "\ttr := &http.Transport{\n";
148
+ if (request.insecure) {
149
+ goCode += "\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n";
150
+ imports.add("crypto/tls");
151
+ }
152
+ if (request.compressed === false) {
153
+ goCode += "\t\tDisableCompression: true,\n";
154
+ }
155
+ goCode += "\t}\n";
156
+ }
157
+
158
+ goCode += "\tclient := &http.Client{";
159
+ if (request.timeout) {
160
+ goCode += "\n";
161
+ if (request.insecure || request.compressed === false) {
162
+ goCode += "\t\tTransport: tr,\n";
163
+ }
164
+ goCode +=
165
+ "\t\tTimeout: " +
166
+ timeoutAtoi(request.timeout, vars, imports) +
167
+ " * time.Second,\n";
168
+ goCode += "\t";
169
+ imports.add("time");
170
+ } else if (request.insecure || request.compressed === false) {
171
+ goCode += "Transport: tr";
172
+ }
173
+ goCode += "}\n";
174
+
175
+ if (request.data && !request.multipartUploads) {
176
+ goCode +=
177
+ "\tvar data = strings.NewReader(" +
178
+ reprBacktick(request.data, vars, imports) +
179
+ ")\n";
180
+ imports.add("strings");
181
+ }
182
+
183
+ goCode +=
184
+ "\treq, err := http.NewRequest(" +
185
+ repr(request.urls[0].method, vars, imports) +
186
+ ", " +
187
+ repr(request.urls[0].url, vars, imports);
188
+ goCode +=
189
+ ", " +
190
+ (request.multipartUploads ? "form" : request.data ? "data" : "nil") +
191
+ ")\n";
192
+ goCode += IF_ERR;
193
+
194
+ if (request.headers.length) {
195
+ for (const [headerName, headerValue] of request.headers) {
196
+ let start = "\t";
197
+ if (
198
+ headerName.toLowerCase().toString() === "accept-encoding" &&
199
+ // By default Go will automatically decompress gzip,
200
+ // unless you set DisableCompression to true on the Transport
201
+ // or pass a custom Accept-Encoding header.
202
+ // By default curl won't automatically decompress gzip unless
203
+ // you pass --compressed, but we comment out the header in that
204
+ // case (request.compressed = undefined) too.
205
+ request.compressed !== false
206
+ ) {
207
+ start += "// ";
208
+ }
209
+ goCode +=
210
+ start +
211
+ "req.Header.Set(" +
212
+ repr(headerName, vars, imports) +
213
+ ", " +
214
+ reprMaybeBacktick(headerValue || new Word(), vars, imports) +
215
+ ")\n";
216
+ }
217
+ }
218
+ if (request.multipartUploads) {
219
+ goCode +=
220
+ '\treq.Header.Set("Content-Type", writer.FormDataContentType())\n';
221
+ }
222
+
223
+ if (request.urls[0].auth && request.authType === "basic") {
224
+ const [user, password] = request.urls[0].auth;
225
+ goCode +=
226
+ "\treq.SetBasicAuth(" +
227
+ repr(user, vars, imports) +
228
+ ", " +
229
+ repr(password, vars, imports) +
230
+ ")\n";
231
+ }
232
+
233
+ goCode += "\tresp, err := client.Do(req)\n";
234
+ goCode += IF_ERR;
235
+ goCode += "\tdefer resp.Body.Close()\n";
236
+ goCode += "\tbodyText, err := io.ReadAll(resp.Body)\n";
237
+ goCode += IF_ERR;
238
+ goCode += '\tfmt.Printf("%s\\n", bodyText)\n';
239
+ goCode += "}";
240
+
241
+ let preamble = "package main\n\n";
242
+ preamble += "import (\n";
243
+ for (const imp of Array.from(imports).sort()) {
244
+ preamble += '\t"' + imp + '"\n';
245
+ }
246
+ preamble += ")\n\n";
247
+ preamble += "func main() {\n";
248
+ // TODO: sorts wrong when >9 commands
249
+ for (const [name, expr] of Array.from(Object.entries(vars)).sort()) {
250
+ preamble += "\t" + name + ", err := " + expr + "\n";
251
+ preamble += IF_ERR;
252
+ }
253
+ if (Object.values(vars).length) {
254
+ preamble += "\n";
255
+ }
256
+
257
+ return preamble + goCode + "\n";
258
+ }
259
+ export function toGoWarn(
260
+ curlCommand: string | string[],
261
+ warnings: Warnings = [],
262
+ ): [string, Warnings] {
263
+ const requests = parse(curlCommand, supportedArgs, warnings);
264
+ const go = _toGo(requests, warnings);
265
+ return [go, warnings];
266
+ }
267
+ export function toGo(curlCommand: string | string[]): string {
268
+ return toGoWarn(curlCommand)[0];
269
+ }