]>
Lady’s Gitweb - Gitweb/blob - gitweb.js
1 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
2 // 2007, Petr Baudis <pasky@suse.cz>
3 // 2008-2009, Jakub Narebski <jnareb@gmail.com>
6 * @fileOverview JavaScript code for gitweb (git web interface).
7 * @license GPLv2 or later
11 * This code uses DOM methods instead of (nonstandard) innerHTML
14 * innerHTML is non-standard IE extension, though supported by most
15 * browsers; however Firefox up to version 1.5 didn't implement it in
16 * a strict mode (application/xml+xhtml mimetype).
18 * Also my simple benchmarks show that using elem.firstChild.data =
19 * 'content' is slightly faster than elem.innerHTML = 'content'. It
20 * is however more fragile (text element fragment must exists), and
21 * less feature-rich (we cannot add HTML).
23 * Note that DOM 2 HTML is preferred over generic DOM 2 Core; the
24 * equivalent using DOM 2 Core is usually shown in comments.
28 /* ============================================================ */
29 /* generic utility functions */
33 * pad number N with nonbreakable spaces on the left, to WIDTH characters
34 * example: padLeftStr(12, 3, ' ') == ' 12'
35 * (' ' is nonbreakable space)
37 * @param {Number|String} input: number to pad
38 * @param {Number} width: visible width of output
39 * @param {String} str: string to prefix to string, e.g. ' '
40 * @returns {String} INPUT prefixed with (WIDTH - INPUT.length) x STR
42 function padLeftStr(input
, width
, str
) {
45 width
-= input
.toString().length
;
50 return prefix
+ input
;
54 * Pad INPUT on the left to SIZE width, using given padding character CH,
55 * for example padLeft('a', 3, '_') is '__a'.
57 * @param {String} input: input value converted to string.
58 * @param {Number} width: desired length of output.
59 * @param {String} ch: single character to prefix to string.
61 * @returns {String} Modified string, at least SIZE length.
63 function padLeft(input
, width
, ch
) {
65 while (s
.length
< width
) {
72 * Create XMLHttpRequest object in cross-browser way
73 * @returns XMLHttpRequest object, or null
75 function createRequestObject() {
77 return new XMLHttpRequest();
80 return window
.createRequest();
83 return new ActiveXObject("Msxml2.XMLHTTP");
86 return new ActiveXObject("Microsoft.XMLHTTP");
92 /* ============================================================ */
93 /* utility/helper functions (and variables) */
95 var xhr
; // XMLHttpRequest object
96 var projectUrl
; // partial query + separator ('?' or ';')
98 // 'commits' is an associative map. It maps SHA1s to Commit objects.
102 * constructor for Commit objects, used in 'blame'
103 * @class Represents a blamed commit
104 * @param {String} sha1: SHA-1 identifier of a commit
106 function Commit(sha1
) {
107 if (this instanceof Commit
) {
109 this.nprevious
= 0; /* number of 'previous', effective parents */
111 return new Commit(sha1
);
115 /* ............................................................ */
116 /* progress info, timing, error reporting */
119 var totalLines
= '???';
120 var div_progress_bar
;
121 var div_progress_info
;
124 * Detects how many lines does a blamed file have,
125 * This information is used in progress info
127 * @returns {Number|String} Number of lines in file, or string '...'
129 function countLines() {
131 document
.getElementById('blame_table') ||
132 document
.getElementsByTagName('table')[0];
135 return table
.getElementsByTagName('tr').length
- 1; // for header
142 * update progress info and length (width) of progress bar
144 * @globals div_progress_info, div_progress_bar, blamedLines, totalLines
146 function updateProgressInfo() {
147 if (!div_progress_info
) {
148 div_progress_info
= document
.getElementById('progress_info');
150 if (!div_progress_bar
) {
151 div_progress_bar
= document
.getElementById('progress_bar');
153 if (!div_progress_info
&& !div_progress_bar
) {
157 var percentage
= Math
.floor(100.0*blamedLines
/totalLines
);
159 if (div_progress_info
) {
160 div_progress_info
.firstChild
.data
= blamedLines
+ ' / ' + totalLines
+
161 ' (' + padLeftStr(percentage
, 3, ' ') + '%)';
164 if (div_progress_bar
) {
165 //div_progress_bar.setAttribute('style', 'width: '+percentage+'%;');
166 div_progress_bar
.style
.width
= percentage
+ '%';
171 var t_interval_server
= '';
172 var cmds_server
= '';
176 * write how much it took to generate data, and to run script
178 * @globals t0, t_interval_server, cmds_server
180 function writeTimeInterval() {
181 var info_time
= document
.getElementById('generating_time');
182 if (!info_time
|| !t_interval_server
) {
186 info_time
.firstChild
.data
+= ' + (' +
187 t_interval_server
+ ' sec server blame_data / ' +
188 (t1
.getTime() - t0
.getTime())/1000 + ' sec client JavaScript)';
190 var info_cmds
= document
.getElementById('generating_cmd');
191 if (!info_time
|| !cmds_server
) {
194 info_cmds
.firstChild
.data
+= ' + ' + cmds_server
;
198 * show an error message alert to user within page (in prohress info area)
199 * @param {String} str: plain text error message (no HTML)
201 * @globals div_progress_info
203 function errorInfo(str
) {
204 if (!div_progress_info
) {
205 div_progress_info
= document
.getElementById('progress_info');
207 if (div_progress_info
) {
208 div_progress_info
.className
= 'error';
209 div_progress_info
.firstChild
.data
= str
;
213 /* ............................................................ */
214 /* coloring rows like 'blame' after 'blame_data' finishes */
217 * returns true if given row element (tr) is first in commit group
218 * to be used only after 'blame_data' finishes (after processing)
220 * @param {HTMLElement} tr: table row
221 * @returns {Boolean} true if TR is first in commit group
223 function isStartOfGroup(tr
) {
224 return tr
.firstChild
.className
=== 'sha1';
227 var colorRe
= /(?:light|dark)/;
230 * change colors to use zebra coloring (2 colors) instead of 3 colors
231 * concatenate neighbour commit groups belonging to the same commit
235 function fixColorsAndGroups() {
236 var colorClasses
= ['light', 'dark'];
241 document
.getElementById('blame_table') ||
242 document
.getElementsByTagName('table')[0];
244 while ((tr
= document
.getElementById('l'+linenum
))) {
245 // index origin is 0, which is table header; start from 1
246 //while ((tr = table.rows[linenum])) { // <- it is slower
247 if (isStartOfGroup(tr
, linenum
, document
)) {
249 prev_group
.firstChild
.firstChild
.href
===
250 tr
.firstChild
.firstChild
.href
) {
251 // we have to concatenate groups
252 var prev_rows
= prev_group
.firstChild
.rowSpan
|| 1;
253 var curr_rows
= tr
.firstChild
.rowSpan
|| 1;
254 prev_group
.firstChild
.rowSpan
= prev_rows
+ curr_rows
;
255 //tr.removeChild(tr.firstChild);
256 tr
.deleteCell(0); // DOM2 HTML way
258 colorClass
= (colorClass
+ 1) % 2;
262 var tr_class
= tr
.className
;
263 tr
.className
= tr_class
.replace(colorRe
, colorClasses
[colorClass
]);
268 /* ............................................................ */
272 * used to extract hours and minutes from timezone info, e.g '-0900'
275 var tzRe
= /^([+-][0-9][0-9])([0-9][0-9])$/;
278 * return date in local time formatted in iso-8601 like format
279 * 'yyyy-mm-dd HH:MM:SS +/-ZZZZ' e.g. '2005-08-07 21:49:46 +0200'
281 * @param {Number} epoch: seconds since '00:00:00 1970-01-01 UTC'
282 * @param {String} timezoneInfo: numeric timezone '(+|-)HHMM'
283 * @returns {String} date in local time in iso-8601 like format
287 function formatDateISOLocal(epoch
, timezoneInfo
) {
288 var match
= tzRe
.exec(timezoneInfo
);
289 // date corrected by timezone
290 var localDate
= new Date(1000 * (epoch
+
291 (parseInt(match
[1],10)*3600 + parseInt(match
[2],10)*60)));
292 var localDateStr
= // e.g. '2005-08-07'
293 localDate
.getUTCFullYear() + '-' +
294 padLeft(localDate
.getUTCMonth()+1, 2, '0') + '-' +
295 padLeft(localDate
.getUTCDate(), 2, '0');
296 var localTimeStr
= // e.g. '21:49:46'
297 padLeft(localDate
.getUTCHours(), 2, '0') + ':' +
298 padLeft(localDate
.getUTCMinutes(), 2, '0') + ':' +
299 padLeft(localDate
.getUTCSeconds(), 2, '0');
301 return localDateStr
+ ' ' + localTimeStr
+ ' ' + timezoneInfo
;
304 /* ............................................................ */
305 /* unquoting/unescaping filenames */
310 var escCodeRe
= /\\([^0-7]|[0-7]{1,3})/g;
311 var octEscRe
= /^[0-7]{1,3}$/;
312 var maybeQuotedRe
= /^\"(.*)\"$/;
316 * unquote maybe git-quoted filename
317 * e.g. 'aa' -> 'aa', '"a\ta"' -> 'a a'
319 * @param {String} str: git-quoted string
320 * @returns {String} Unquoted and unescaped string
322 * @globals escCodeRe, octEscRe, maybeQuotedRe
324 function unquote(str
) {
327 // character escape codes, aka escape sequences (from C)
328 // replacements are to some extent JavaScript specific
329 t: "\t", // tab (HT, TAB)
330 n: "\n", // newline (NL)
331 r: "\r", // return (CR)
332 f: "\f", // form feed (FF)
333 b: "\b", // backspace (BS)
334 a: "\x07", // alarm (bell) (BEL)
335 e: "\x1B", // escape (ESC)
336 v: "\v" // vertical tab (VT)
339 if (seq
.search(octEscRe
) !== -1) {
340 // octal char sequence
341 return String
.fromCharCode(parseInt(seq
, 8));
342 } else if (seq
in es
) {
343 // C escape sequence, aka character escape code
346 // quoted ordinary character
350 var match
= str
.match(maybeQuotedRe
);
353 // perhaps str = eval('"'+str+'"'); would be enough?
354 str
= str
.replace(escCodeRe
,
355 function (substr
, p1
, offset
, s
) { return unq(p1
); });
360 /* ============================================================ */
361 /* main part: parsing response */
364 * Function called for each blame entry, as soon as it finishes.
365 * It updates page via DOM manipulation, adding sha1 info, etc.
367 * @param {Commit} commit: blamed commit
368 * @param {Object} group: object representing group of lines,
369 * which blame the same commit (blame entry)
371 * @globals blamedLines
373 function handleLine(commit
, group
) {
375 This is the structure of the HTML fragment we are working
378 <tr id="l123" class="">
379 <td class="sha1" title=""><a href=""> </a></td>
380 <td class="linenr"><a class="linenr" href="">123</a></td>
381 <td class="pre"># times (my ext3 doesn't).</td>
385 var resline
= group
.resline
;
387 // format date and time string only once per commit
389 /* e.g. 'Kay Sievers, 2005-08-07 21:49:46 +0200' */
390 commit
.info
= commit
.author
+ ', ' +
391 formatDateISOLocal(commit
.authorTime
, commit
.authorTimezone
);
394 // loop over lines in commit group
395 for (var i
= 0; i
< group
.numlines
; i
++, resline
++) {
396 var tr
= document
.getElementById('l'+resline
);
401 <tr id="l123" class="">
402 <td class="sha1" title=""><a href=""> </a></td>
403 <td class="linenr"><a class="linenr" href="">123</a></td>
404 <td class="pre"># times (my ext3 doesn't).</td>
407 var td_sha1
= tr
.firstChild
;
408 var a_sha1
= td_sha1
.firstChild
;
409 var a_linenr
= td_sha1
.nextSibling
.firstChild
;
411 /* <tr id="l123" class=""> */
412 var tr_class
= 'light'; // or tr.className
413 if (commit
.boundary
) {
414 tr_class
+= ' boundary';
416 if (commit
.nprevious
=== 0) {
417 tr_class
+= ' no-previous';
418 } else if (commit
.nprevious
> 1) {
419 tr_class
+= ' multiple-previous';
421 tr
.className
= tr_class
;
423 /* <td class="sha1" title="?" rowspan="?"><a href="?">?</a></td> */
425 td_sha1
.title
= commit
.info
;
426 td_sha1
.rowSpan
= group
.numlines
;
428 a_sha1
.href
= projectUrl
+ 'a=commit;h=' + commit
.sha1
;
429 a_sha1
.firstChild
.data
= commit
.sha1
.substr(0, 8);
430 if (group
.numlines
>= 2) {
431 var fragment
= document
.createDocumentFragment();
432 var br
= document
.createElement("br");
433 var text
= document
.createTextNode(
434 commit
.author
.match(/\b([A-Z])\B/g).join(''));
436 var elem
= fragment
|| td_sha1
;
437 elem
.appendChild(br
);
438 elem
.appendChild(text
);
440 td_sha1
.appendChild(fragment
);
445 //tr.removeChild(td_sha1); // DOM2 Core way
446 tr
.deleteCell(0); // DOM2 HTML way
449 /* <td class="linenr"><a class="linenr" href="?">123</a></td> */
451 ('previous' in commit
? commit
.previous : commit
.sha1
);
452 var linenr_filename
=
453 ('file_parent' in commit
? commit
.file_parent : commit
.filename
);
454 a_linenr
.href
= projectUrl
+ 'a=blame_incremental' +
455 ';hb=' + linenr_commit
+
456 ';f=' + encodeURIComponent(linenr_filename
) +
457 '#l' + (group
.srcline
+ i
);
461 //updateProgressInfo();
465 // ----------------------------------------------------------------------
467 var inProgress
= false; // are we processing response
472 var sha1Re
= /^([0-9a
-f
]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/;
473 var infoRe
= /^([a
-z
-]+) ?(.*)/;
474 var endRe
= /^END
?([^ ]*) ?(.*)/;
477 var curCommit
= new Commit();
480 var pollTimer
= null;
483 * Parse output from 'git blame --incremental [...]', received via
484 * XMLHttpRequest from server (blamedataUrl), and call handleLine
485 * (which updates page) as soon as blame entry is completed.
487 * @param {String[]} lines: new complete lines from blamedata server
489 * @globals commits, curCommit, curGroup, t_interval_server, cmds_server
490 * @globals sha1Re, infoRe, endRe
492 function processBlameLines(lines
) {
495 for (var i
= 0, len
= lines
.length
; i
< len
; i
++) {
497 if ((match
= sha1Re
.exec(lines
[i
]))) {
499 var srcline
= parseInt(match
[2], 10);
500 var resline
= parseInt(match
[3], 10);
501 var numlines
= parseInt(match
[4], 10);
503 var c
= commits
[sha1
];
505 c
= new Commit(sha1
);
510 curGroup
.srcline
= srcline
;
511 curGroup
.resline
= resline
;
512 curGroup
.numlines
= numlines
;
514 } else if ((match
= infoRe
.exec(lines
[i
]))) {
519 curCommit
.filename
= unquote(data
);
520 // 'filename' information terminates the entry
521 handleLine(curCommit
, curGroup
);
522 updateProgressInfo();
525 curCommit
.author
= data
;
528 curCommit
.authorTime
= parseInt(data
, 10);
531 curCommit
.authorTimezone
= data
;
534 curCommit
.nprevious
++;
535 // store only first 'previous' header
536 if (!'previous' in curCommit
) {
537 var parts
= data
.split(' ', 2);
538 curCommit
.previous
= parts
[0];
539 curCommit
.file_parent
= unquote(parts
[1]);
543 curCommit
.boundary
= true;
547 } else if ((match
= endRe
.exec(lines
[i
]))) {
548 t_interval_server
= match
[1];
549 cmds_server
= match
[2];
551 } else if (lines
[i
] !== '') {
560 * Process new data and return pointer to end of processed part
562 * @param {String} unprocessed: new data (from nextReadPos)
563 * @param {Number} nextReadPos: end of last processed data
564 * @return {Number} end of processed data (new value for nextReadPos)
566 function processData(unprocessed
, nextReadPos
) {
567 var lastLineEnd
= unprocessed
.lastIndexOf('\n');
568 if (lastLineEnd
!== -1) {
569 var lines
= unprocessed
.substring(0, lastLineEnd
).split('\n');
570 nextReadPos
+= lastLineEnd
+ 1 /* 1 == '\n'.length */;
572 processBlameLines(lines
);
579 * Handle XMLHttpRequest errors
581 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
583 * @globals pollTimer, commits, inProgress
585 function handleError(xhr
) {
586 errorInfo('Server error: ' +
587 xhr
.status
+ ' - ' + (xhr
.statusText
|| 'Error contacting server'));
589 clearInterval(pollTimer
);
590 commits
= {}; // free memory
596 * Called after XMLHttpRequest finishes (loads)
598 * @param {XMLHttpRequest} xhr: XMLHttpRequest object (unused)
600 * @globals pollTimer, commits, inProgress
602 function responseLoaded(xhr
) {
603 clearInterval(pollTimer
);
605 fixColorsAndGroups();
607 commits
= {}; // free memory
613 * handler for XMLHttpRequest onreadystatechange event
616 * @globals xhr, inProgress
618 function handleResponse() {
623 * Value Constant (W3C) Description
624 * -------------------------------------------------------------------
625 * 0 UNSENT open() has not been called yet.
626 * 1 OPENED send() has not been called yet.
627 * 2 HEADERS_RECEIVED send() has been called, and headers
628 * and status are available.
629 * 3 LOADING Downloading; responseText holds partial data.
630 * 4 DONE The operation is complete.
633 if (xhr
.readyState
!== 4 && xhr
.readyState
!== 3) {
637 // the server returned error
638 if (xhr
.readyState
=== 3 && xhr
.status
!== 200) {
641 if (xhr
.readyState
=== 4 && xhr
.status
!== 200) {
646 // In konqueror xhr.responseText is sometimes null here...
647 if (xhr
.responseText
=== null) {
651 // in case we were called before finished processing
658 // extract new whole (complete) lines, and process them
659 while (xhr
.prevDataLength
!== xhr
.responseText
.length
) {
660 if (xhr
.readyState
=== 4 &&
661 xhr
.prevDataLength
=== xhr
.responseText
.length
) {
665 xhr
.prevDataLength
= xhr
.responseText
.length
;
666 var unprocessed
= xhr
.responseText
.substring(xhr
.nextReadPos
);
667 xhr
.nextReadPos
= processData(unprocessed
, xhr
.nextReadPos
);
670 // did we finish work?
671 if (xhr
.readyState
=== 4 &&
672 xhr
.prevDataLength
=== xhr
.responseText
.length
) {
679 // ============================================================
680 // ------------------------------------------------------------
683 * Incrementally update line data in blame_incremental view in gitweb.
685 * @param {String} blamedataUrl: URL to server script generating blame data.
686 * @param {String} bUrl: partial URL to project, used to generate links.
688 * Called from 'blame_incremental' view after loading table with
689 * file contents, a base for blame view.
691 * @globals xhr, t0, projectUrl, div_progress_bar, totalLines, pollTimer
693 function startBlame(blamedataUrl
, bUrl
) {
695 xhr
= createRequestObject();
697 errorInfo('ERROR: XMLHttpRequest not supported');
702 projectUrl
= bUrl
+ (bUrl
.indexOf('?') === -1 ? '?' : ';');
703 if ((div_progress_bar
= document
.getElementById('progress_bar'))) {
704 //div_progress_bar.setAttribute('style', 'width: 100%;');
705 div_progress_bar
.style
.cssText
= 'width: 100%;';
707 totalLines
= countLines();
708 updateProgressInfo();
710 /* add extra properties to xhr object to help processing response */
711 xhr
.prevDataLength
= -1; // used to detect if we have new data
712 xhr
.nextReadPos
= 0; // where unread part of response starts
714 xhr
.onreadystatechange
= handleResponse
;
715 //xhr.onreadystatechange = function () { handleResponse(xhr); };
717 xhr
.open('GET', blamedataUrl
);
718 xhr
.setRequestHeader('Accept', 'text/plain');
721 // not all browsers call onreadystatechange event on each server flush
722 // poll response using timer every second to handle this issue
723 pollTimer
= setInterval(xhr
.onreadystatechange
, 1000);
This page took 0.962487 seconds and 5 git commands to generate.