2 /** FusionForge Darcs plugin
4 * Copyright 2009, Roland Mas
6 * This file is part of FusionForge.
8 * FusionForge is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published
10 * by the Free Software Foundation; either version 2 of the License,
11 * or (at your option) any later version.
13 * FusionForge is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 forge_define_config_item ('default_server', 'scmdarcs', forge_get_config ('web_host')) ;
24 forge_define_config_item ('repos_path', 'scmdarcs', forge_get_config('chroot').'/scmrepos/darcs') ;
26 class DarcsPlugin extends SCMPlugin {
27 function DarcsPlugin () {
30 $this->name = 'scmdarcs';
31 $this->text = 'Darcs';
32 $this->hooks[] = 'scm_generate_snapshots' ;
33 $this->hooks[] = 'scm_update_repolist' ;
34 $this->hooks[] = 'scm_browser_page' ;
35 $this->hooks[] = 'scm_gather_stats' ;
40 function getDefaultServer() {
41 return forge_get_config('default_server', 'scmdarcs') ;
44 function getRootRepositories ($project) {
45 return (forge_get_config('repos_path', 'scmdarcs') . '/' . $project->getUnixName());
48 function getRepositories ($project) {
50 $toprepo = $this->getRootRepositories($project);
53 foreach (scandir($toprepo) as $repo_name)
55 $repo = $toprepo . '/' . $repo_name;
56 if (is_dir($repo) && is_dir($repo . '/_darcs'))
65 function printShortStats ($params) {
66 $project = $this->checkParams ($params) ;
71 if ($project->usesPlugin($this->name)) {
72 $result = db_query_params('SELECT sum(commits) AS commits, sum(adds) AS adds FROM stats_cvs_group WHERE group_id=$1',
73 array ($project->getID())) ;
74 $commit_num = db_result($result,0,'commits');
75 $add_num = db_result($result,0,'adds');
82 echo ' (Darcs: '.sprintf(_('<strong>%1$s</strong> commits, <strong>%2$s</strong> adds'), number_format($commit_num, 0), number_format($add_num, 0)).")";
86 function getBlurb () {
87 return '<p>' . _('Documentation for Darcs is available <a href="http://darcs.net/">here</a>.') . '</p>';
90 function getInstructionForDarcs ($project, $rw) {
91 $repo_names = $this->getRepositories($project);
92 if (count($repo_names) > 0)
94 $default_repo = "REPO";
95 if (count($repo_names) == 1)
97 $default_repo = $repo_names[0];
101 $url = $this->getBoxForProject($project) . ':'. $this->getRootRepositories($project) . '/' . $default_repo;
105 $url = util_make_url ('/anonscm/darcs/'.$project->getUnixName().'/' . $default_repo);
107 $b = '<p><tt>darcs get ' . $url . '</tt></p>';
108 if (count($repo_names) > 1)
110 $b .= _('<p>where REPO can be: ') . implode(_(', '), $repo_names) . '</p>';
113 else if (is_dir($this->getRootRepositories($project)))
115 $b = _('<p><em>No repositories defined.</em></p>');
119 $b = _('<p><em>Repository not yet created, wait an hour.</em></p>');
124 function getInstructionsForAnon ($project) {
126 $b .= _('Anonymous Darcs Access');
129 $b .= _('This project\'s Darcs repository can be checked out through anonymous access with the following command.');
131 $b .= $this->getInstructionForDarcs($project, false);
136 function getInstructionsForRW ($project) {
138 $b .= _('Developer Darcs Access via SSH');
141 $b .= ('Only project developers can access the Darcs tree via this method. SSH must be installed on your client machine. Substitute <i>developername</i> with the proper values. Enter your site password when prompted.');
143 $b .= $this->getInstructionForDarcs($project, true);
147 function getSnapshotPara ($project) {
150 $filename = $project->getUnixName().'-scm-latest.tar'.util_get_compressed_file_extension();
151 if (file_exists(forge_get_config('scm_snapshots_path').'/'.$filename)) {
153 $b .= util_make_link ("/snapshots.php?group_id=".$project->getID(),
154 _('Download the nightly snapshot')
161 function getBrowserLinkBlock ($project) {
163 $b = $HTML->boxMiddle(_('Darcs Repository Browser'));
165 $b .= _('Browsing the Darcs tree gives you a view into the current status of this project\'s code. You may also view the complete histories of any file in the repository.');
167 $repo_names = $this->getRepositories($project);
168 if (count($repo_names) > 0)
170 foreach ($repo_names as $repo_name)
173 $b .= util_make_link ("/scm/browser.php?group_id=".$project->getID()."&repo_name=".$repo_name,
174 _('Browse Darcs Repository '. $repo_name));
180 $b .= _('<p>No repositories to browse</p>');
185 function getStatsBlock ($project) {
189 $result = db_query_params('SELECT u.realname, u.user_name, u.user_id, sum(commits) as commits, sum(adds) as adds, sum(adds+commits) as combined FROM stats_cvs_user s, users u WHERE group_id=$1 AND s.user_id=u.user_id AND (commits>0 OR adds >0) GROUP BY u.user_id, realname, user_name, u.user_id ORDER BY combined DESC, realname',
190 array ($project->getID()));
192 if (db_numrows($result) > 0) {
193 $b .= $HTML->boxMiddle(_('Repository Statistics'));
195 $tableHeaders = array(
200 $b .= $HTML->listTableTop($tableHeaders);
203 $total = array('adds' => 0, 'commits' => 0);
205 while($data = db_fetch_array($result)) {
206 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
207 $b .= '<td width="50%">' ;
208 $b .= util_make_link_u ($data['user_name'], $data['user_id'], $data['realname']) ;
209 $b .= '</td><td width="25%" align="right">'.$data['adds']. '</td>'.
210 '<td width="25%" align="right">'.$data['commits'].'</td></tr>';
211 $total['adds'] += $data['adds'];
212 $total['commits'] += $data['commits'];
215 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
216 $b .= '<td width="50%"><strong>'._('Total').':</strong></td>'.
217 '<td width="25%" align="right"><strong>'.$total['adds']. '</strong></td>'.
218 '<td width="25%" align="right"><strong>'.$total['commits'].'</strong></td>';
220 $b .= $HTML->listTableBottom();
226 function printBrowserPage ($params) {
229 $project = $this->checkParams ($params) ;
234 if ($project->usesPlugin ($this->name)) {
235 if ($this->browserDisplayable ($project)) {
236 print '<iframe src="'.
237 util_make_url ("/plugins/scmdarcs/cgi-bin/darcsweb.cgi?r=".
238 $project->getUnixName()). '/' . $params['repo_name'] .
239 '" frameborder="0" width=100% height=700></iframe>' ;
244 function createOrUpdateRepo ($params) {
245 $project = $this->checkParams ($params) ;
250 if (! $project->usesPlugin ($this->name)) {
254 $toprepo = $this->getRootRepositories($project);
255 $unix_group = 'scm_' . $project->getUnixName() ;
257 system("chmod g+ws $toprepo");
259 $result = db_query_params(
260 "SELECT repo_name, clone_repo_name FROM plugin_scmdarcs_create_repos WHERE group_id=$1",
261 array($project->getID()));
264 echo "Error while retrieving darcs repository to create\n";
268 while ($res = db_fetch_array($result))
270 $repo = $toprepo . '/' . $res['repo_name'];
272 if ($res['clone_repo_name'] != '')
274 $clone_repo = $toprepo . '/' . $res['clone_repo_name'];
276 if (!is_dir ($repo."/_darcs")) {
277 system ("mkdir -p '$repo'") ;
278 system ("cd $repo ; darcs init >/dev/null") ;
281 system ("darcs fetch '$clone_repo'") ;
283 system ("find $repo -type d | xargs chmod g+s") ;
285 $result1 = db_query_params(
286 "DELETE FROM plugin_scmdarcs_create_repos WHERE group_id=$1 AND repo_name=$2",
287 array($project->getID(), $res['repo_name']));
290 echo "Cannot remove scheduling of darcs repository creation ".$res['repo_name']."\n";
296 foreach ($this->getRepositories($project) as $repo_name)
298 $repo = $toprepo . '/' . $repo_name ;
300 system ("chgrp -R $unix_group $repo") ;
301 if ($project->enableAnonSCM()) {
302 system ("chmod -R g+wX,o+rX-w $repo") ;
304 system ("chmod -R g+wX,o-rwx $repo") ;
309 function darcswebRepository ($project, $repo_name, $repo_url, $repo_dir) {
310 $classname = preg_replace ('/\W/', '_', 'repo_' . $repo_name) ;
311 return ("class $classname:\n"
312 ."\trepodir = '$repo_dir'\n"
313 ."\treponame = '$repo_name'\n"
314 ."\t".'repodesc = """Repository ' . $repo_name . ' of '.$project->getPublicName().'"""'."\n"
315 ."\trepourl = '" . util_make_url ('/anonscm/darcs/' . $repo_url) . "'\n"
316 ."\trepoprojurl = '" . util_make_url ('/projects/' . $repo_url) . "'\n"
317 ."\trepoencoding = 'utf8'\n"
322 function updateRepositoryList ($params) {
323 $groups = $this->getGroups () ;
325 foreach ($groups as $project) {
326 if ($this->browserDisplayable ($project)) {
331 $fname = '/etc/gforge/plugins/scmdarcs/config.py' ;
333 $f = fopen ($fname.'.new', 'w') ;
335 fwrite ($f, "class base:\n"
336 ."\tdarcslogo = '".util_make_url ('/plugins/scmdarcs/darcsweb/darcs.png')."'\n"
337 ."\tdarcsfav = '".util_make_url ('/plugins/scmdarcs/darcsweb/minidarcs.png')."'\n"
338 ."\tcssfile = '".util_make_url ('/plugins/scmdarcs/darcsweb/style.css')."'\n"
341 foreach ($list as $project) {
342 $unix_name = $project->getUnixName();
343 $toprepo = $this->getRootRepositories($project);
344 $repo_names = $this->getRepositories($project);
345 foreach ($repo_names as $repo_name) {
346 if ($repo_name == $unix_name)
348 # Default repository name, we create a default entry for it
350 $this->darcswebRepository($project,
352 "$unix_name/$repo_name",
353 "$toprepo/$repo_name"));
356 $this->darcswebRepository($project,
357 "$unix_name/$repo_name",
358 "$unix_name/$repo_name",
359 "$toprepo/$repo_name"));
363 chmod ($fname.'.new', 0644) ;
364 rename ($fname.'.new', $fname) ;
367 function generateSnapshots ($params) {
370 $project = $this->checkParams ($params) ;
375 $group_name = $project->getUnixName() ;
377 $tarball = forge_get_config('scm_tarballs_path').'/'.$group_name.'-scmroot.tar'.util_get_compressed_file_extension();
379 if (! $project->usesPlugin ($this->name)) {
383 if (! $project->enableAnonSCM()) {
389 $toprepo = forge_get_config('repos_path', 'scmdarcs') ;
390 $repo = $this->getRootRepositories($project);
392 if (!is_dir ($repo)) {
397 $tmp = trim (`mktemp -d`) ;
401 $today = date ('Y-m-d') ;
402 $dir = $project->getUnixName ()."-$today" ;
403 system ("mkdir -p $tmp/$dir") ;
404 system ("cd $tmp ; darcs $repo $dir > /dev/null 2>&1") ;
405 system ("tar cCf $tmp - $dir |".forge_get_config('compression_method')."> $tmp/snapshot") ;
406 chmod ("$tmp/snapshot", 0644) ;
407 copy ("$tmp/snapshot", $snapshot) ;
408 unlink ("$tmp/snapshot") ;
409 system ("rm -rf $tmp/$dir") ;
411 system ("tar cCf $toprepo - ".$project->getUnixName() ."|".forge_get_config('compression_method')."> $tmp/tarball") ;
412 chmod ("$tmp/tarball", 0644) ;
413 copy ("$tmp/tarball", $tarball) ;
414 unlink ("$tmp/tarball") ;
415 system ("rm -rf $tmp") ;
418 function gatherStats ($params) {
419 global $adds, $deletes, $updates, $commits,
420 $usr_adds, $usr_deletes, $usr_updates;
422 $project = $this->checkParams ($params) ;
427 if (! $project->usesPlugin ($this->name)) {
431 if ($params['mode'] == 'day') {
434 $year = $params ['year'] ;
435 $month = $params ['month'] ;
436 $day = $params ['day'] ;
437 $month_string = sprintf( "%04d%02d", $year, $month );
438 $start_time = gmmktime( 0, 0, 0, $month, $day, $year);
439 $end_time = $start_time + 86400;
444 $usr_adds = array () ;
445 $usr_updates = array () ;
446 $usr_deletes = array ();
448 $toprepo = $this->getRootRepositories($project) ;
449 $from_date = date("c", $start_time);
450 $to_date = date("c", $end_time);
452 // cleaning stats_cvs_* table for the current day
453 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE month=$1 AND day=$2 AND group_id=$3',
454 array ($month_string,
456 $project->getID())) ;
458 echo "Error while cleaning stats_cvs_group\n" ;
463 $res = db_query_params ('DELETE FROM stats_cvs_user WHERE month=$1 AND day=$2 AND group_id=$3',
464 array ($month_string,
466 $project->getID())) ;
468 echo "Error while cleaning stats_cvs_user\n" ;
473 foreach ($this->getRepositories($project) as $repo_name)
475 $repo = $toprepo . '/' . $repo_name;
476 if (!is_dir ($repo) || !is_dir ("$repo/_darcs")) {
477 echo "No repository $repo\n" ;
486 $pipe = popen("darcs changes --repodir='$repo' "
487 ."--match 'date \"between $from_date and $to_date\"' "
490 $xml_parser = xml_parser_create();
491 xml_set_element_handler($xml_parser, "DarcsPluginStartElement", "DarcsPluginEndElement");
493 // Analyzing history stream
494 while (!feof($pipe) &&
495 $data = fgets ($pipe, 4096)) {
497 if (!xml_parse ($xml_parser, $data, feof ($pipe))) {
498 debug("Unable to parse XML with error " .
499 xml_error_string(xml_get_error_code($xml_parser)) .
501 xml_get_current_line_number($xml_parser));
508 xml_parser_free ($xml_parser);
511 // inserting group results in stats_cvs_groups
513 if (!db_query_params ('INSERT INTO stats_cvs_group (month,day,group_id,checkouts,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
514 array ($month_string,
520 echo "Error while inserting into stats_cvs_group\n" ;
525 // build map for email -> login
527 $email_login = array();
528 $email_login_fn = $repo."/_darcs/email-login.txt";
529 if (!file_exists($email_login_fn))
531 $email_login_fn = $repo."/.email-login.txt";
533 if (!file_exists($email_login_fn))
535 unset($email_login_fn);
538 if (isset($email_login_fn))
540 $fh = fopen($email_login_fn, 'r');
543 $a = explode(" ", fgets($fh));
546 $email_login[$a[0]] = rtrim($a[1]);
552 // building the user list
553 $user_list = array_unique( array_merge( array_keys( $usr_adds ), array_keys( $usr_updates ) ) );
555 foreach ( $user_list as $user ) {
556 // trying to get user id from darcs user name
558 $tmp_email = explode("<", $id, 2);
559 if (isset($tmp_email[1]))
561 $tmp_email = explode(">", $tmp_email[1]);
564 if (isset($email_login[$id]))
566 $id = $email_login[$id];
569 $u = &user_get_object_by_name ($id) ;
571 $user_id = $u->getID();
576 if (!db_query_params ('INSERT INTO stats_cvs_user (month,day,group_id,user_id,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
577 array ($month_string,
581 $usr_updates[$user] ? $usr_updates[$user] : 0,
582 $usr_adds[$user] ? $usr_adds[$user] : 0))) {
583 echo "Error while inserting into stats_cvs_user\n" ;
593 function printAdminPage ($params) {
594 parent::printAdminPage($params);
596 $project = $this->checkParams($params);
602 if ($project->usesPlugin($this->name))
604 $result = db_query_params(
605 "SELECT repo_name FROM plugin_scmdarcs_create_repos WHERE group_id=$1",
606 array($project->getID()));
607 if ($result && db_numrows($result) > 0)
610 while ($res = db_fetch_array($result))
612 array_push($nm, $res['repo_name']);
614 print '<p><strong>'._('Repository to be created: ') . '</strong>' .
615 implode(_(', '), $nm) . '</p>';
618 print '<p><strong>Create new repository:</strong></p>';
619 print '<p>'._('Repository name: ').
620 '<input type="string" name="scm_create_repo_name" size=16 maxlength=128 /></p>';
621 print '<p>'._('Clone: ').
622 '<select name="scm_clone_repo_name">';
623 print '<option value=""><none></option>';
624 foreach ($this->getRepositories($project) as $repo_name)
626 print '<option value="'.$repo_name.'">'.$repo_name.'</option>';
628 print '</select></p>';
632 function adminUpdate ($params) {
633 parent::adminUpdate($params);
635 $project = $this->checkParams($params);
641 $new_repo_name = $params['scm_create_repo_name'];
642 $clone_repo_name = $params['scm_clone_repo_name'];
643 if ($new_repo_name != '')
645 $repo_names = $this->getRepositories($project);
646 if (in_array($new_repo_name, $repo_names))
648 html_error_top(_("Repository $new_repo_name already exists"));
652 if ($clone_repo_name != '' && !in_array($clone_repo_name, $repo_names))
654 html_error_top(_("Clone repository $clone_repo_name doesn't exist"));
657 if ($clone_repo_name == '<none>')
659 $clone_repo_name = '';
662 if (!preg_match('/^[\w][-_\w\d\.]+$/', $new_repo_name))
664 html_error_top("Invalid repository name $new_repo_name");
669 if (!db_query_params ('INSERT INTO plugin_scmdarcs_create_repos (group_id,repo_name,clone_repo_name)
671 array($project->getID(), $new_repo_name, $clone_repo_name)))
673 html_error_top("SQL error while scheduling new repository $new_repo_name");
679 html_feedback_top(_("Repository $new_repo_name schedule for creation"));
685 function DarcsPluginStartElement($parser, $name, $attrs) {
686 global $last_user, $commits,
687 $adds, $updates, $deletes,
688 $usr_adds, $usr_updates, $usr_deletes;
691 $last_user = $attrs['AUTHOR'];
692 if (!array_key_exists($last_user, $usr_deletes))
694 $usr_deletes[$last_user] = 0;
696 if (!array_key_exists($last_user, $usr_updates))
698 $usr_updates[$last_user] = 0;
700 if (!array_key_exists($last_user, $usr_adds))
702 $usr_adds[$last_user] = 0;
707 case "REMOVE_DIRECTORY":
710 $usr_deletes[$last_user]++;
717 $usr_updates[$last_user]++;
721 case "ADD_DIRECTORY":
724 $usr_adds[$last_user]++;
730 function DarcsPluginEndElement ($parser, $name) {
734 // c-file-style: "bsd"