Skip to content
Merged
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
27 changes: 16 additions & 11 deletions src/fixtures/runCustomFixtures.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { readFile } from 'fs/promises';
import { writeFileSync } from 'fs';
import { readFile, writeFile } from 'fs/promises';
import path from 'path';

import { HTTPSnippet, Request } from '../httpsnippet';
Expand All @@ -21,17 +22,21 @@ export interface CustomFixture {
export const runCustomFixtures = ({ targetId, clientId, tests }: CustomFixture) => {
describe(`custom fixtures for ${targetId}:${clientId}`, () => {
tests.forEach(({ it: title, expected: fixtureFile, options, input: request }) => {
const result = new HTTPSnippet(request).convert(targetId, clientId, options);
const filePath = path.join(
__dirname,
'..',
'targets',
targetId,
clientId,
'fixtures',
fixtureFile,
);
if (process.env.OVERWRITE_EVERYTHING) {
writeFileSync(filePath, String(result));
}

it(title, async () => {
const result = new HTTPSnippet(request).convert(targetId, clientId, options);
const filePath = path.join(
__dirname,
'..',
'targets',
targetId,
clientId,
'fixtures',
fixtureFile,
);
const buffer = await readFile(filePath);
const fixture = String(buffer);

Expand Down
16 changes: 16 additions & 0 deletions src/targets/shell/curl/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import applicationFormEncoded from '../../../fixtures/requests/application-form-encoded.json';
import full from '../../../fixtures/requests/full.json';
import nested from '../../../fixtures/requests/nested.json';
import { runCustomFixtures } from '../../../fixtures/runCustomFixtures';
Expand Down Expand Up @@ -71,5 +72,20 @@ runCustomFixtures({
},
expected: 'custom-indentation.sh',
},
{
it: 'should url encode the params key',
input: {
...applicationFormEncoded,
postData: {
mimeType: 'application/x-www-form-urlencoded',
params: [
{ name: 'user name', value: 'John Doe' },
{ name: '$filter', value: 'by id' },
],
},
} as Request,
options: {},
expected: 'urlencode.sh',
},
],
});
84 changes: 49 additions & 35 deletions src/targets/shell/curl/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/**
* @description
*
* HTTP code snippet generator for the Shell using cURL.
*
* @author
Expand All @@ -20,39 +21,59 @@ export interface CurlOptions {
indent?: string | false;
}

/**
* This is a const record with keys that correspond to the long names and values that correspond to the short names for cURL arguments.
*/
const params = {
globoff: 'g',
request: 'X',
'url ': '',
'http1.0': '0',
header: 'H',
cookie: 'b',
form: 'F',
data: 'd',
} as const;

const getArg = (short: boolean) => (longName: keyof typeof params) => {
if (short) {
const shortName = params[longName];
if (!shortName) {
return '';
}
return `-${shortName}`;
}
return `--${longName}`;
};

export const curl: Client<CurlOptions> = {
info: {
key: 'curl',
title: 'cURL',
link: 'http://curl.haxx.se/',
description: 'cURL is a command line tool and library for transferring data with URL syntax',
},
convert: ({ fullUrl, method, httpVersion, headersObj, allHeaders, postData }, options) => {
const opts = {
indent: ' ',
short: false,
binary: false,
globOff: false,
...options,
};
convert: ({ fullUrl, method, httpVersion, headersObj, allHeaders, postData }, options = {}) => {
const { indent = ' ', short = false, binary = false, globOff = false } = options;

const { push, join } = new CodeBuilder({
...(typeof opts.indent === 'string' ? { indent: opts.indent } : {}),
join: opts.indent !== false ? ` \\\n${opts.indent}` : ' ',
...(typeof indent === 'string' ? { indent: indent } : {}),
join: indent !== false ? ` \\\n${indent}` : ' ',
});

const globOption = opts.short ? '-g' : '--globoff';
const requestOption = opts.short ? '-X' : '--request';
const arg = getArg(short);

let formattedUrl = quote(fullUrl);

push(`curl ${requestOption} ${method}`);
if (opts.globOff) {
push(`curl ${arg('request')} ${method}`);
if (globOff) {
formattedUrl = unescape(formattedUrl);
push(globOption);
push(arg('globoff'));
}
push(`${opts.short ? '' : '--url '}${formattedUrl}`);
push(`${arg('url ')}${formattedUrl}`);

if (httpVersion === 'HTTP/1.0') {
push(opts.short ? '-0' : '--http1.0');
push(arg('http1.0'));
}

// if multipart form data, we want to remove the boundary
Expand All @@ -78,11 +99,11 @@ export const curl: Client<CurlOptions> = {
.sort()
.forEach(key => {
const header = `${key}: ${headersObj[key]}`;
push(`${opts.short ? '-H' : '--header'} ${quote(header)}`);
push(`${arg('header')} ${quote(header)}`);
});

if (allHeaders.cookie) {
push(`${opts.short ? '-b' : '--cookie'} ${quote(allHeaders.cookie as string)}`);
push(`${arg('cookie')} ${quote(allHeaders.cookie as string)}`);
}

// construct post params
Expand All @@ -96,36 +117,29 @@ export const curl: Client<CurlOptions> = {
post = `${param.name}=${param.value}`;
}

push(`${opts.short ? '-F' : '--form'} ${quote(post)}`);
push(`${arg('form')} ${quote(post)}`);
});
break;

case 'application/x-www-form-urlencoded':
if (postData.params) {
postData.params.forEach(param => {
push(
`${opts.binary ? '--data-binary' : opts.short ? '-d' : '--data'} ${quote(
`${param.name}=${param.value}`,
)}`,
);
const unencoded = param.name;
const encoded = encodeURIComponent(param.name);
const needsEncoding = encoded !== unencoded;
const name = needsEncoding ? encoded : unencoded;
const flag = binary ? '--data-binary' : `--data${needsEncoding ? '-urlencode' : ''}`;
push(`${flag} ${quote(`${name}=${param.value}`)}`);
});
} else {
push(
`${opts.binary ? '--data-binary' : opts.short ? '-d' : '--data'} ${quote(
postData.text,
)}`,
);
push(`${binary ? '--data-binary' : arg('data')} ${quote(postData.text)}`);
}
break;

default:
// raw request body
if (postData.text) {
push(
`${opts.binary ? '--data-binary' : opts.short ? '-d' : '--data'} ${quote(
postData.text,
)}`,
);
push(`${binary ? '--data-binary' : arg('data')} ${quote(postData.text)}`);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/targets/shell/curl/fixtures/short-options.sh
Original file line number Diff line number Diff line change
@@ -1 +1 @@
curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' -d foo=bar
curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' --data foo=bar
5 changes: 5 additions & 0 deletions src/targets/shell/curl/fixtures/urlencode.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
curl --request POST \
--url http://mockbin.com/har \
--header 'content-type: application/x-www-form-urlencoded' \
--data-urlencode 'user%20name=John Doe' \
--data-urlencode '%24filter=by id'