Showing the changes to node_modules/simple-git/promise.js (1 of 41 files). Show all
Unified · Split
| @@ -0,0 +1,96 @@ | |||
| 1 | |||
| 2 | if (typeof Promise === 'undefined') { | ||
| 3 | throw new ReferenceError("Promise wrappers must be enabled to use the promise API"); | ||
| 4 | } | ||
| 5 | |||
| 6 | function isAsyncCall (fn) { | ||
| 7 | return /^[^)]+then\s*\)/.test(fn) || /\._run\(/.test(fn); | ||
| 8 | } | ||
| 9 | |||
| 10 | module.exports = function (baseDir) { | ||
| 11 | |||
| 12 | var Git = require('./src/git'); | ||
| 13 | var gitFactory = require('./src'); | ||
| 14 | var git; | ||
| 15 | |||
| 16 | |||
| 17 | var chain = Promise.resolve(); | ||
| 18 | |||
| 19 | try { | ||
| 20 | git = gitFactory(baseDir); | ||
| 21 | } | ||
| 22 | catch (e) { | ||
| 23 | chain = Promise.reject(e); | ||
| 24 | } | ||
| 25 | |||
| 26 | return Object.keys(Git.prototype).reduce(function (promiseApi, fn) { | ||
| 27 | if (/^_|then/.test(fn)) { | ||
| 28 | return promiseApi; | ||
| 29 | } | ||
| 30 | |||
| 31 | if (isAsyncCall(Git.prototype[fn])) { | ||
| 32 | promiseApi[fn] = git ? asyncWrapper(fn, git) : function () { | ||
| 33 | return chain; | ||
| 34 | }; | ||
| 35 | } | ||
| 36 | |||
| 37 | else { | ||
| 38 | promiseApi[fn] = git ? syncWrapper(fn, git, promiseApi) : function () { | ||
| 39 | return promiseApi; | ||
| 40 | }; | ||
| 41 | } | ||
| 42 | |||
| 43 | return promiseApi; | ||
| 44 | |||
| 45 | }, {}); | ||
| 46 | |||
| 47 | function asyncWrapper (fn, git) { | ||
| 48 | return function () { | ||
| 49 | var args = [].slice.call(arguments); | ||
| 50 | |||
| 51 | if (typeof args[args.length] === 'function') { | ||
| 52 | throw new TypeError( | ||
| 53 | "Promise interface requires that handlers are not supplied inline, " + | ||
| 54 | "trailing function not allowed in call to " + fn); | ||
| 55 | } | ||
| 56 | |||
| 57 | return chain.then(function () { | ||
| 58 | return new Promise(function (resolve, reject) { | ||
| 59 | args.push(function (err, result) { | ||
| 60 | if (err) { | ||
| 61 | return reject(toError(err)); | ||
| 62 | } | ||
| 63 | |||
| 64 | resolve(result); | ||
| 65 | }); | ||
| 66 | |||
| 67 | git[fn].apply(git, args); | ||
| 68 | }); | ||
| 69 | }); | ||
| 70 | }; | ||
| 71 | } | ||
| 72 | |||
| 73 | function syncWrapper (fn, git, api) { | ||
| 74 | return function () { | ||
| 75 | git[fn].apply(git, arguments); | ||
| 76 | |||
| 77 | return api; | ||
| 78 | }; | ||
| 79 | } | ||
| 80 | |||
| 81 | }; | ||
| 82 | |||
| 83 | function toError (error) { | ||
| 84 | |||
| 85 | if (error instanceof Error) { | ||
| 86 | return error; | ||
| 87 | } | ||
| 88 | |||
| 89 | if (typeof error === 'string') { | ||
| 90 | return new Error(error); | ||
| 91 | } | ||
| 92 | |||
| 93 | return Object.create(new Error(error), { | ||
| 94 | git: { value: error }, | ||
| 95 | }); | ||
| 96 | } | ||