Skip to content
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

feat: adding a simple CLI #173

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
1 change: 0 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,5 @@
/tslint.json
/.eslintignore
/.eslintrc.json
/.travis.yml
/tsconfig.build.json
/tsconfig.test.json
5 changes: 0 additions & 5 deletions .travis.yml

This file was deleted.

4 changes: 2 additions & 2 deletions README.md
Nedgeva marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[![Build Status](https://travis-ci.org/devexperts/swagger-codegen-ts.svg?branch=master)](https://travis-ci.org/devexperts/swagger-codegen-ts)

# Typesafe OpenAPI generator for TypeScript

![](https://img.shields.io/npm/v/@devexperts/swagger-codegen-ts)

## Features
* Generates client code from **OpenAPI 3.0, 2.0** (aka Swagger) and **AsyncAPI** specs
* **Pluggable HTTP clients:** can use `fetch`, `Axios` or any other library
Expand Down
17 changes: 14 additions & 3 deletions docs/development/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,19 @@ TODO: describe the architecture and data flows

### FAQ
1. **Why don't spec codecs reuse common parts?**
That's because different versions of specs refer to different versions of [JSON Schema](http://json-schema.org) and they are generally not the same. We would like to avoid maintaining JSON Schema composition in this project. (for now)

That's because different versions of specs refer to different versions of [JSON Schema](http://json-schema.org) and they are generally not the same. We would like to avoid maintaining JSON Schema composition in this project. (for now)

### Publish
`npm version major|minor|patch`

GitHub Actions are configured to build and publish a new version when a [new release](https://github.com/devexperts/swagger-codegen-ts/releases/new) is created in GitHub.

If you need to run this process manually:
```
# bumps the version in package.json, builds the dist files
# and commits the updated CHANGELOG.md
yarn version

# uploads the package to the registry
yarn publish
```
12 changes: 8 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@
"test:lint": "eslint \"./src/**/*.ts\" \"./test/**/*.ts\" --fix",
"test:build": "tsc -p tsconfig.test.json",
"test:jest": "jest",
"test": "yarn test:lint && yarn prettier && yarn test:jest && yarn test:build",
"test": "yarn test:lint && yarn test:jest && yarn test:build",
"prettier": "prettier --list-different \"./src/**/*.ts\" \"./test/**/*.ts\"",
"prettier:fix": "prettier --write \"./src/**/*.ts\" \"./test/**/*.ts\"",
"prepublishOnly": "yarn test && yarn build",
"start": "nodemon --exec \"yarn test:run\"",
"build": "tsc -p tsconfig.build.json",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"preversion": "yarn test && yarn build",
"version": "yarn changelog && git add CHANGELOG.md"
},
"bin": {
"swagger-codegen-ts": "dist/cli/index.js"
},
"author": "devexperts",
"license": "MPL-2.0",
"repository": {
Expand All @@ -41,7 +44,8 @@
"eslint-plugin-prettier": "^3.1.1",
"fs-extra": "^8.1.0",
"json-schema-ref-parser": "^7.1.1",
"prettier": "^1.19.1"
"prettier": "^1.19.1",
"yargs": "^17.7.1"
},
"devDependencies": {
"@devexperts/lint": "^1.0.0-alpha.10",
Expand Down
114 changes: 114 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
const yargs = require('yargs'); // eslint-disable-line
andr3medeiros marked this conversation as resolved.
Show resolved Hide resolved
const { hideBin } = require('yargs/helpers'); // eslint-disable-line
import { array, either, taskEither } from 'fp-ts';
import { serialize as serializeOpenAPI3 } from '../language/typescript/3.0';
import { generate, Language } from '../index';
import { Decoder } from 'io-ts';
import { Reader } from 'fp-ts/lib/Reader';
import { ResolveRefContext } from '../utils/ref';
import { TaskEither } from 'fp-ts/lib/TaskEither';
import * as $RefParser from 'json-schema-ref-parser';
import * as path from 'path';
import { pipe } from 'fp-ts/lib/pipeable';
import { OpenapiObject, OpenapiObjectCodec } from '../schema/3.0/openapi-object';
import { SwaggerObject } from '../schema/2.0/swagger-object';
import { serialize as serializeSwagger } from '../language/typescript/2.0';
import { AsyncAPIObject, AsyncAPIObjectCodec } from '../schema/asyncapi-2.0.0/asyncapi-object';
import { serialize as serializeAsyncApi } from '../language/typescript/asyncapi-2.0.0';

const options = yargs(hideBin(process.argv))
.usage('swagger-codegen-ts -o <output_path> [flags] <path/to/spec.yaml>...')
.option('baseDir', {
alias: 'b',
describe: 'base directory for <specs> and <outDir> paths',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it really "outDir" or "baseDir", maybe a typo

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's correct if I understand you correctly
outDir is relative to baseDir

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After thinking a bit more on this, probably making outDir relative to the baseDir does not make much sense.
In the new commit this will be like this:

  • outDir is relative to the cwd (unless an absolute path is given);
  • each spec is relative to baseDir if it is provided, otherwise relative to the cwd

defaultDescription: 'current working dir',
})
.option('outDir', {
alias: 'o',
describe: 'path to the output files, relative to the <baseDir>',
})
.positional('', {
array: true,
type: 'string',
describe: 'list of OpenAPI or YAML specifications, paths relative to the <baseDir>',
}).argv;

const tasks = pipe(
andr3medeiros marked this conversation as resolved.
Show resolved Hide resolved
options._,
array.map((spec: string) => (options.baseDir ? path.resolve(options.baseDir, spec) : spec)),
array.map(spec =>
pipe(
detectCodec(spec),
taskEither.chain(codec =>
generate({
...(codec as any),
cwd: options.baseDir || process.cwd(),
spec,
out: options.outDir,
}),
),
),
),
array.array.sequence(taskEither.taskEither),
);

tasks().then(
either.fold(
error => {
console.error(error);
process.exit(1);
},
() => {
console.log('Generated successfully');
},
),
);

export interface DetectedCodec<A> {
readonly decoder: Decoder<unknown, A>;
readonly language: Reader<ResolveRefContext, Language<A>>;
}

const supportedCodecs = [
{
decoder: OpenapiObjectCodec,
language: serializeOpenAPI3,
},
{
decoder: SwaggerObject,
language: serializeSwagger,
},
{
decoder: AsyncAPIObjectCodec,
language: serializeAsyncApi,
},
];

function detectCodec(
spec: string,
): TaskEither<Error, DetectedCodec<OpenapiObject> | DetectedCodec<SwaggerObject> | DetectedCodec<AsyncAPIObject>> {
return pipe(
taskEither.tryCatch(
() =>
$RefParser.resolve(spec, {
resolve: {
external: false,
http: false,
},
}),
either.toError,
),
taskEither.map(refs => Object.entries(refs.values())),
taskEither.filterOrElse(
i => i.length === 1,
() => new Error('Could not detect the schema type for ' + spec),
),
taskEither.chain(([[, schema]]) =>
pipe(
supportedCodecs,
array.findFirst(c => either.isRight<unknown, unknown>(c.decoder.decode(schema))),
taskEither.fromOption(() => new Error('Could not detect the schema type for ' + spec)),
),
),
);
}
1 change: 1 addition & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"extends": "./tsconfig.json",
"include": [
"./src/index.ts",
"./src/cli/index.ts",
"./src/language/typescript/2.0/index.ts",
"./src/language/typescript/3.0/index.ts",
"./src/language/typescript/asyncapi-2.0.0/index.ts",
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"noEmitOnError": true
},
"exclude": [
"dist"
"dist", "node_modules"
],
"include": [
"test/index.spec.ts"
Expand Down
45 changes: 44 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ ansi-regex@^4.0.0, ansi-regex@^4.1.0:
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.1.tgz#164daac87ab2d6f6db3a29875e2d1766582dabed"
integrity sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==

ansi-regex@^5.0.0:
ansi-regex@^5.0.0, ansi-regex@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
Expand Down Expand Up @@ -1082,6 +1082,15 @@ cliui@^7.0.2:
strip-ansi "^6.0.0"
wrap-ansi "^7.0.0"

cliui@^8.0.1:
version "8.0.1"
resolved "https://registry.yarnpkg.com/cliui/-/cliui-8.0.1.tgz#0c04b075db02cbfe60dc8e6cf2f5486b1a3608aa"
integrity sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==
dependencies:
string-width "^4.2.0"
strip-ansi "^6.0.1"
wrap-ansi "^7.0.0"

co@^4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184"
Expand Down Expand Up @@ -4781,6 +4790,15 @@ string-width@^4.1.0, string-width@^4.2.0:
is-fullwidth-code-point "^3.0.0"
strip-ansi "^6.0.0"

string-width@^4.2.3:
version "4.2.3"
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
dependencies:
emoji-regex "^8.0.0"
is-fullwidth-code-point "^3.0.0"
strip-ansi "^6.0.1"

string.prototype.trimleft@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/string.prototype.trimleft/-/string.prototype.trimleft-2.1.0.tgz#6cc47f0d7eb8d62b0f3701611715a3954591d634"
Expand Down Expand Up @@ -4839,6 +4857,13 @@ strip-ansi@^6.0.0:
dependencies:
ansi-regex "^5.0.0"

strip-ansi@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
dependencies:
ansi-regex "^5.0.1"

strip-bom@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3"
Expand Down Expand Up @@ -5409,6 +5434,11 @@ yargs-parser@^20.2.2, yargs-parser@^20.2.3:
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee"
integrity sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==

yargs-parser@^21.1.1:
version "21.1.1"
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35"
integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==

yargs@^13.3.0:
version "13.3.0"
resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.0.tgz#4c657a55e07e5f2cf947f8a366567c04a0dedc83"
Expand Down Expand Up @@ -5438,6 +5468,19 @@ yargs@^16.2.0:
y18n "^5.0.5"
yargs-parser "^20.2.2"

yargs@^17.7.1:
version "17.7.1"
resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.7.1.tgz#34a77645201d1a8fc5213ace787c220eabbd0967"
integrity sha512-cwiTb08Xuv5fqF4AovYacTFNxk62th7LKJ6BL9IGUpTJrWoU7/7WdQGTP2SjKf1dUNBGzDd28p/Yfs/GI6JrLw==
dependencies:
cliui "^8.0.1"
escalade "^3.1.1"
get-caller-file "^2.0.5"
require-directory "^2.1.1"
string-width "^4.2.3"
y18n "^5.0.5"
yargs-parser "^21.1.1"

yn@^3.0.0:
version "3.1.1"
resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50"
Expand Down