forked from gabrielcsapo/node-git-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.js.html
More file actions
519 lines (449 loc) · 20.2 KB
/
git.js.html
File metadata and controls
519 lines (449 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>git.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="Git.html">Git</a><ul class='methods'><li data-type='method'><a href="Git.html#.close">close</a></li><li data-type='method'><a href="Git.html#.create">create</a></li><li data-type='method'><a href="Git.html#.exists">exists</a></li><li data-type='method'><a href="Git.html#.handle">handle</a></li><li data-type='method'><a href="Git.html#.list">list</a></li><li data-type='method'><a href="Git.html#.listen">listen</a></li><li data-type='method'><a href="Git.html#.mkdir">mkdir</a></li></ul></li><li><a href="HttpDuplex.html">HttpDuplex</a><ul class='methods'><li data-type='method'><a href="HttpDuplex.html#addTrailers">addTrailers</a></li><li data-type='method'><a href="HttpDuplex.html#cork">cork</a></li><li data-type='method'><a href="HttpDuplex.html#destroy">destroy</a></li><li data-type='method'><a href="HttpDuplex.html#end">end</a></li><li data-type='method'><a href="HttpDuplex.html#getHeader">getHeader</a></li><li data-type='method'><a href="HttpDuplex.html#pause">pause</a></li><li data-type='method'><a href="HttpDuplex.html#removeHeader">removeHeader</a></li><li data-type='method'><a href="HttpDuplex.html#resume">resume</a></li><li data-type='method'><a href="HttpDuplex.html#setDefaultEncoding">setDefaultEncoding</a></li><li data-type='method'><a href="HttpDuplex.html#setEncoding">setEncoding</a></li><li data-type='method'><a href="HttpDuplex.html#setHeader">setHeader</a></li><li data-type='method'><a href="HttpDuplex.html#uncork">uncork</a></li><li data-type='method'><a href="HttpDuplex.html#write">write</a></li><li data-type='method'><a href="HttpDuplex.html#writeContinue">writeContinue</a></li><li data-type='method'><a href="HttpDuplex.html#writeHead">writeHead</a></li><li data-type='method'><a href="HttpDuplex.html#writeHeader">writeHeader</a></li></ul></li><li><a href="Service.html">Service</a><ul class='methods'><li data-type='method'><a href="Service.html#.accept">accept</a></li><li data-type='method'><a href="Service.html#.reject">reject</a></li></ul></li></ul><h3>Modules</h3><ul><li><a href="module-lib_util.html">lib/util</a><ul class='methods'><li data-type='method'><a href="module-lib_util.html#~basicAuth">basicAuth</a></li><li data-type='method'><a href="module-lib_util.html#~createAction">createAction</a></li><li data-type='method'><a href="module-lib_util.html#~infoResponse">infoResponse</a></li><li data-type='method'><a href="module-lib_util.html#~noCache">noCache</a></li><li data-type='method'><a href="module-lib_util.html#~onExit">onExit</a></li><li data-type='method'><a href="module-lib_util.html#~parseGitName">parseGitName</a></li><li data-type='method'><a href="module-lib_util.html#~serviceRespond">serviceRespond</a></li></ul></li></ul><h3>Events</h3><ul><li><a href="HttpDuplex.html#event:close">close</a></li><li><a href="HttpDuplex.html#event:data">data</a></li><li><a href="HttpDuplex.html#event:drain">drain</a></li><li><a href="HttpDuplex.html#event:end">end</a></li><li><a href="HttpDuplex.html#event:error">error</a></li><li><a href="Git.html#event:fetch">fetch</a></li><li><a href="Git.html#event:head">head</a></li><li><a href="Git.html#event:info">info</a></li><li><a href="Git.html#event:push">push</a></li><li><a href="Git.html#event:tag">tag</a></li></ul><h3>Global</h3><ul><li><a href="global.html#getType">getType</a></li></ul>
</nav>
<div id="main">
<h1 class="page-title">git.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const url = require('url');
const qs = require('querystring');
const httpDuplex = require('./http-duplex');
const { spawn } = require('child_process');
const { EventEmitter } = require('events');
const { parseGitName, createAction, infoResponse, onExit, basicAuth, noCache } = require('./util');
const services = ['upload-pack', 'receive-pack'];
/**
* @event Git#push
* @type {Object}
* @property {HttpDuplex} push - is a http duplex object (see below) with these extra properties
* @property {String} push.repo - the string that defines the repo
* @property {String} push.commit - the string that defines the commit sha
* @property {String} push.branch - the string that defines the branch
* @example
repos.on('push', function (push) { ... }
Emitted when somebody does a `git push` to the repo.
Exactly one listener must call `push.accept()` or `push.reject()`. If there are
no listeners, `push.accept()` is called automatically.
*
**/
/**
* @event Git#tag
* @type {Object}
* @property {HttpDuplex} tag - an http duplex object (see below) with these extra properties:
* @property {String} tag.repo - the string that defines the repo
* @property {String} tag.commit - the string that defines the commit sha
* @property {String} tag.version - the string that defines the repo
* @example
repos.on('tag', function (tag) { ... }
Emitted when somebody does a `git push --tags` to the repo.
Exactly one listener must call `tag.accept()` or `tag.reject()`. If there are
No listeners, `tag.accept()` is called automatically.
*
**/
/**
* @event Git#fetch
* @type {Object}
* @property {HttpDuplex} fetch - an http duplex object (see below) with these extra properties:
* @property {String} fetch.repo - the string that defines the repo
* @property {String} fetch.commit - the string that defines the commit sha
* @example
repos.on('fetch', function (fetch) { ... }
Emitted when somebody does a `git fetch` to the repo (which happens whenever you
do a `git pull` or a `git clone`).
Exactly one listener must call `fetch.accept()` or `fetch.reject()`. If there are
no listeners, `fetch.accept()` is called automatically.
*
*/
/**
* @event Git#info
* @type {Object}
* @property {HttpDuplex} info - an http duplex object (see below) with these extra properties:
* @property {String} info.repo - the string that defines the repo
* @example
repos.on('info', function (info) { ... }
Emitted when the repo is queried for info before doing other commands.
Exactly one listener must call `info.accept()` or `info.reject()`. If there are
no listeners, `info.accept()` is called automatically.
*
*/
/**
* @event Git#info
* @type {Object}
* @property {HttpDuplex} info - an http duplex object (see below) with these extra properties:
* @property {String} info.repo - the string that defines the repo
* @example
repos.on('info', function (info) { ... }
Emitted when the repo is queried for info before doing other commands.
Exactly one listener must call `info.accept()` or `info.reject()`. If there are
no listeners, `info.accept()` is called automatically.
*
*/
/**
* @event Git#head
* @type {Object}
* @property {HttpDuplex} head - an http duplex object (see below) with these extra properties:
* @property {String} head.repo - the string that defines the repo
* @example
repos.on('head', function (head) { ... }
Emitted when the repo is queried for HEAD before doing other commands.
Exactly one listener must call `head.accept()` or `head.reject()`. If there are
no listeners, `head.accept()` is called automatically.
*
*/
class Git extends EventEmitter {
/**
*
* Handles invoking the git-*-pack binaries
* @class Git
* @extends EventEmitter
* @param {(String|Function)} repoDir - Create a new repository collection from the directory `repoDir`. `repoDir` should be entirely empty except for git repo directories. If `repoDir` is a function, `repoDir(repo)` will be used to dynamically resolve project directories. The return value of `repoDir(repo)` should be a string path specifying where to put the string `repo`. Make sure to return the same value for `repo` every time since `repoDir(repo)` will be called multiple times.
* @param {Object} options - options that can be applied on the new instance being created
* @param {Boolean=} options.autoCreate - By default, repository targets will be created if they don't exist. You can
disable that behavior with `options.autoCreate = true`
* @param {Function} options.authenticate - a function that has the following arguments (repo, username, password, next) and will be called when a request comes through if set
*
authenticate: (type, repo, username, password, next) => {
console.log(type, repo, username, password);
next();
}
// alternatively you can also pass authenticate a promise
authenticate: (type, repo, username, password, next) => {
console.log(type, repo, username, password);
return new Promise((resolve, reject) => {
if(username === 'foo') {
return resolve();
}
return reject("sorry you don't have access to this content");
});
}
* @param {Boolean=} options.checkout - If `opts.checkout` is true, create and expected checked-out repos instead of bare repos
*/
constructor(repoDir, options={}) {
super();
if(typeof repoDir === 'function') {
this.dirMap = repoDir;
} else {
this.dirMap = (dir) => {
return (path.normalize(dir ? path.resolve(repoDir, dir) : repoDir));
};
}
this.authenticate = options.authenticate;
this.autoCreate = options.autoCreate === false ? false : true;
this.checkout = options.checkout;
}
/**
* Get a list of all the repositories
* @method list
* @memberof Git
* @param {Function} callback function to be called when repositories have been found `function(error, repos)`
*/
list(callback) {
fs.readdir(this.dirMap(), (error, results) => {
if(error) return callback(error);
let repos = results.filter((r) => {
return r.substring(r.length - 3, r.length) == 'git';
}, []);
callback(null, repos);
});
}
/**
* Find out whether `repoName` exists in the callback `cb(exists)`.
* @method exists
* @memberof Git
* @param {String} repo - name of the repo
* @param {Function=} callback - function to be called when finished
*/
exists(repo, callback) {
fs.exists(this.dirMap(repo), callback);
}
/**
* Create a subdirectory `dir` in the repo dir with a callback `cb(err)`.
* @method mkdir
* @memberof Git
* @param {String} dir - directory name
* @param {Function=} callback - callback to be called when finished
*/
mkdir(dir, callback) {
// TODO: remove sync operations
const parts = this.dirMap(dir).split(path.sep);
for(var i = 0; i <= parts.length; i++) {
const directory = parts.slice(0, i).join(path.sep);
if(directory && !fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
}
callback();
}
/**
* Create a new bare repository `repoName` in the instance repository directory.
* @method create
* @memberof Git
* @param {String} repo - the name of the repo
* @param {Function=} callback - Optionally get a callback `cb(err)` to be notified when the repository was created.
*/
create(repo, callback) {
var self = this;
if (typeof callback !== 'function') callback = function () {};
if (!/\.git$/.test(repo)) repo += '.git';
self.exists(repo, function (ex) {
if (!ex) {
self.mkdir(repo, next);
} else {
next();
}
});
function next (err) {
if (err) return callback(err);
var ps, error = '';
var dir = self.dirMap(repo);
if (self.checkout) {
ps = spawn('git', [ 'init', dir ]);
}
else {
ps = spawn('git', [ 'init', '--bare', dir ]);
}
ps.stderr.on('data', function (buf) { error += buf; });
onExit(ps, function (code) {
if (!callback) { return; }
else if (code) callback(error || true);
else callback(null);
});
}
}
/**
* returns the typeof service being process
* @method getType
* @param {String} service - the service type
* @return {String} - will respond with either upload or download
*/
getType(service) {
switch(service) {
case 'upload-pack':
return 'fetch';
case 'receive-pack':
return 'push';
default:
return 'unknown';
}
}
/**
* Handle incoming HTTP requests with a connect-style middleware
* @method handle
* @memberof Git
* @param {Object} req - http request object
* @param {Object} res - http response object
*/
handle(req, res) {
const handlers = [
function(req, res) {
if (req.method !== 'GET') return false;
var self = this;
var u = url.parse(req.url);
var m = u.pathname.match(/\/(.+)\/info\/refs$/);
if (!m) return false;
if (/\.\./.test(m[1])) return false;
var repo = m[1];
var params = qs.parse(u.query);
if (!params.service) {
res.statusCode = 400;
res.end('service parameter required');
return;
}
var service = params.service.replace(/^git-/, '');
if (services.indexOf(service) < 0) {
res.statusCode = 405;
res.end('service not available');
return;
}
var repoName = parseGitName(m[1]);
var next = (error) => {
if(error) {
res.setHeader("Content-Type", 'text/plain');
res.setHeader("WWW-Authenticate", 'Basic realm="authorization needed"');
res.writeHead(401);
res.end(typeof error === 'string' ? error : error.toString());
return;
} else {
return infoResponse(self, repo, service, req, res);
}
};
// check if the repo is authenticated
if(this.authenticate) {
const type = this.getType(service);
const promise = this.authenticate(type, repoName, basicAuth.bind(null, req, res), (error) => {
return next(error);
});
if(promise instanceof Promise) {
return promise
.then(next)
.catch(next);
}
} else {
return next();
}
},
function(req, res) {
if (req.method !== 'GET') return false;
var u = url.parse(req.url);
var m = u.pathname.match(/^\/(.+)\/HEAD$/);
if (!m) return false;
if (/\.\./.test(m[1])) return false;
var self = this;
var repo = m[1];
var next = () => {
const file = self.dirMap(path.join(m[1], 'HEAD'));
self.exists(file, (ex) => {
if (ex) fs.createReadStream(file).pipe(res);
else {
res.statusCode = 404;
res.end('not found');
}
});
};
self.exists(repo, (ex) => {
const anyListeners = self.listeners('head').length > 0;
const dup = new httpDuplex(req, res);
dup.exists = ex;
dup.repo = repo;
dup.cwd = self.dirMap(repo);
dup.accept = dup.emit.bind(dup, 'accept');
dup.reject = dup.emit.bind(dup, 'reject');
dup.once('reject', (code) => {
dup.statusCode = code || 500;
dup.end();
});
if (!ex && self.autoCreate) {
dup.once('accept', (dir) => {
self.create(dir || repo, next);
});
self.emit('head', dup);
if (!anyListeners) dup.accept();
} else if (!ex) {
res.statusCode = 404;
res.setHeader('content-type', 'text/plain');
res.end('repository not found');
} else {
dup.once('accept', next);
self.emit('head', dup);
if (!anyListeners) dup.accept();
}
});
},
function(req, res) {
if (req.method !== 'POST') return false;
var m = req.url.match(/\/(.+)\/git-(.+)/);
if (!m) return false;
if (/\.\./.test(m[1])) return false;
var self = this;
var repo = m[1],
service = m[2];
if (services.indexOf(service) < 0) {
res.statusCode = 405;
res.end('service not available');
return;
}
res.setHeader('content-type', 'application/x-git-' + service + '-result');
noCache(res);
var action = createAction({
repo: repo,
service: service,
cwd: self.dirMap(repo)
}, req, res);
action.on('header', () => {
var evName = action.evName;
var anyListeners = self.listeners(evName).length > 0;
self.emit(evName, action);
if (!anyListeners) action.accept();
});
},
(req, res) => {
if (req.method !== 'GET' && req.method !== 'POST') {
res.statusCode = 405;
res.end('method not supported');
} else {
return false;
}
},
(req, res) => {
res.statusCode = 404;
res.end('not found');
}
];
res.setHeader('connection', 'close');
var self = this;
(function next(ix) {
var done = () => {
next(ix + 1);
};
var x = handlers[ix].call(self, req, res, done);
if (x === false) next(ix + 1);
})(0);
}
/**
* starts a git server on the given port
* @method listen
* @memberof Git
* @param {Number} port - the port to start the server on
* @param {Object=} options - the options to add extended functionality to the server
* @param {String=} options.type - this is either https or http (the default is http)
* @param {Buffer|String=} options.key - the key file for the https server
* @param {Buffer|String=} options.cert - the cert file for the https server
* @param {Function} callback - the function to call when server is started or error has occured
*/
listen(port, options, callback) {
const self = this;
if(typeof options == 'function' || !options) {
callback = options;
options = { type: 'http' };
}
const createServer = options.type == 'http' ? http.createServer : https.createServer.bind(this, options);
this.server = createServer(function(req, res) {
self.handle(req, res);
});
this.server.listen(port, callback);
}
/**
* closes the server instance
* @method close
* @memberof Git
*/
close() {
this.server.close();
}
}
module.exports = Git;
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/linenumber.js"></script>
</body>
</html>