-
Notifications
You must be signed in to change notification settings - Fork 1
/
gittattle.js
executable file
·636 lines (590 loc) · 21.2 KB
/
gittattle.js
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
#!/usr/bin/env node
var http = require('http'),
fs = require('fs'),
util = require('util'),
url = require('url'),
path = require('path'),
child_process = require('child_process'),
error = require('./serverUtils').error,
respond = require('./serverUtils').respond,
DEFAULT_HEADERS = require('./serverUtils').DEFAULT_HEADERS,
Router = require('./router');
DeepRepo = require('./DeepRepo');
// GITTATTLE
// ---------
// Implements a very straightforward minimal web api
var file = 'gittattle.json';
var filepath = path.resolve(__dirname, file);
var gitpattern = /(.*?)\.git/;
var DEFAULT_COUNT = 30;
var config = {
gitdir: '/var/lib/gitolite/repositories',
port: 9902,
tar: 'tar',
fastTimeout: 1400,
logEntriesPerPage: DEFAULT_COUNT,
serveIndexPage: true,
failOnNoDir: true,
blacklist: [],
whitelist: [],
listfilter: ''
};
// Look for a file named gittattle.json in the process working dir, and
// if present, override config defaults with its contents
if (fs.existsSync(filepath)) {
var loaded = JSON.parse(fs.readFileSync(filepath, {encoding: 'utf8'}));
for (var key in loaded) {
config[key] = loaded[key]
}
}
// ensure gitolite-admin.git is never exposed
config.blacklist.unshift('gitolite-admin.git');
config.whitelist = config.whitelist.join(' ')
.replace(/gitolite\-admin\.git/g, '')
.trim()
.replace(/\s+/g, ' ')
.split(' ');
// Note: When the string is empty,
// split returns an array containing one empty string,
// rather than an empty array.
if (config.whitelist[0] == '') {
config.whitelist.pop();
}
// check config.listfilter value
if (!/^(blacklist|whitelist)$/.test(config.listfilter)) {
// try autodetection - blacklist takes precedence over whitelist for backwards compatibility
config.listfilter = config.whitelist.length > 0 &&
config.blacklist.length <= 1 ? 'whitelist' : 'blacklist';
}
// in case of whitelist we need to allow deep search
if (/whitelist/.test(config.listfilter)) {
var parts = [];
config.whitelist.forEach(function(path) {
var chunk = path.split(/\//),
buildpath = '';
chunk.pop();
for (var i=0, l=chunk.length; i < l; i++) {
buildpath += (i > 0 ? '/' : '') + chunk[i];
if (parts.indexOf(buildpath) < 0) {
parts.push(buildpath);
}
}
});
config.whitelist = config.whitelist.concat(parts);
}
// Bail out early if gitdir is not set, or if failOnNoDir is true and the
// dir does not exist
if (!config.gitdir || (config.failOnNoDir && !fs.existsSync(config.gitdir))) {
throw new Error("Git dir does not exist: '" + config.gitdir + "'")
}
var deepRepoInst = DeepRepo.create(config.gitdir, gitpattern);
var listFileRex = /\/git\/[^\/`'"'&|<>]*\/get\/([^&`'"|<>]*)/;
var downloadRex = /\/git\/([^\/`'"'&|<>]*)\.([tarzipgb2x\.]*)$/;
var router = new Router();
// Redirects to the UI home page
router.getAndHead("", redir);
router.getAndHead("/", redir);
router.getAndHead(/\/git$/, redir);
// Static content
if (config.serveIndexPage) {
router.getAndHead(/\/git\/index.html/, getFile('index.html'), 'Index page');
router.getAndHead(/\/git\/?$/, getFile('index.html'), 'Index page');
router.getAndHead(/\/git\/ajax-loader.gif/, getFile('ajax-loader.gif'), 'Progress animation');
}
// Web API
router.getAndHead('/git/list', list, 'List repositories');
router.getAndHead(downloadRex, archive, 'Fetch an archive of a repository');
router.getAndHead(/\/git\/[^\/`'"'&|<>]*$/, log, 'Fetch log for one repository');
router.getAndHead(/\/git\/[^\/`'"'&|<>]*\/[abcdef1234567890]*$/, diff, 'Fetch a change set')
router.getAndHead(/\/git\/[^\/`'"'&|<>]*\/list$/, listFiles, 'List files');
router.getAndHead(listFileRex, getOneFile, 'List files');
// Start the server
router.createSimpleServer(config.port, function onStart(err) {
if (err)
throw err;
console.log('Started git server on ' + config.port + " over " + config.gitdir);
});
// Redirect requests to the site root
function redir(req, res) {
res.writeHead(302, {
Location: '/git/'
});
res.end("Redirecting to git server root");
}
// Web API calls:
function getFile(file) {
var dir = path.dirname(module.filename);
var pth = path.join(dir, file);
if (!fs.existsSync(pth)) {
throw new Error(pth + " does not exist");
}
var contentType = guessContentType(pth);
return function serveFile(req, res) {
fs.stat(pth, function(err, stat) {
if (err) {
return error(req, res, err);
}
if (req.headers['if-modified-since']) {
var date = new Date(req.headers['if-modified-since']);
if (date <= mtime) {
res.writeHead(304)
return res.end()
}
}
var mtime = stat.mtime;
var stream = fs.createReadStream(pth);
var hdrs = {
'Content-Type': contentType,
'Last-Modified': mtime
};
if (/image/.test(contentType) || /javascript/.test(contentType)) {
var expires = new Date();
expires.setFullYear(expires.getFullYear() + 10)
hdrs['Expires'] = expires
hdrs['Cache-Control'] = 'public, max-age=600000'
} else {
hdrs['Cache-Control'] = 'public, must-revalidate'
}
res.writeHead(200, hdrs);
stream.pipe(res);
});
}
}
// PENDING: include tags and branches in basic repo info
function copy(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result.push(arr[i])
}
return result;
}
function gitCommits(pth, n, cb, skip) {
// The terrifying ^@^ delimiter is so that we can escape quotes safely,
// after which we can replace them with quotes. If anybody actually uses
// this sequence in a commit message, well, it will be a weird hack.
var skipArg = '';
if (skip) {
skipArg = ' --skip=' + skip + ' ';
}
// Basically we're getting `git log` to return pseudo-JSON
var cmd = 'git log -n' + n + ' --branches=* ' + skipArg
+ ' --pretty=format:\'{%n^@^hash^@^:^@^%h^@^,%n^@^author^@^:^@^%an^@^,%n^@^date^@^:^@^%ad^@^,%n^@^email^@^:^@^%aE^@^,%n^@^message^@^:^@^%s^@^,%n^@^commitDate^@^:^@^%ai^@^,%n^@^age^@^:^@^%cr^@^},\'';
var opts = {
cwd: pth,
timeout: config.fastTimeout
};
if (!gitpattern.test(pth)) {
opts.cwd += '.git';
}
child_process.exec(cmd, opts, function(err, stdout) {
if (err)
return cb(err)
var out = ("" + stdout).replace(/\\/g, '\\\\').replace(/"/gm, '\\"').replace(/\^@\^/gm, '"').replace(/[\f\r\n]/g, "");
if (out[out.length - 1] === ',') {
out = out.substring(0, out.length - 1);
}
out = '[' + out + ']';
try {
var parsed = JSON.parse(out);
for (var i = 0; i < parsed.length; i++) {
if (parsed[i].date) {
parsed[i].date = new Date(Date.parse(parsed[i].date))
}
}
cb(null, parsed);
} catch (err) {
cb(err, out)
}
});
}
function diff(req, res) {
var u = url.parse(req.url, true);
var portions = u.pathname.split(/\//g);
var repo = deepRepoInst.object(portions[portions.length - 2]);
var commit = portions[portions.length - 1];
var dir = repo.location;
fs.exists(dir, function(exists) {
if (!exists)
return error(req, res, 'No such repository ' + repo.name + '\n', 404);
var opts = {
cwd: dir,
timeout: config.fastTimeout
}
var cmdline = 'git diff-tree --patch-with-stat "' + commit + '"';
var expires = new Date();
// Set expiration date 10 years in the future - a commit will always
// match its hash
expires.setFullYear(expires.getFullYear() + 10);
res.writeHead(200, {
'Content-Type': 'text/plain; charset=UTF-8',
Expires: expires,
'Cache-Control': 'public'
});
var proc = child_process.exec(cmdline, opts);
proc.stdout.pipe(res);
});
}
function archive(req, res) {
var u = url.parse(req.url, true);
var x = downloadRex.exec(u.pathname);
var repo = x[1];
if (/(.*)\.tar/.test(repo)) {
repo = /(.*?)\.tar/.exec(repo)[1];
}
// Do a little hack to pipe it through xz or bz2, so we can
// support those target formats
var orepo = deepRepoInst.object(repo);
var dir = orepo.location;
var branch = u.query.branch || 'HEAD' || 'master';
var fmt = x[2];
var format = 'tar';
var cmdline = 'git archive --format='
var postProcess = '';
var contentType = 'application/x-tar';
switch (fmt) {
case 'tar' :
break;
case 'zip' :
format = 'zip';
contentType = 'application/zip'
break;
case 'gz' :
format = 'tar.gz'
contentType = 'application/x-gtar';
break;
case 'bz2' :
postProcess = ' | bzip2 -9c'
contentType = 'application/x-gtar';
break;
case 'xz' :
postProcess = ' | xz -9c'
contentType = 'application/x-xz';
break;
default :
return error(req, res, 'Unknown format ' + fmt, 400);
}
cmdline += format + ' ' + branch + postProcess;
var opts = {
cwd: dir,
timeout: 24000,
encoding: 'binary'
}
// XXX for some reason, when piping the process output directly to the
// http response, the result ends up truncated. For now use a temporary
// file and serve that
var tempfile = '/tmp/' + new Date().getTime() + '_' + repo + '-' + Math.random() + '.' + format;
cmdline += ' > ' + tempfile;
res.writeHead(200, {
'Content-Type': contentType,
'Content-Disposition': 'inline;filename=' + orepo.archive + '.' + format
});
var proc = child_process.exec(cmdline, opts, function(err, stdout) {
if (err)
console.log(err);
var str = fs.createReadStream(tempfile);
str.on('close', function() {
fs.unlink(tempfile);
})
str.pipe(res);
});
}
function guessContentType(pth) {
var contentType = "application/octet-stream";
var rex = /.*\.(.*)/;
if (rex.test(pth)) {
switch (rex.exec(pth.toLowerCase())[1]) {
case 'js' :
contentType = 'application/javascript; charset=utf8';
break;
case 'java' :
contentType = 'text/x-java; charset=utf8';
break;
case 'woff' :
contentType = 'font/woff';
break;
case 'ttf' :
contentType = 'font/ttf';
break;
case 'gif' :
contentType = 'image/gif';
break;
case 'png' :
contentType = 'image/png';
break;
case 'jpg' :
case 'jpeg' :
contentType = 'image/jpeg';
break;
case 'txt' :
break;
case 'html' :
contentType = 'text/html; charset=utf8';
break;
case 'md' :
case 'markdown' :
contentType = 'text/x-markdown; charset=utf8';
break;
case 'xml' :
contentType = 'text/xml; charset=utf8';
break;
case 'css' :
contentType = 'text/css; charset=utf8';
break;
case 'mf' :
contentType = 'text/x-manifest; charset=utf8';
break;
case 'json' :
contentType = 'application/json; charset=utf8';
break;
case 'rb' :
contentType = 'text/ruby; charset=utf8';
break;
case 'zip' :
contentType = 'application/zip';
break;
case 'xz' :
contentType = 'application/x-xz';
break;
case 'jar' :
contentType = 'application/jar';
break;
case 'bz2' :
contentType = 'application/x-bzip2';
break;
case 'gz' :
contentType = 'application/x-gzip';
break;
}
}
return contentType;
}
function getOneFile(req, res) {
// Use git show to list the file - we never actually unpack it to disk,
// just read the index
var self = this;
var u = url.parse(self.req.url, true);
var portions = u.pathname.split(/\//g);
var repo = deepRepoInst.object(portions[2]);
var dir = repo.location
var pth = "";
var raw = u.query.raw;
var branch = u.query.branch || 'HEAD' || 'master';
for (var i = 4; i < portions.length; i++) {
if (pth.length > 0) {
pth += '/'
}
pth += portions[i];
}
fs.exists(dir, function(exists) {
if (!exists)
return error(req, res, 'No such repository ' + repo.name + '\n', 404);
var opts = {
cwd: dir,
timeout: config.fastTimeout
}
var contentType = 'text/plain; charset=UTF-8';
if (raw || /.*\.gif/.test(pth) || /.*\.png/.test(pth) || /.*\.jpg/.test(pth)) {
var rex = /.*\.(.*)/;
if (rex.test(pth)) {
contentType = guessContentType(pth);
}
}
var cmdline = 'git show --format=raw "' + branch + ':' + pth + '"';
var proc = child_process.exec(cmdline, opts);
self.res.writeHead(200, {'Content-Type': contentType});
proc.stdout.setEncoding('binary');
proc.stdout.pipe(res);
});
}
function listFiles(req, res) {
var self = this;
var u = url.parse(self.req.url, true);
var portions = u.pathname.split(/\//g);
var repo = deepRepoInst.object(portions[portions.length - 2]);
var dir = repo.location;
var branch = u.query.branch || 'HEAD' || 'master';
var rex = /([dwrxs-]{10})\s+(\S+)\s+(\d+)\s+([\d-]+)\s+([\d:-]+)\s+(.*)$/gm
fs.exists(dir, function(exists) {
if (!exists)
return error(req, res, 'No such repository ' + repo.name + '\n', 404);
var opts = {
cwd: dir,
timeout: config.fastTimeout
}
// PENDING: This is pretty horribly inefficient, since we're archiving
// the entire repo in order to list it - find another way
var cmdline = 'git archive "' + branch + '"| ' + config.tar + ' -tv';
child_process.exec(cmdline, opts, function(err, stdout, stderr) {
if (err)
return error(req, res, err);
var split = (stdout + '').split('\n');
var result = [];
for (var i = 0; i < split.length; i++) {
var dta = split[i].split(/\s+/);
if (/^([dwrxs-]{10})/.test(dta[0])) {
var isFile = dta[0][0] != 'd';
var name = dta[5].split(/\//gm);
if (name && name.length > 0) {
name = name[name.length - 1];
} else {
name = dta[5];
}
if (isFile) {
var item = {
type: dta[0],
name: name,
// owner: dta[1],
size: parseInt(dta[2]),
date: new Date(Date.parse(dta[3] + ' ' + dta[4])), // XXX timezone
// date: dta[3],
// time: dta[4],
path: dta[5]
};
result.push(item)
}
}
}
respond(req, res, result)
});
});
}
function log(req, res) {
var self = this;
var u = url.parse(self.req.url, true);
var portions = u.pathname.split(/\//g);
var repo = deepRepoInst.object(portions[portions.length - 1]);
var dir = repo.location;
fs.exists(dir, function(exists) {
var skip = null;
var count = config.logEntriesPerPage;
if (typeof u.query.skip !== 'undefined') {
skip = parseInt(u.query.skip);
if (skip + '' === 'NaN') {
return respond(req, res, 'Not a number: ' + u.query.skip + '\n');
}
}
if (typeof u.query.count !== 'undefined') {
count = parseInt(u.query.count);
if (count + '' === 'NaN') {
return respond(req, res, 'Not a number: ' + u.query.count + '\n');
}
}
if (!exists)
return error(req, res, 'No such repository ' + repo.name + '\n', 404);
gitCommits(dir, count, function(err, commits) {
if (err)
return error(req, res, err);
respond(req, res, commits);
}, skip)
});
}
function list(req, res) {
// List repositories, with commit info
if (req.method.toUpperCase() === 'HEAD') {
res.writeHead(200, DEFAULT_HEADERS);
return res.end();
}
function isListable(dir, relpath) {
var list = config[config.listfilter];
if (/blacklist/.test(config.listfilter)) {
return list && list.length > 0 ?
list.indexOf(dir) < 0 && list.indexOf(relpath) < 0 : true;
}
return list && list.length > 0 ?
list.indexOf(dir) >= 0 || list.indexOf(relpath) >= 0 : false;
}
function sortrepos(a, b) {
return a.name <= b.name ? -1 : 1;
}
function findrepos(dir, onDone) {
var repos = [];
fs.readdir(dir, function(err, files) {
if (err)
return onDone(err);
if (files.length == 0)
return onDone(null, repos);
function setImmediate(callback) {
process.nextTick(callback);
}
function processFile() {
if (files.length == 0)
return onDone(null, repos);
var file = files.pop();
var relativepath =
(dir.replace(config.gitdir, '') + '/' + file).replace(/^\//, '');
if (isListable(file, relativepath)) {
var fullpath = path.join(dir, file);
fs.stat(fullpath, function(err, stat) {
if (gitpattern.test(file)) {
repos.push(deepRepoInst.object(fullpath));
setImmediate(processFile);
} else if (stat && stat.isDirectory()) {
findrepos(fullpath, function(err, res) {
repos = repos.concat(res);
setImmediate(processFile);
});
}
});
} else {
setImmediate(processFile);
}
}
setImmediate(processFile);
});
}
// List all subdirs of the git dir
findrepos(config.gitdir, function(err, data) {
if (err)
return error(req, res);
if (data.length === 0) {
return respond(req, res, []);
}
// sort data in alphabetically ascendant order
data.sort(sortrepos);
// clone the data
var moreData = copy(data);
var handled = 0;
function loadDescription() {
// Called iteratively - get the current item
var item = moreData.pop();
var descriptionFile = item ? path.join(item.location, 'description') : '';
function done() {
if (++handled >= data.length) {
respond(req, res, data);
} else {
process.nextTick(loadDescription);
}
}
function almostDone() {
// get the most recent commit for this repo
gitCommits(item.location, 1, function(err, commit) {
if (commit) {
item.lastCommit = commit[0];
} else if (err) {
console.log(err);
}
done();
});
}
// load the description
fs.exists(descriptionFile, function(exists) {
if (!exists) {
almostDone();
} else {
fs.readFile(descriptionFile, {encoding: 'utf8'}, function(err, desc) {
if (desc) {
for (var i = 0; i < data.length; i++) {
if (data[i].name === item.name) {
data[i].description = desc;
break;
}
}
}
almostDone();
});
}
});
}
loadDescription();
});
}