Skip to content

Commit 8f1ec73

Browse files
committed
Merge branch 'feat/codebuilder/format'
Conflicts: src/targets/node/request.js
2 parents 3fb2bca + 6a0e4bd commit 8f1ec73

19 files changed

Lines changed: 144 additions & 129 deletions

File tree

src/helpers/code-builder.js

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
'use strict'
22

3+
var util = require('util')
4+
35
/**
46
* Helper object to format and aggragate lines of code.
57
* Lines are aggregated in a `code` array, and need to be joined to obtain a proper code snippet.
@@ -16,14 +18,29 @@ var CodeBuilder = function (indentation, join) {
1618
}
1719

1820
/**
19-
* Add given indentation level to given string
20-
* @param {number} [indentationLevel=0] Desired level of indentation for this line
21-
* @param {string} line Line of code
21+
* Add given indentation level to given string and format the string (variadic)
22+
* @param {number} [indentationLevel=0] - Desired level of indentation for this line
23+
* @param {string} line - Line of code. Can contain formatting placeholders
24+
* @param {...anyobject} - Parameter to bind to `line`'s formatting placeholders
2225
* @return {string}
26+
*
27+
* @example
28+
* var builder = CodeBuilder('\t')
29+
*
30+
* builder.buildLine('console.log("hello world")')
31+
* // returns: 'console.log("hello world")'
32+
*
33+
* builder.buildLine(2, 'console.log("hello world")')
34+
* // returns: 'console.log("\t\thello world")'
35+
*
36+
* builder.buildLine(2, 'console.log("%s %s")', 'hello', 'world')
37+
* // returns: 'console.log("\t\thello world")'
2338
*/
2439
CodeBuilder.prototype.buildLine = function (indentationLevel, line) {
2540
var lineIndentation = ''
41+
var slice = 2
2642
if (Object.prototype.toString.call(indentationLevel) === '[object String]') {
43+
slice = 1
2744
line = indentationLevel
2845
indentationLevel = 0
2946
} else if (indentationLevel === null) {
@@ -35,29 +52,32 @@ CodeBuilder.prototype.buildLine = function (indentationLevel, line) {
3552
indentationLevel--
3653
}
3754

38-
return lineIndentation + line
55+
var format = Array.prototype.slice.call(arguments, slice, arguments.length)
56+
format.unshift(lineIndentation + line)
57+
58+
return util.format.apply(this, format)
3959
}
4060

4161
/**
42-
* Add a line at the top of current lines with given indentation level
62+
* Invoke buildLine() and add the line at the top of current lines
4363
* @param {number} [indentationLevel=0] Desired level of indentation for this line
4464
* @param {string} line Line of code
4565
* @return {this}
4666
*/
47-
CodeBuilder.prototype.unshift = function (indentationLevel, str) {
48-
this.code.unshift(this.buildLine(indentationLevel, str))
67+
CodeBuilder.prototype.unshift = function () {
68+
this.code.unshift(this.buildLine.apply(this, arguments))
4969

5070
return this
5171
}
5272

5373
/**
54-
* Add a line at the end of current lines with given indentation level
74+
* Invoke buildLine() and add the line at the bottom of current lines
5575
* @param {number} [indentationLevel=0] Desired level of indentation for this line
5676
* @param {string} line Line of code
5777
* @return {this}
5878
*/
59-
CodeBuilder.prototype.push = function (indentationLevel, str) {
60-
this.code.push(this.buildLine(indentationLevel, str))
79+
CodeBuilder.prototype.push = function () {
80+
this.code.push(this.buildLine.apply(this, arguments))
6181

6282
return this
6383
}

src/targets/go/native.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,24 +64,24 @@ module.exports = function (source, options) {
6464
if (opts.timeout > 0) {
6565
client = 'client'
6666
code.push(1, 'client := http.Client{')
67-
.push(2, util.format('Timeout: time.Duration(%s * time.Second),', opts.timeout))
67+
.push(2, 'Timeout: time.Duration(%s * time.Second),', opts.timeout)
6868
.push(1, '}')
6969
.blank()
7070
} else {
7171
client = 'http.DefaultClient'
7272
}
7373

74-
code.push(1, util.format('url := "%s"', source.fullUrl))
74+
code.push(1, 'url := "%s"', source.fullUrl)
7575
.blank()
7676

7777
// If we have body content or not create the var and reader or nil
7878
if (source.postData.text) {
79-
code.push(1, util.format('payload := strings.NewReader(%s)', JSON.stringify(source.postData.text)))
79+
code.push(1, 'payload := strings.NewReader(%s)', JSON.stringify(source.postData.text))
8080
.blank()
81-
.push(1, util.format('req, %s := http.NewRequest("%s", url, payload)', errorPlaceholder, source.method))
81+
.push(1, 'req, %s := http.NewRequest("%s", url, payload)', errorPlaceholder, source.method)
8282
.blank()
8383
} else {
84-
code.push(1, util.format('req, %s := http.NewRequest("%s", url, nil)', errorPlaceholder, source.method))
84+
code.push(1, 'req, %s := http.NewRequest("%s", url, nil)', errorPlaceholder, source.method)
8585
.blank()
8686
}
8787

@@ -90,20 +90,20 @@ module.exports = function (source, options) {
9090
// Add headers
9191
if (Object.keys(source.allHeaders).length) {
9292
Object.keys(source.allHeaders).map(function (key) {
93-
code.push(1, util.format('req.Header.Add("%s", "%s")', key, source.allHeaders[key]))
93+
code.push(1, 'req.Header.Add("%s", "%s")', key, source.allHeaders[key])
9494
})
9595
code.blank()
9696
}
9797

9898
// Make request
99-
code.push(1, util.format('res, %s := %s.Do(req)', errorPlaceholder, client))
99+
code.push(1, 'res, %s := %s.Do(req)', errorPlaceholder, client)
100100
errorCheck()
101101

102102
// Get Body
103103
if (opts.printBody) {
104104
code.blank()
105105
.push(1, 'defer res.Body.Close()')
106-
.push(1, util.format('body, %s := ioutil.ReadAll(res.Body)', errorPlaceholder))
106+
.push(1, 'body, %s := ioutil.ReadAll(res.Body)', errorPlaceholder)
107107
errorCheck()
108108
}
109109

src/targets/java/unirest.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ module.exports = function (source, options) {
2323
var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ]
2424

2525
if (methods.indexOf(source.method.toUpperCase()) === -1) {
26-
code.push(util.format('HttpResponse<String> response = Unirest.customMethod("%s","%s")', source.method.toUpperCase(), source.fullUrl))
26+
code.push('HttpResponse<String> response = Unirest.customMethod("%s","%s")', source.method.toUpperCase(), source.fullUrl)
2727
} else {
28-
code.push(util.format('HttpResponse<String> response = Unirest.%s("%s")', source.method.toLowerCase(), source.fullUrl))
28+
code.push('HttpResponse<String> response = Unirest.%s("%s")', source.method.toLowerCase(), source.fullUrl)
2929
}
3030

3131
// Add headers, including the cookies
@@ -34,12 +34,12 @@ module.exports = function (source, options) {
3434
// construct headers
3535
if (headers.length) {
3636
headers.map(function (key) {
37-
code.push(1, util.format('.header("%s", "%s")', key, source.allHeaders[key]))
37+
code.push(1, '.header("%s", "%s")', key, source.allHeaders[key])
3838
})
3939
}
4040

4141
if (source.postData.text) {
42-
code.push(1, util.format('.body(%s)', JSON.stringify(source.postData.text)))
42+
code.push(1, '.body(%s)', JSON.stringify(source.postData.text))
4343
}
4444

4545
code.push(1, '.asString();')

src/targets/javascript/jquery.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ module.exports = function (source, options) {
4242
code.push('var form = new FormData();')
4343

4444
source.postData.params.map(function (param) {
45-
code.push(util.format('form.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || '')))
45+
code.push('form.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || ''))
4646
})
4747

4848
settings.processData = false

src/targets/javascript/xhr.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@ module.exports = function (source, options) {
2323

2424
switch (source.postData.mimeType) {
2525
case 'application/json':
26-
code.push(util.format('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)))
26+
code.push('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent))
2727
.push(null)
2828
break
2929

3030
case 'multipart/form-data':
3131
code.push('var data = new FormData();')
3232

3333
source.postData.params.map(function (param) {
34-
code.push(util.format('data.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || '')))
34+
code.push('data.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || ''))
3535
})
3636

3737
// remove the contentType header
@@ -43,7 +43,7 @@ module.exports = function (source, options) {
4343
break
4444

4545
default:
46-
code.push(util.format('var data = %s;', JSON.stringify(source.postData.text || null)))
46+
code.push('var data = %s;', JSON.stringify(source.postData.text || null))
4747
.blank()
4848
}
4949

@@ -60,10 +60,10 @@ module.exports = function (source, options) {
6060
.push(1, '}')
6161
.push('});')
6262
.blank()
63-
.push(util.format('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl)))
63+
.push('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl))
6464

6565
Object.keys(source.allHeaders).map(function (key) {
66-
code.push(util.format('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key])))
66+
code.push('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key]))
6767
})
6868

6969
code.blank()

src/targets/node/native.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ module.exports = function (source, options) {
2828
headers: source.allHeaders
2929
}
3030

31-
code.push(util.format('var http = require("%s");', source.uriObj.protocol.replace(':', '')))
31+
code.push('var http = require("%s");', source.uriObj.protocol.replace(':', ''))
3232

3333
code.blank()
34-
.push(util.format('var options = %s;', JSON.stringify(reqOpts, null, opts.indent)))
34+
.push('var options = %s;', JSON.stringify(reqOpts, null, opts.indent))
3535
.blank()
3636
.push('var req = http.request(options, function (res) {')
3737
.push(1, 'var chunks = [];')
@@ -51,23 +51,23 @@ module.exports = function (source, options) {
5151
case 'application/x-www-form-urlencoded':
5252
if (source.postData.paramsObj) {
5353
code.unshift('var qs = require("querystring");')
54-
code.push(util.format('req.write(qs.stringify(%s));', util.inspect(source.postData.paramsObj, {
54+
code.push('req.write(qs.stringify(%s));', util.inspect(source.postData.paramsObj, {
5555
depth: null
56-
})))
56+
}))
5757
}
5858
break
5959

6060
case 'application/json':
6161
if (source.postData.jsonObj) {
62-
code.push(util.format('req.write(JSON.stringify(%s));', util.inspect(source.postData.jsonObj, {
62+
code.push('req.write(JSON.stringify(%s));', util.inspect(source.postData.jsonObj, {
6363
depth: null
64-
})))
64+
}))
6565
}
6666
break
6767

6868
default:
6969
if (source.postData.text) {
70-
code.push(util.format('req.write(%s);', JSON.stringify(source.postData.text, null, opts.indent)))
70+
code.push('req.write(%s);', JSON.stringify(source.postData.text, null, opts.indent))
7171
}
7272
}
7373

src/targets/node/request.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ module.exports = function (source, options) {
9494
var url = source.url
9595

9696
source.cookies.map(function (cookie) {
97-
code.push(util.format('jar.setCookie(request.cookie("%s=%s"), "%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), url))
97+
code.push('jar.setCookie(request.cookie("%s=%s"), "%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), url)
9898
})
9999
code.blank()
100100
}
@@ -103,12 +103,11 @@ module.exports = function (source, options) {
103103
code.unshift('var fs = require("fs");')
104104
}
105105

106-
code.push(util.format('var options = %s;', util.inspect(reqOpts, {
107-
depth: null
108-
})))
106+
code.push('var options = %s;', util.inspect(reqOpts, { depth: null }))
109107
.blank()
110108

111109
code.push(util.format('request(options, %s', 'function (error, response, body) {'))
110+
112111
.push(1, 'if (error) throw new Error(error);')
113112
.blank()
114113
.push(1, 'console.log(body);')

src/targets/node/unirest.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,41 +23,41 @@ module.exports = function (source, options) {
2323

2424
code.push('var unirest = require("unirest");')
2525
.blank()
26-
.push(util.format('var req = unirest("%s", "%s");', source.method, source.url))
26+
.push('var req = unirest("%s", "%s");', source.method, source.url)
2727
.blank()
2828

2929
if (source.cookies.length) {
3030
code.push('var CookieJar = unirest.jar();')
3131

3232
source.cookies.forEach(function (cookie) {
33-
code.push(util.format('CookieJar.add("%s=%s","%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), source.url))
33+
code.push('CookieJar.add("%s=%s","%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), source.url)
3434
})
3535

3636
code.push('req.jar(CookieJar);')
3737
.blank()
3838
}
3939

4040
if (Object.keys(source.queryObj).length) {
41-
code.push(util.format('req.query(%s);', JSON.stringify(source.queryObj, null, opts.indent)))
41+
code.push('req.query(%s);', JSON.stringify(source.queryObj, null, opts.indent))
4242
.blank()
4343
}
4444

4545
if (Object.keys(source.headersObj).length) {
46-
code.push(util.format('req.headers(%s);', JSON.stringify(source.headersObj, null, opts.indent)))
46+
code.push('req.headers(%s);', JSON.stringify(source.headersObj, null, opts.indent))
4747
.blank()
4848
}
4949

5050
switch (source.postData.mimeType) {
5151
case 'application/x-www-form-urlencoded':
5252
if (source.postData.paramsObj) {
53-
code.push(util.format('req.form(%s);', JSON.stringify(source.postData.paramsObj, null, opts.indent)))
53+
code.push('req.form(%s);', JSON.stringify(source.postData.paramsObj, null, opts.indent))
5454
}
5555
break
5656

5757
case 'application/json':
5858
if (source.postData.jsonObj) {
5959
code.push('req.type("json");')
60-
.push(util.format('req.send(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)))
60+
.push('req.send(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent))
6161
}
6262
break
6363

@@ -84,12 +84,12 @@ module.exports = function (source, options) {
8484
}
8585
})
8686

87-
code.push(util.format('req.multipart(%s);', JSON.stringify(multipart, null, opts.indent)))
87+
code.push('req.multipart(%s);', JSON.stringify(multipart, null, opts.indent))
8888
break
8989

9090
default:
9191
if (source.postData.text) {
92-
code.push(opts.indent + util.format('req.send(%s);', JSON.stringify(source.postData.text, null, opts.indent)))
92+
code.push(opts.indent + 'req.send(%s);', JSON.stringify(source.postData.text, null, opts.indent))
9393
}
9494
}
9595

src/targets/objc/nsurlsession.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,11 @@ module.exports = function (source, options) {
4646
// we make it easier for the user to edit it according to his or her needs after pasting.
4747
// The user can just add/remove lines adding/removing body parameters.
4848
code.blank()
49-
.push(util.format('NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];',
50-
source.postData.params[0].name, source.postData.params[0].value))
49+
.push('NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];',
50+
source.postData.params[0].name, source.postData.params[0].value)
5151
for (var i = 1, len = source.postData.params.length; i < len; i++) {
52-
code.push(util.format('[postData appendData:[@"&%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];',
53-
source.postData.params[i].name, source.postData.params[i].value))
52+
code.push('[postData appendData:[@"&%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];',
53+
source.postData.params[i].name, source.postData.params[i].value)
5454
}
5555
break
5656

@@ -67,7 +67,7 @@ module.exports = function (source, options) {
6767
// we make it easier for the user to edit it according to his or her needs after pasting.
6868
// The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method.
6969
code.push(helpers.nsDeclaration('NSArray', 'parameters', source.postData.params, opts.pretty))
70-
.push(util.format('NSString *boundary = @"%s";', source.postData.boundary))
70+
.push('NSString *boundary = @"%s";', source.postData.boundary)
7171
.blank()
7272
.push('NSError *error;')
7373
.push('NSMutableString *body = [NSMutableString string];')

0 commit comments

Comments
 (0)