Skip to content

Commit

Permalink
Add git init
Browse files Browse the repository at this point in the history
  • Loading branch information
gkoberger committed Oct 3, 2016
1 parent 36f3964 commit c75ed34
Show file tree
Hide file tree
Showing 5 changed files with 254 additions and 10 deletions.
8 changes: 4 additions & 4 deletions api.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,10 @@ exports.api = function(args, opts) {
};

exports.load = function(action) {
try {
//try {
return require(path.join(__dirname, 'lib', `${action}.js`));
} catch(e) {
console.log('Action not found');
}
//} catch(e) {
//console.log('Action not found');
//}
};

206 changes: 206 additions & 0 deletions lib/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
var colors = require('colors');
var inquirer = require('inquirer');
var fs = require('fs');
var crypto = require('crypto');
var YAML = require('json2yaml');
var utils = require('../utils');

exports.swagger = false;
exports.login = false;

var types = [
{ "name": "application/json", "checked": true },
{ "name": "application/xml" },
{ "name": "application/x-www-form-urlencoded" },
{ "name": "multipart/form-data" },
];

exports.run = function(config, info) {

console.log("This will help you set up an 'Open API' (formerly 'Swagger') file in your");
console.log("repo, so you can start documenting your API!");

console.log("");

var questions = [
{
type: 'input',
name: 'info.title',
message: 'Name of the API',
default: process.cwd().split('/').slice(-1)[0],
},
{
type: 'input',
name: 'info.version',
message: 'Version number',
default: '1.0.0',
},
{
type: 'input',
name: 'info.license',
message: 'License',
},
{
type: 'input',
name: 'url',
message: 'Full Base URL',
validate: function (value) {
var pass = /^(http|https|ws|wss):\/\/[^ "]+$/.test(value);

if (pass) {
return true;
}

return 'Please enter a valid URL, including protocol';
}
},
{
type: 'checkbox',
name: 'consumes',
message: 'Consumes content types',
choices: types,
},
{
type: 'checkbox',
name: 'produces',
message: 'Produces content types',
choices: types,
},
{
type: 'input',
name: 'output',
message: 'Output JSON or YAML file',
default: getDefaultSwagger(),
choices: types,
validate: function (value) {
var pass = /.(json|yaml|yml)$/.test(value);
var doesntExist = !fileExists(value);

if (pass && doesntExist) {
return true;
}

if(!pass) {
return 'Your file must end with .json or .yaml';
}
if(!doesntExist) {
return 'This file already exists';
}
}
},
{
type: 'list',
name: 'language',
message: 'API primary language',
choices: [
'JavaScript',
'Ruby',
'Python',
'CoffeeScript',
'PHP',
'Java',
'Go',
'Other',
],
validate: function (value) {
var pass = /.(json|yaml|yml)$/.test(value);
var doesntExist = !fileExists(value);

if (pass && doesntExist) {
return true;
}

if(!pass) {
return 'Your file must end with .json or .yaml';
}
if(!doesntExist) {
return 'This file already exists';
}
}
},
];

inquirer.prompt(questions).then(function (answers) {
var swagger = {
'swagger': '2.0',
'x-api-id': crypto.randomBytes(15).toString('hex'),
'info': {
'version': answers['info.version'],
'title': answers['info.title'],
},
};

if(answers['info.license']) {
swagger.info.license = {
'name': answers['info.license']
};
}

if(answers.produces.length) {
swagger.produces = answers.produces;
}

if(answers.consumes.length) {
swagger.consumes = answers.consumes;
}

var url = answers.url.match(/^(.*):\/\/([^\/]*)(.*)?$/);
swagger.schemes = [url[1]];
swagger.host = url[2];
if(url[3]) {
swagger.basePath = url[3];
}

writeFile(answers.output, swagger);

console.log("");
console.log("======================");
console.log("");
console.log("SUCCESS!".green);
console.log("");
console.log("We've created your new Open API file at " + answers.output.yellow + ".");
console.log("");
console.log("You can document each endpoint right above the code. Just use the");
console.log("following syntax in a comment above the code:");
console.log("");

console.log(utils.swaggerInlineExample(answers.language));

console.log('');
console.log('For more information on this syntax, see https://github.com/readmeio/swagger-inline');
console.log('');
console.log('To see what you can do with your API, type ' + 'api help'.yellow + '.');
console.log('');
console.log('');
});

};

function writeFile(output, swagger) {
var body = JSON.stringify(swagger, undefined, 2)
if(output.match(/.(yaml|yml)/)) {
body = YAML.stringify(swagger);
body = body.replace(/^\s\s/gm, '').replace(/^---\n/, '');
}
fs.writeFileSync(output, body)
}

function getDefaultSwagger() {
var i = 0;
while(file = fileExists(_file(i))) {
i++;
}
return _file(i);

function _file(i) {
return 'swagger' + (i ? i : '') + '.json';
}
}

function fileExists(file) {
try {
return fs.statSync(file).isFile();
} catch (err) {
return false;
}
}
6 changes: 0 additions & 6 deletions lib/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@ var request = require('request');
exports.swagger = true;
exports.login = true;

/*
* This will completely change 100%, and all files
* uploaded to apis.host will be removed! It's just
* a placeholder to kinda have something that works.
*/

exports.run = function(config, info) {
console.log('Uploading Swagger file...');

Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
"base-store": "^0.4.4",
"colors": "^1.1.2",
"git-utils": "^4.1.2",
"inquirer": "^1.2.1",
"json2yaml": "^1.1.0",
"jsonfile": "^2.3.1",
"lodash": "^4.13.1",
"minimist": "^1.2.0",
Expand Down
42 changes: 42 additions & 0 deletions utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,45 @@ exports.addId = function(file, id) {
return true;
};

exports.swaggerInlineExample = function(_lang) {
var prefix = ' ';

var annotation = [
'@api [get] /pet/{petId}',
'description: "Returns all pets from the system that the user has access to"',
'responses:',
' "200":',
' description: "A list of pets."',
' schema:',
' type: "String"',
];

var languages = {
'javascript': ['/*', ' * ', '*/', 'route.get("/pet/:petId", pet.show);'],
'java': ['/*', ' * ', '*/', 'public String getPet(id) {'],
'php': ['/*', ' * ', '*/', 'function showPet($id) {'],
'coffeescript': ['###', '', '###', "route.get '/pet/:petId', pet.show"],
'ruby': ['=begin', '', '=end', "get '/pet/:petId' do"],
'python': ['"""', '', '"""', "def getPet(id):"],
'go': ['/*', ' * ', '*/', 'func getPet(id) {'],
};

_lang = _lang.toLowerCase();
if(!_lang || !languages[_lang]) _lang = 'javascript';

var lang = languages[_lang];

var out = [
prefix + lang[0].cyan,
];

_.each(annotation, function(line) {
out.push(prefix + lang[1].cyan + line.cyan);
});

out.push(prefix + lang[2].cyan);
out.push(prefix + lang[3].grey);

return out.join("\n");
}

0 comments on commit c75ed34

Please sign in to comment.