Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d854732143 | |||
|
9b021296eb
|
|||
|
d581afa793
|
|||
| 95ca655eb0 | |||
|
25887a47d3
|
|||
|
1f7816c917
|
|||
|
fb7b4baa32
|
|||
|
2c4eedbf8b
|
|||
| c790adf611 | |||
|
c6094566b4
|
|||
| 0ac5e64c17 | |||
|
40cc852328
|
|||
|
c4961b1238
|
|||
|
c630af8795
|
|||
|
9947987c20
|
|||
| c5f928dc47 | |||
|
2081aa935a
|
|||
|
1b3dd8b677
|
|||
|
9613697ada
|
|||
| 9ed0ddf79b | |||
|
b9c804b0f6
|
|||
|
882fbe4713
|
|||
|
aa583e7d43
|
57
README.md
57
README.md
@@ -15,6 +15,8 @@ These formats are supported for now: `http`, `curl`, `wget`.
|
||||
## Supported features
|
||||
|
||||
* [collection schema **v2.1**](https://schema.postman.com/json/collection/v2.1.0/collection.json);
|
||||
* `Bearer` auth;
|
||||
* replace vars in requests by stored in collection and environment file;
|
||||
* export one or several collections (or even whole directories) into one or all of formats supported at the same time;
|
||||
* all headers (including disabled for `http`-format);
|
||||
* `json` body (forces header `Content-Type` to `application/json`);
|
||||
@@ -22,13 +24,10 @@ These formats are supported for now: `http`, `curl`, `wget`.
|
||||
|
||||
## Planned features
|
||||
|
||||
- support as many as possible/necessary of authentication kinds (_currently no ones_);
|
||||
- support as many as possible/necessary of body formats (_currently json and formdata_);
|
||||
- support as many as possible/necessary of authentication kinds (_currently only `Bearer` supported_);
|
||||
- support as many as possible/necessary of body formats (_currently only `json` and `formdata`_);
|
||||
- documentation generation support (markdown) with responce examples (if present);
|
||||
- maybe some another convert formats (like httpie or something...);
|
||||
- replace `{{vars}}` from folder;
|
||||
- replace `{{vars}}` from environment;
|
||||
- performance measurement;
|
||||
- better logging;
|
||||
- tests, phpcs, psalm, etc.;
|
||||
- web version.
|
||||
@@ -53,39 +52,45 @@ export PATH="$PATH:~/.config/composer/vendor/bin"
|
||||
$ pm-convert --help
|
||||
Postman collection converter
|
||||
Usage:
|
||||
./pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
php pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
composer pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
./vendor/bin/pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
./pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
php pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
composer pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
./vendor/bin/pm-convert -f|-d PATH -o OUTPUT_PATH [ARGUMENTS] [FORMATS]
|
||||
|
||||
Possible ARGUMENTS:
|
||||
-f, --file - a PATH to single collection located in PATH to convert from
|
||||
-d, --dir - a directory with collections located in COLLECTION_FILEPATH to convert from
|
||||
-o, --output - a directory OUTPUT_PATH to put results in
|
||||
-p, --preserve - do not delete OUTPUT_PATH (if exists)
|
||||
-h, --help - show this help message and exit
|
||||
-v, --version - show version info and exit
|
||||
-f, --file - a PATH to single collection located in PATH to convert from
|
||||
-d, --dir - a directory with collections located in COLLECTION_FILEPATH to convert from
|
||||
-o, --output - a directory OUTPUT_PATH to put results in
|
||||
-e, --env - use environment file with variable values to replace in request
|
||||
-p, --preserve - do not delete OUTPUT_PATH (if exists)
|
||||
-h, --help - show this help message and exit
|
||||
-v, --version - show version info and exit
|
||||
|
||||
If both -c and -d are specified then only unique set of files will be converted.
|
||||
If no ARGUMENTS passed then --help implied.
|
||||
If both -f and -d are specified then only unique set of files will be converted.
|
||||
-f or -d are required to be specified at least once, but each may be specified multiple times.
|
||||
PATH must be a valid path to readable json-file or directory.
|
||||
OUTPUT_PATH must be a valid path to writeable directory.
|
||||
If -o is specified several times then only last one will be applied.
|
||||
If -o is specified several times then only last one will be used.
|
||||
If -e is specified several times then only last one will be used.
|
||||
If -e is not specified then only collection vars will be replaced (if any).
|
||||
|
||||
Possible FORMATS:
|
||||
--http - generate raw *.http files (default)
|
||||
--curl - generate shell scripts with curl command
|
||||
--wget - generate shell scripts with wget command
|
||||
--http - generate raw *.http files (default)
|
||||
--curl - generate shell scripts with curl command
|
||||
--wget - generate shell scripts with wget command
|
||||
If no FORMATS specified then --http implied.
|
||||
Any of FORMATS can be specified at the same time.
|
||||
|
||||
Example:
|
||||
./pm-convert \
|
||||
-f ~/dir1/first.postman_collection.json \
|
||||
--directory ~/team \
|
||||
--file ~/dir2/second.postman_collection.json \
|
||||
-d ~/personal \
|
||||
-o ~/postman_export
|
||||
./pm-convert \
|
||||
-f ~/dir1/first.postman_collection.json \
|
||||
--directory ~/team \
|
||||
--file ~/dir2/second.postman_collection.json \
|
||||
--env ~/localhost.postman_environment.json \
|
||||
-d ~/personal \
|
||||
-o ~/postman_export
|
||||
|
||||
```
|
||||
### Notice
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
declare(strict_types = 1);
|
||||
declare(strict_types=1);
|
||||
|
||||
use PmConverter\Processor;
|
||||
|
||||
@@ -20,8 +20,13 @@ foreach ($paths as $path) {
|
||||
|
||||
is_null($file) && throw new RuntimeException('Unable to locate autoload.php file.');
|
||||
|
||||
$processor = new Processor($argv);
|
||||
try {
|
||||
(new Processor($argv))->start();
|
||||
$processor->convert();
|
||||
} catch (InvalidArgumentException $e) {
|
||||
fwrite(STDERR, sprintf('ERROR: %s%s', $e->getMessage(), PHP_EOL));
|
||||
print(implode(PHP_EOL, $processor->usage()));
|
||||
die(1);
|
||||
} catch (Exception $e) {
|
||||
fwrite(STDERR, sprintf('ERROR: %s%s', $e->getMessage(), PHP_EOL));
|
||||
die(1);
|
||||
|
||||
65
src/Environment.php
Normal file
65
src/Environment.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PmConverter;
|
||||
|
||||
class Environment implements \ArrayAccess
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected array $vars = [];
|
||||
|
||||
/**
|
||||
* @param object $env
|
||||
*/
|
||||
public function __construct(protected object $env)
|
||||
{
|
||||
foreach ($env->values as $var) {
|
||||
$this->vars["{{{$var->key}}}"] = $var->value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if there are some vars or not
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasVars(): bool
|
||||
{
|
||||
return !empty($this->vars);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function offsetExists(mixed $offset): bool
|
||||
{
|
||||
return array_key_exists($offset, $this->vars);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function offsetGet(mixed $offset): mixed
|
||||
{
|
||||
return $this->vars[$offset];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function offsetSet(mixed $offset, mixed $value): void
|
||||
{
|
||||
$this->vars[$offset] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function offsetUnset(mixed $offset): void
|
||||
{
|
||||
unset($this->vars[$offset]);
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,16 @@ declare(strict_types=1);
|
||||
namespace PmConverter\Exporters\Abstract;
|
||||
|
||||
use Exception;
|
||||
use PmConverter\Environment;
|
||||
use PmConverter\Exporters\{
|
||||
ConverterContract,
|
||||
RequestContract};
|
||||
use PmConverter\FileSystem;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
abstract class AbstractConverter
|
||||
abstract class AbstractConverter implements ConverterContract
|
||||
{
|
||||
/**
|
||||
* @var object|null
|
||||
@@ -25,6 +27,30 @@ abstract class AbstractConverter
|
||||
protected string $outputPath;
|
||||
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
protected array $vars = [];
|
||||
|
||||
/**
|
||||
* @var Environment
|
||||
*/
|
||||
protected Environment $env;
|
||||
|
||||
/**
|
||||
* Sets an environment with vars
|
||||
*
|
||||
* @param Environment $env
|
||||
* @return $this
|
||||
*/
|
||||
public function withEnv(Environment $env): static
|
||||
{
|
||||
$this->env = $env;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts collection requests
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function convert(object $collection, string $outputPath): void
|
||||
@@ -32,12 +58,30 @@ abstract class AbstractConverter
|
||||
$outputPath = sprintf('%s%s%s', $outputPath, DIRECTORY_SEPARATOR, static::OUTPUT_DIR);
|
||||
$this->outputPath = FileSystem::makeDir($outputPath);
|
||||
$this->collection = $collection;
|
||||
$this->setVariables();
|
||||
foreach ($collection->item as $item) {
|
||||
$this->convertItem($item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares collection variables
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
protected function setVariables(): static
|
||||
{
|
||||
if (isset($this->collection?->variable)) {
|
||||
foreach ($this->collection->variable as $var) {
|
||||
$this->vars["{{{$var->key}}}"] = $var->value;
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns output path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getOutputPath(): string
|
||||
@@ -46,6 +90,8 @@ abstract class AbstractConverter
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether item contains another items or not
|
||||
*
|
||||
* @param object $item
|
||||
* @return bool
|
||||
*/
|
||||
@@ -55,6 +101,8 @@ abstract class AbstractConverter
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an item to request object and writes it into file
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function convertItem(mixed $item): void
|
||||
@@ -77,18 +125,23 @@ abstract class AbstractConverter
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialiazes request object to be written in file
|
||||
*
|
||||
* @param object $item
|
||||
* @return RequestContract
|
||||
*/
|
||||
protected function initRequest(object $item): RequestContract
|
||||
{
|
||||
$request_class = static::REQUEST;
|
||||
$result = new $request_class();
|
||||
$request_class = static::REQUEST_CLASS;
|
||||
|
||||
/** @var RequestContract $result */
|
||||
$result = new $request_class($this->vars);
|
||||
$result->setName($item->name);
|
||||
$result->setDescription($item->request?->description ?? null);
|
||||
$result->setVerb($item->request->method);
|
||||
$result->setUrl($item->request->url->raw);
|
||||
$result->setHeaders($item->request->header);
|
||||
$result->setAuth($item->request?->auth ?? $this->collection?->auth ?? null);
|
||||
if ($item->request->method !== 'GET' && !empty($item->request->body)) {
|
||||
$result->setBody($item->request->body);
|
||||
}
|
||||
@@ -96,6 +149,8 @@ abstract class AbstractConverter
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes converted request object to file
|
||||
*
|
||||
* @param RequestContract $request
|
||||
* @param string|null $subpath
|
||||
* @return bool
|
||||
@@ -106,6 +161,33 @@ abstract class AbstractConverter
|
||||
$filedir = sprintf('%s%s%s', $this->outputPath, DIRECTORY_SEPARATOR, $subpath);
|
||||
$filedir = FileSystem::makeDir($filedir);
|
||||
$filepath = sprintf('%s%s%s.%s', $filedir, DIRECTORY_SEPARATOR, $request->getName(), static::FILE_EXT);
|
||||
return file_put_contents($filepath, (string)$request) > 0;
|
||||
$content = $this->interpolate((string)$request);
|
||||
return file_put_contents($filepath, $content) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces variables in request with values from collection or environment
|
||||
*
|
||||
* @param string $content
|
||||
* @return string
|
||||
*/
|
||||
protected function interpolate(string $content): string
|
||||
{
|
||||
if (empty($this->vars) && !empty($this->env) && $this->env->hasVars()) {
|
||||
return $content;
|
||||
}
|
||||
$matches = [];
|
||||
if (preg_match_all('/\{\{[a-zA-Z][a-zA-Z0-9]+}}/', $content, $matches, PREG_PATTERN_ORDER) > 0) {
|
||||
foreach ($matches[0] as $key => $var) {
|
||||
if (str_contains($content, $var)) {
|
||||
$content = str_replace($var, $this->vars[$var] ?? $this->env[$var] ?? $var, $content);
|
||||
unset($matches[0][$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (!empty($matches[0])) {
|
||||
// fwrite(STDERR, sprintf(' No values found: %s%s', implode(', ', $matches[0]), PHP_EOL));
|
||||
// }
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,14 +8,14 @@ use PmConverter\Exporters\Http\HttpRequest;
|
||||
use PmConverter\Exporters\RequestContract;
|
||||
|
||||
/**
|
||||
*
|
||||
* Class to determine file content with any request format
|
||||
*/
|
||||
abstract class AbstractRequest implements RequestContract
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected string $http = 'HTTP/1.1'; //TODO verb
|
||||
protected string $http = 'HTTP/1.1'; //TODO proto
|
||||
|
||||
/**
|
||||
* @var string
|
||||
@@ -53,6 +53,8 @@ abstract class AbstractRequest implements RequestContract
|
||||
protected string $url;
|
||||
|
||||
/**
|
||||
* Sets name from collection item to request object
|
||||
*
|
||||
* @param string $name
|
||||
* @return HttpRequest
|
||||
*/
|
||||
@@ -63,6 +65,8 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns name of request
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
@@ -71,6 +75,8 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets description from collection item to request object
|
||||
*
|
||||
* @param string|null $description
|
||||
* @return HttpRequest
|
||||
*/
|
||||
@@ -81,6 +87,8 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets HTTP verb from collection item to request object
|
||||
*
|
||||
* @param string $verb
|
||||
* @return HttpRequest
|
||||
*/
|
||||
@@ -91,6 +99,8 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets URL from collection item to request object
|
||||
*
|
||||
* @param string $url
|
||||
* @return HttpRequest
|
||||
*/
|
||||
@@ -101,6 +111,8 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets headers from collection item to request object
|
||||
*
|
||||
* @param object[]|null $headers
|
||||
* @return $this
|
||||
*/
|
||||
@@ -116,6 +128,32 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets authorization headers
|
||||
*
|
||||
* @param object|null $auth
|
||||
* @return $this
|
||||
*/
|
||||
public function setAuth(?object $auth): static
|
||||
{
|
||||
if (!empty($auth)) {
|
||||
switch ($auth->type) {
|
||||
case 'bearer':
|
||||
$this->headers['Authorization'] = [
|
||||
'value' => 'Bearer ' . $auth->{$auth->type}[0]->value,
|
||||
'disabled' => false,
|
||||
];
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets body mode from collection item to request object
|
||||
*
|
||||
* @param string $bodymode
|
||||
* @return HttpRequest
|
||||
*/
|
||||
@@ -126,8 +164,10 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $body
|
||||
* @return HttpRequest
|
||||
* Sets body from collection item to request object
|
||||
*
|
||||
* @param object $body
|
||||
* @return $this
|
||||
*/
|
||||
public function setBody(object $body): static
|
||||
{
|
||||
@@ -153,11 +193,29 @@ abstract class AbstractRequest implements RequestContract
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* Returns array of description lines
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract protected function prepareBody(): ?string;
|
||||
abstract protected function prepareDescription(): array;
|
||||
|
||||
/**
|
||||
* Returns array of headers
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract protected function prepareHeaders(): array;
|
||||
|
||||
/**
|
||||
* Returns array of request body lines
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract protected function prepareBody(): array;
|
||||
|
||||
/**
|
||||
* Converts request object to string to be written in result file
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function __toString(): string;
|
||||
|
||||
@@ -11,7 +11,8 @@ use PmConverter\Exporters\{
|
||||
class CurlConverter extends AbstractConverter implements ConverterContract
|
||||
{
|
||||
protected const FILE_EXT = 'sh';
|
||||
|
||||
protected const OUTPUT_DIR = 'curl';
|
||||
|
||||
protected const REQUEST = CurlRequest::class;
|
||||
protected const REQUEST_CLASS = CurlRequest::class;
|
||||
}
|
||||
|
||||
@@ -7,59 +7,77 @@ namespace PmConverter\Exporters\Curl;
|
||||
use PmConverter\Exporters\Abstract\AbstractRequest;
|
||||
|
||||
/**
|
||||
*
|
||||
* Class to determine file content with curl request format
|
||||
*/
|
||||
class CurlRequest extends AbstractRequest
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function prepareBody(): ?string
|
||||
protected function prepareDescription(): array
|
||||
{
|
||||
switch ($this->bodymode) {
|
||||
case 'formdata':
|
||||
$body = [];
|
||||
foreach ($this->body as $data) {
|
||||
$body[] = sprintf(
|
||||
"%s\t--form '%s=%s' \ ",
|
||||
isset($data->disabled) ? '# ' : '',
|
||||
$data->key,
|
||||
$data->type === 'file' ? "@$data->src" : $data->value
|
||||
);
|
||||
}
|
||||
return implode(PHP_EOL, $body);
|
||||
default:
|
||||
return $this->body;
|
||||
}
|
||||
return empty($this->description)
|
||||
? []
|
||||
: ['# ' . str_replace("\n", "\n# ", $this->description), ''];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __toString(): string
|
||||
protected function prepareHeaders(): array
|
||||
{
|
||||
$output[] = '#!/bin/sh';
|
||||
if ($this->description) {
|
||||
$output[] = '# ' . str_replace("\n", "\n# ", $this->description);
|
||||
$output[] = '';
|
||||
}
|
||||
$output[] = "curl \ ";
|
||||
$output[] = "\t--http1.1 \ "; //TODO verb
|
||||
$output[] = "\t--request $this->verb \ ";
|
||||
$output[] = "\t--location $this->url \ ";
|
||||
$output = [];
|
||||
foreach ($this->headers as $header_key => $header) {
|
||||
if ($header['disabled']) {
|
||||
continue;
|
||||
}
|
||||
$output[] = sprintf("\t--header '%s=%s' \ ", $header_key, $header['value']);
|
||||
}
|
||||
if (!is_null($body = $this->prepareBody())) {
|
||||
$output[] = match ($this->bodymode) {
|
||||
'formdata' => $body,
|
||||
default => "\t--data '$body'",
|
||||
};
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function prepareBody(): array
|
||||
{
|
||||
$output = [];
|
||||
switch ($this->bodymode) {
|
||||
case 'formdata':
|
||||
foreach ($this->body as $data) {
|
||||
$output[] = sprintf(
|
||||
"%s\t--form '%s=%s' \ ",
|
||||
isset($data->disabled) ? '# ' : '',
|
||||
$data->key,
|
||||
$data->type === 'file' ? "@$data->src" : $data->value
|
||||
);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
$output = ["\t--data '$this->body'"];
|
||||
break;
|
||||
}
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
$output = array_merge(
|
||||
['#!/bin/sh'],
|
||||
$this->prepareDescription(),
|
||||
[
|
||||
"curl \ ",
|
||||
"\t--http1.1 \ ", //TODO proto
|
||||
"\t--request $this->verb \ ",
|
||||
"\t--location $this->url \ ",
|
||||
],
|
||||
$this->prepareHeaders(),
|
||||
$this->prepareBody()
|
||||
);
|
||||
$output[] = rtrim(array_pop($output), '\ ');
|
||||
return implode(PHP_EOL, $output);
|
||||
return implode(PHP_EOL, array_merge($output, ['']));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ use PmConverter\Exporters\{
|
||||
class HttpConverter extends AbstractConverter implements ConverterContract
|
||||
{
|
||||
protected const FILE_EXT = 'http';
|
||||
|
||||
protected const OUTPUT_DIR = 'http';
|
||||
|
||||
protected const REQUEST = HttpRequest::class;
|
||||
protected const REQUEST_CLASS = HttpRequest::class;
|
||||
}
|
||||
|
||||
@@ -7,47 +7,64 @@ namespace PmConverter\Exporters\Http;
|
||||
use PmConverter\Exporters\Abstract\AbstractRequest;
|
||||
|
||||
/**
|
||||
*
|
||||
* Class to determine file content with http request format
|
||||
*/
|
||||
class HttpRequest extends AbstractRequest
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function prepareBody(): ?string
|
||||
protected function prepareDescription(): array
|
||||
{
|
||||
switch ($this->bodymode) {
|
||||
case 'formdata':
|
||||
$body = [];
|
||||
foreach ($this->body as $data) {
|
||||
$body[] = sprintf(
|
||||
'%s%s=%s',
|
||||
empty($data->disabled) ? '' : '# ',
|
||||
$data->key,
|
||||
$data->type === 'file' ? "$data->src" : $data->value
|
||||
);
|
||||
}
|
||||
return implode(PHP_EOL, $body);
|
||||
default:
|
||||
return $this->body;
|
||||
}
|
||||
return empty($this->description)
|
||||
? []
|
||||
: ['# ' . str_replace("\n", "\n# ", $this->description), ''];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __toString(): string
|
||||
protected function prepareHeaders(): array
|
||||
{
|
||||
if ($this->description) {
|
||||
$output[] = '# ' . str_replace("\n", "\n# ", $this->description);
|
||||
$output[] = '';
|
||||
}
|
||||
$output[] = "$this->verb $this->url $this->http";
|
||||
foreach ($this->headers as $header_key => $header) {
|
||||
$output[] = sprintf('%s%s: %s', $header['disabled'] ? '# ' : '', $header_key, $header['value']);
|
||||
}
|
||||
$output[] = '';
|
||||
$output[] = (string)$this->prepareBody();
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function prepareBody(): array
|
||||
{
|
||||
switch ($this->bodymode) {
|
||||
case 'formdata':
|
||||
$output = [''];
|
||||
foreach ($this->body as $data) {
|
||||
$output[] = sprintf(
|
||||
'%s%s=%s',
|
||||
empty($data->disabled) ? '' : '# ',
|
||||
$data->key,
|
||||
$data->type === 'file' ? $data->src : $data->value
|
||||
);
|
||||
}
|
||||
return $output;
|
||||
default:
|
||||
return ['', $this->body];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
$output = array_merge(
|
||||
$this->prepareDescription(),
|
||||
$this->prepareHeaders(),
|
||||
$this->prepareBody()
|
||||
);
|
||||
return implode(PHP_EOL, $output);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ interface RequestContract
|
||||
public function setDescription(?string $description): static;
|
||||
public function setVerb(string $verb): static;
|
||||
public function setUrl(string $url): static;
|
||||
public function setAuth(object $auth): static;
|
||||
public function setHeaders(?array $headers): static;
|
||||
public function setBodymode(string $bodymode): static;
|
||||
public function setBody(object $body): static;
|
||||
|
||||
@@ -11,7 +11,8 @@ use PmConverter\Exporters\{
|
||||
class WgetConverter extends AbstractConverter implements ConverterContract
|
||||
{
|
||||
protected const FILE_EXT = 'sh';
|
||||
|
||||
protected const OUTPUT_DIR = 'wget';
|
||||
|
||||
protected const REQUEST = WgetRequest::class;
|
||||
protected const REQUEST_CLASS = WgetRequest::class;
|
||||
}
|
||||
|
||||
@@ -7,57 +7,75 @@ namespace PmConverter\Exporters\Wget;
|
||||
use PmConverter\Exporters\Abstract\AbstractRequest;
|
||||
|
||||
/**
|
||||
*
|
||||
* Class to determine file content with wget request format
|
||||
*/
|
||||
class WgetRequest extends AbstractRequest
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function prepareBody(): ?string
|
||||
protected function prepareDescription(): array
|
||||
{
|
||||
switch ($this->bodymode) {
|
||||
case 'formdata':
|
||||
$lines = [];
|
||||
foreach ($this->body as &$data) {
|
||||
if ($data->type === 'file') {
|
||||
continue;
|
||||
}
|
||||
$lines[$data->key] = $data->value;
|
||||
}
|
||||
$body[] = http_build_query($lines);
|
||||
return implode(PHP_EOL, $body);
|
||||
default:
|
||||
return $this->body;
|
||||
}
|
||||
return empty($this->description)
|
||||
? []
|
||||
: ['# ' . str_replace("\n", "\n# ", $this->description), ''];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __toString(): string
|
||||
protected function prepareHeaders(): array
|
||||
{
|
||||
$output[] = '#!/bin/sh';
|
||||
if ($this->description) {
|
||||
$output[] = '# ' . str_replace("\n", "\n# ", $this->description);
|
||||
$output[] = '';
|
||||
}
|
||||
$output[] = 'wget \ ';
|
||||
$output[] = "\t--no-check-certificate \ ";
|
||||
$output[] = "\t--quiet \ ";
|
||||
$output[] = "\t--timeout=0 \ ";
|
||||
$output[] = "\t--method $this->verb \ ";
|
||||
$output = [];
|
||||
foreach ($this->headers as $header_key => $header) {
|
||||
if ($header['disabled']) {
|
||||
continue;
|
||||
}
|
||||
$output[] = sprintf("\t--header '%s=%s' \ ", $header_key, $header['value']);
|
||||
}
|
||||
if (!is_null($body = $this->prepareBody())) {
|
||||
$output[] = "\t--body-data '$body' \ ";
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function prepareBody(): array
|
||||
{
|
||||
switch ($this->bodymode) {
|
||||
case 'formdata':
|
||||
$params = [];
|
||||
foreach ($this->body as $data) {
|
||||
if ($data->type === 'file') {
|
||||
continue;
|
||||
}
|
||||
$params[$data->key] = $data->value;
|
||||
}
|
||||
$output[] = http_build_query($params);
|
||||
return $output;
|
||||
default:
|
||||
return ["\t'$this->body' \ "];
|
||||
}
|
||||
$output[] = rtrim(array_pop($output), '\ ');
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
$output = array_merge(
|
||||
['#!/bin/sh'],
|
||||
$this->prepareDescription(),
|
||||
[
|
||||
'wget \ ',
|
||||
"\t--no-check-certificate \ ",
|
||||
"\t--quiet \ ",
|
||||
"\t--timeout=0 \ ",
|
||||
"\t--method $this->verb \ ",
|
||||
],
|
||||
$this->prepareHeaders(),
|
||||
$this->prepareBody()
|
||||
);
|
||||
$output[] = "\t'$this->url'";
|
||||
return implode(PHP_EOL, $output);
|
||||
return implode(PHP_EOL, array_merge($output, ['']));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types = 1);
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace PmConverter;
|
||||
|
||||
@@ -10,8 +10,17 @@ use PmConverter\Exceptions\{
|
||||
DirectoryIsNotWriteableException,
|
||||
DirectoryNotExistsException};
|
||||
|
||||
/**
|
||||
* Helper class to work with files and directories
|
||||
*/
|
||||
class FileSystem
|
||||
{
|
||||
/**
|
||||
* Normalizes a given path
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
public static function normalizePath(string $path): string
|
||||
{
|
||||
$path = str_replace('~', $_SERVER['HOME'], $path);
|
||||
@@ -19,6 +28,8 @@ class FileSystem
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively creates a new directory by given path
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
* @throws CannotCreateDirectoryException
|
||||
@@ -38,6 +49,8 @@ class FileSystem
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively removes a given directory
|
||||
*
|
||||
* @param string $path
|
||||
* @return void
|
||||
* @throws DirectoryIsNotReadableException
|
||||
@@ -65,23 +78,22 @@ class FileSystem
|
||||
{
|
||||
$path = static::normalizePath($path);
|
||||
if (!file_exists($path)) {
|
||||
throw new DirectoryNotExistsException("output directory is not exist: $path");
|
||||
throw new DirectoryNotExistsException("directory does not exist: $path");
|
||||
}
|
||||
if (!is_readable($path)) {
|
||||
throw new DirectoryIsNotReadableException("output directory permissions are not valid: $path");
|
||||
throw new DirectoryIsNotReadableException("directory permissions are not valid: $path");
|
||||
}
|
||||
if (!is_writable($path)) {
|
||||
throw new DirectoryIsNotWriteableException("output directory permissions are not valid: $path");
|
||||
throw new DirectoryIsNotWriteableException("directory permissions are not valid: $path");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns content of given directory path
|
||||
*
|
||||
* @param string $path
|
||||
* @return array
|
||||
* @throws DirectoryIsNotReadableException
|
||||
* @throws DirectoryIsNotWriteableException
|
||||
* @throws DirectoryNotExistsException
|
||||
*/
|
||||
public static function dirContents(string $path): array
|
||||
{
|
||||
@@ -92,4 +104,22 @@ class FileSystem
|
||||
}
|
||||
return $records;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given file is a valid collection json file
|
||||
*
|
||||
* @param string $path
|
||||
* @return bool
|
||||
*/
|
||||
public static function isCollectionFile(string $path): bool
|
||||
{
|
||||
$path = static::normalizePath($path);
|
||||
return !empty($path = trim($path))
|
||||
&& str_ends_with($path, '.postman_collection.json')
|
||||
&& file_exists($path)
|
||||
&& is_readable($path)
|
||||
&& ($json = json_decode(file_get_contents($path), true))
|
||||
&& json_last_error() === JSON_ERROR_NONE
|
||||
&& isset($json['collection']['info']['name']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,12 +22,12 @@ class Processor
|
||||
/**
|
||||
* Converter version
|
||||
*/
|
||||
public const VERSION = '1.0.0';
|
||||
public const VERSION = '1.2.3';
|
||||
|
||||
/**
|
||||
* @var string[] Paths to collection files
|
||||
*/
|
||||
protected array $collectionPaths;
|
||||
protected array $collectionPaths = [];
|
||||
|
||||
/**
|
||||
* @var string Output path where to put results in
|
||||
@@ -52,7 +52,27 @@ class Processor
|
||||
/**
|
||||
* @var object[] Collections that will be converted into choosen formats
|
||||
*/
|
||||
protected array $collections;
|
||||
protected array $collections = [];
|
||||
|
||||
/**
|
||||
* @var int Initial timestamp
|
||||
*/
|
||||
protected int $initTime;
|
||||
|
||||
/**
|
||||
* @var int Initial RAM usage
|
||||
*/
|
||||
protected int $initRam;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected string $envFile;
|
||||
|
||||
/**
|
||||
* @var Environment
|
||||
*/
|
||||
protected Environment $env;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
@@ -61,6 +81,8 @@ class Processor
|
||||
*/
|
||||
public function __construct(protected array $argv)
|
||||
{
|
||||
$this->initTime = hrtime(true);
|
||||
$this->initRam = memory_get_usage(true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,60 +102,82 @@ class Processor
|
||||
switch ($arg) {
|
||||
case '-f':
|
||||
case '--file':
|
||||
$path = $this->argv[$idx + 1];
|
||||
if (empty($path) || !str_ends_with($path, '.json') || !file_exists($path) || !is_readable($path)) {
|
||||
throw new InvalidArgumentException('a valid json-file path is expected for -f (--file)');
|
||||
$rawpath = $this->argv[$idx + 1];
|
||||
$normpath = FileSystem::normalizePath($rawpath);
|
||||
if (!FileSystem::isCollectionFile($normpath)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf("this is not a valid collection file:%s\t%s %s", PHP_EOL, $arg, $rawpath)
|
||||
);
|
||||
}
|
||||
$this->collectionPaths[] = $this->argv[$idx + 1];
|
||||
break;
|
||||
|
||||
case '-o':
|
||||
case '--output':
|
||||
if (empty($this->argv[$idx + 1])) {
|
||||
throw new InvalidArgumentException('-o expected');
|
||||
throw new InvalidArgumentException('-o is required');
|
||||
}
|
||||
$this->outputPath = $this->argv[$idx + 1];
|
||||
break;
|
||||
|
||||
case '-d':
|
||||
case '--dir':
|
||||
if (empty($this->argv[$idx + 1])) {
|
||||
throw new InvalidArgumentException('a directory path is expected for -d (--dir)');
|
||||
}
|
||||
$path = $this->argv[$idx + 1];
|
||||
if (FileSystem::checkDir($path)) {
|
||||
$files = array_filter(
|
||||
FileSystem::dirContents($path),
|
||||
static fn($filename) => str_ends_with($filename, '.json')
|
||||
);
|
||||
$this->collectionPaths = array_unique(array_merge($this?->collectionPaths ?? [], $files));
|
||||
}
|
||||
$rawpath = $this->argv[$idx + 1];
|
||||
$files = array_filter(
|
||||
FileSystem::dirContents($rawpath),
|
||||
static fn($filename) => FileSystem::isCollectionFile($filename)
|
||||
);
|
||||
$this->collectionPaths = array_unique(array_merge($this?->collectionPaths ?? [], $files));
|
||||
break;
|
||||
|
||||
case '-e':
|
||||
case '--env':
|
||||
$this->envFile = FileSystem::normalizePath($this->argv[$idx + 1]);
|
||||
break;
|
||||
|
||||
case '-p':
|
||||
case '--preserve':
|
||||
$this->preserveOutput = true;
|
||||
break;
|
||||
|
||||
case '--http':
|
||||
$this->formats[ConvertFormat::Http->name] = ConvertFormat::Http;
|
||||
break;
|
||||
|
||||
case '--curl':
|
||||
$this->formats[ConvertFormat::Curl->name] = ConvertFormat::Curl;
|
||||
break;
|
||||
|
||||
case '--wget':
|
||||
$this->formats[ConvertFormat::Wget->name] = ConvertFormat::Wget;
|
||||
break;
|
||||
|
||||
case '-v':
|
||||
case '--version':
|
||||
die(implode(PHP_EOL, $this->version()) . PHP_EOL);
|
||||
|
||||
case '-h':
|
||||
case '--help':
|
||||
die(implode(PHP_EOL, $this->usage()) . PHP_EOL);
|
||||
}
|
||||
}
|
||||
if (empty($this->collectionPaths)) {
|
||||
throw new InvalidArgumentException('there are no collections to convert');
|
||||
}
|
||||
if (empty($this->outputPath)) {
|
||||
throw new InvalidArgumentException('-o is required');
|
||||
}
|
||||
if (empty($this->formats)) {
|
||||
$this->formats = [ConvertFormat::Http->name => ConvertFormat::Http];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes output directory
|
||||
*
|
||||
* @return void
|
||||
* @throws CannotCreateDirectoryException
|
||||
* @throws DirectoryIsNotWriteableException
|
||||
@@ -161,6 +205,8 @@ class Processor
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes collection objects
|
||||
*
|
||||
* @throws JsonException
|
||||
*/
|
||||
protected function initCollections(): void
|
||||
@@ -175,33 +221,77 @@ class Processor
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes environment object
|
||||
*
|
||||
* @return void
|
||||
* @throws JsonException
|
||||
*/
|
||||
protected function initEnv(): void
|
||||
{
|
||||
if (!isset($this->envFile)) {
|
||||
return;
|
||||
}
|
||||
$content = file_get_contents(FileSystem::normalizePath($this->envFile));
|
||||
$content = json_decode($content, flags: JSON_THROW_ON_ERROR);
|
||||
if (!property_exists($content, 'environment') || empty($content?->environment)) {
|
||||
throw new JsonException("not a valid environment: $this->envFile");
|
||||
}
|
||||
$this->env = new Environment($content->environment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Begins a conversion
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function start(): void
|
||||
public function convert(): void
|
||||
{
|
||||
$this->parseArgs();
|
||||
$this->initOutputDirectory();
|
||||
$this->initConverters();
|
||||
$this->initCollections();
|
||||
$this->initEnv();
|
||||
$count = count($this->collections);
|
||||
$current = 0;
|
||||
$success = 0;
|
||||
print(implode(PHP_EOL, array_merge($this->version(), $this->copyright())) . PHP_EOL . PHP_EOL);
|
||||
foreach ($this->collections as $collectionName => $collection) {
|
||||
print("Converting '$collectionName':" . PHP_EOL);
|
||||
++$current;
|
||||
printf("Converting '%s' (%d/%d):%s", $collectionName, $current, $count, PHP_EOL);
|
||||
foreach ($this->converters as $type => $exporter) {
|
||||
print("\t-> " . strtolower($type));
|
||||
printf('> %s%s', strtolower($type), PHP_EOL);
|
||||
$outputPath = sprintf('%s%s%s', $this->outputPath, DIRECTORY_SEPARATOR, $collectionName);
|
||||
if (!empty($this->env)) {
|
||||
$exporter->withEnv($this->env);
|
||||
}
|
||||
$exporter->convert($collection, $outputPath);
|
||||
printf("\t- OK: %s%s", $exporter->getOutputPath(), PHP_EOL);
|
||||
printf(' OK: %s%s', $exporter->getOutputPath(), PHP_EOL);
|
||||
}
|
||||
print(PHP_EOL);
|
||||
++$success;
|
||||
}
|
||||
$this->printStats($success, $current);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs some statistics
|
||||
*
|
||||
* @param int $success
|
||||
* @param int $count
|
||||
* @return void
|
||||
*/
|
||||
protected function printStats(int $success, int $count): void
|
||||
{
|
||||
$time = (hrtime(true) - $this->initTime) / 1_000_000;
|
||||
$ram = (memory_get_peak_usage(true) - $this->initRam) / 1024 / 1024;
|
||||
printf('Converted %d of %d in %.3f ms using %.3f MiB RAM', $success, $count, $time, $ram);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
protected function version(): array
|
||||
public function version(): array
|
||||
{
|
||||
return ["Postman collection converter v" . self::VERSION];
|
||||
}
|
||||
@@ -209,7 +299,7 @@ class Processor
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
protected function copyright(): array
|
||||
public function copyright(): array
|
||||
{
|
||||
return [
|
||||
'Anthony Axenov (c) ' . date('Y') . ", MIT license",
|
||||
@@ -220,7 +310,7 @@ class Processor
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
protected function usage(): array
|
||||
public function usage(): array
|
||||
{
|
||||
return array_merge($this->version(), [
|
||||
'Usage:',
|
||||
@@ -233,16 +323,19 @@ class Processor
|
||||
"\t-f, --file - a PATH to single collection located in PATH to convert from",
|
||||
"\t-d, --dir - a directory with collections located in COLLECTION_FILEPATH to convert from",
|
||||
"\t-o, --output - a directory OUTPUT_PATH to put results in",
|
||||
"\t-e, --env - use environment file with variable values to replace in request",
|
||||
"\t-p, --preserve - do not delete OUTPUT_PATH (if exists)",
|
||||
"\t-h, --help - show this help message and exit",
|
||||
"\t-v, --version - show version info and exit",
|
||||
'',
|
||||
'If no ARGUMENTS passed then --help implied.',
|
||||
'If both -c and -d are specified then only unique set of files will be converted.',
|
||||
'If both -f and -d are specified then only unique set of files will be converted.',
|
||||
'-f or -d are required to be specified at least once, but each may be specified multiple times.',
|
||||
'PATH must be a valid path to readable json-file or directory.',
|
||||
'OUTPUT_PATH must be a valid path to writeable directory.',
|
||||
'If -o is specified several times then only last one will be used.',
|
||||
'If -e is specified several times then only last one will be used.',
|
||||
'If -e is not specified then only collection vars will be replaced (if any).',
|
||||
'',
|
||||
'Possible FORMATS:',
|
||||
"\t--http - generate raw *.http files (default)",
|
||||
@@ -256,6 +349,7 @@ class Processor
|
||||
" -f ~/dir1/first.postman_collection.json \ ",
|
||||
" --directory ~/team \ ",
|
||||
" --file ~/dir2/second.postman_collection.json \ ",
|
||||
" --env ~/localhost.postman_environment.json \ ",
|
||||
" -d ~/personal \ ",
|
||||
" -o ~/postman_export ",
|
||||
"",
|
||||
|
||||
Reference in New Issue
Block a user