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
19 * along with FusionForge; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24 forge_define_config_item ('default_server', 'scmdarcs', forge_get_config ('web_host')) ;
25 forge_define_config_item ('repos_path', 'scmdarcs', forge_get_config('chroot').'/scmrepos/darcs') ;
27 class DarcsPlugin extends SCMPlugin {
28 function DarcsPlugin () {
31 $this->name = 'scmdarcs';
32 $this->text = 'Darcs';
33 $this->hooks[] = 'scm_generate_snapshots' ;
34 $this->hooks[] = 'scm_update_repolist' ;
35 $this->hooks[] = 'scm_browser_page' ;
36 $this->hooks[] = 'scm_gather_stats' ;
41 function getDefaultServer() {
42 return forge_get_config('default_server', 'scmdarcs') ;
45 function getRootRepositories ($project) {
46 return (forge_get_config('repos_path', 'scmdarcs') . '/' . $project->getUnixName());
49 function getRepositories ($project) {
51 $toprepo = $this->getRootRepositories($project);
54 foreach (scandir($toprepo) as $repo_name)
56 $repo = $toprepo . '/' . $repo_name;
57 if (is_dir($repo) && is_dir($repo . '/_darcs'))
66 function printShortStats ($params) {
67 $project = $this->checkParams ($params) ;
72 if ($project->usesPlugin($this->name)) {
73 $result = db_query_params('SELECT sum(commits) AS commits, sum(adds) AS adds FROM stats_cvs_group WHERE group_id=$1',
74 array ($project->getID())) ;
75 $commit_num = db_result($result,0,'commits');
76 $add_num = db_result($result,0,'adds');
83 echo ' (Darcs: '.sprintf(_('<strong>%1$s</strong> commits, <strong>%2$s</strong> adds'), number_format($commit_num, 0), number_format($add_num, 0)).")";
87 function getBlurb () {
88 return '<p>' . _('Documentation for Darcs is available <a href="http://darcs.net/">here</a>.') . '</p>';
91 function getInstructionForDarcs ($project, $rw) {
92 $repo_names = $this->getRepositories($project);
93 if (count($repo_names) > 0)
95 $default_repo = "REPO";
96 if (count($repo_names) == 1)
98 $default_repo = $repo_names[0];
102 $url = $project->getSCMBox() . ':'. $this->getRootRepositories($project) . '/' . $default_repo;
106 $url = util_make_url ('/anonscm/darcs/'.$project->getUnixName().'/' . $default_repo);
108 $b = '<p><tt>darcs get ' . $url . '</tt></p>';
109 if (count($repo_names) > 1)
111 $b .= _('<p>where REPO can be: ') . implode(_(', '), $repo_names) . '</p>';
114 else if (is_dir($this->getRootRepositories($project)))
116 $b = _('<p><em>No repositories defined.</em></p>');
120 $b = _('<p><em>Repository not yet created, wait an hour.</em></p>');
125 function getInstructionsForAnon ($project) {
127 $b .= _('Anonymous Darcs Access');
130 $b .= _('This project\'s Darcs repository can be checked out through anonymous access with the following command.');
132 $b .= $this->getInstructionForDarcs($project, false);
137 function getInstructionsForRW ($project) {
139 $b .= _('Developer Darcs Access via SSH');
142 $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.');
144 $b .= $this->getInstructionForDarcs($project, true);
148 function getSnapshotPara ($project) {
151 $filename = $project->getUnixName().'-scm-latest.tar'.util_get_compressed_file_extension();
152 if (file_exists(forge_get_config('scm_snapshots_path').'/'.$filename)) {
154 $b .= util_make_link ("/snapshots.php?group_id=".$project->getID(),
155 _('Download the nightly snapshot')
162 function getBrowserLinkBlock ($project) {
164 $b = $HTML->boxMiddle(_('Darcs Repository Browser'));
166 $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.');
168 $repo_names = $this->getRepositories($project);
169 if (count($repo_names) > 0)
171 foreach ($repo_names as $repo_name)
174 $b .= util_make_link ("/scm/browser.php?group_id=".$project->getID()."&repo_name=".$repo_name,
175 _('Browse Darcs Repository '. $repo_name));
181 $b .= _('<p>No repositories to browse</p>');
186 function getStatsBlock ($project) {
190 $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',
191 array ($project->getID()));
193 if (db_numrows($result) > 0) {
194 $b .= $HTML->boxMiddle(_('Repository Statistics'));
196 $tableHeaders = array(
201 $b .= $HTML->listTableTop($tableHeaders);
204 $total = array('adds' => 0, 'commits' => 0);
206 while($data = db_fetch_array($result)) {
207 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
208 $b .= '<td width="50%">' ;
209 $b .= util_make_link_u ($data['user_name'], $data['user_id'], $data['realname']) ;
210 $b .= '</td><td width="25%" align="right">'.$data['adds']. '</td>'.
211 '<td width="25%" align="right">'.$data['commits'].'</td></tr>';
212 $total['adds'] += $data['adds'];
213 $total['commits'] += $data['commits'];
216 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
217 $b .= '<td width="50%"><strong>'._('Total').':</strong></td>'.
218 '<td width="25%" align="right"><strong>'.$total['adds']. '</strong></td>'.
219 '<td width="25%" align="right"><strong>'.$total['commits'].'</strong></td>';
221 $b .= $HTML->listTableBottom();
227 function printBrowserPage ($params) {
230 $project = $this->checkParams ($params) ;
235 if ($project->usesPlugin ($this->name)) {
236 if ($this->browserDisplayable ($project)) {
237 print '<iframe src="'.
238 util_make_url ("/plugins/scmdarcs/cgi-bin/darcsweb.cgi?r=".
239 $project->getUnixName()). '/' . $params['repo_name'] .
240 '" frameborder="0" width=100% height=700></iframe>' ;
245 function createOrUpdateRepo ($params) {
246 $project = $this->checkParams ($params) ;
251 if (! $project->usesPlugin ($this->name)) {
255 $toprepo = $this->getRootRepositories($project);
256 $unix_group = 'scm_' . $project->getUnixName() ;
258 system("chmod g+ws $toprepo");
260 $result = db_query_params(
261 "SELECT repo_name, clone_repo_name FROM plugin_scmdarcs_create_repos WHERE group_id=$1",
262 array($project->getID()));
265 echo "Error while retrieving darcs repository to create\n";
269 while ($res = db_fetch_array($result))
271 $repo = $toprepo . '/' . $res['repo_name'];
273 if ($res['clone_repo_name'] != '')
275 $clone_repo = $toprepo . '/' . $res['clone_repo_name'];
277 if (!is_dir ($repo."/_darcs")) {
278 system ("mkdir -p '$repo'") ;
279 system ("cd $repo ; darcs init >/dev/null") ;
282 system ("darcs fetch '$clone_repo'") ;
284 system ("find $repo -type d | xargs chmod g+s") ;
286 $result1 = db_query_params(
287 "DELETE FROM plugin_scmdarcs_create_repos WHERE group_id=$1 AND repo_name=$2",
288 array($project->getID(), $res['repo_name']));
291 echo "Cannot remove scheduling of darcs repository creation ".$res['repo_name']."\n";
297 foreach ($this->getRepositories($project) as $repo_name)
299 $repo = $toprepo . '/' . $repo_name ;
301 system ("chgrp -R $unix_group $repo") ;
302 if ($project->enableAnonSCM()) {
303 system ("chmod -R g+wX,o+rX-w $repo") ;
305 system ("chmod -R g+wX,o-rwx $repo") ;
310 function darcswebRepository ($project, $repo_name, $repo_url, $repo_dir) {
311 $classname = preg_replace ('/\W/', '_', 'repo_' . $repo_name) ;
312 return ("class $classname:\n"
313 ."\trepodir = '$repo_dir'\n"
314 ."\treponame = '$repo_name'\n"
315 ."\t".'repodesc = """Repository ' . $repo_name . ' of '.$project->getPublicName().'"""'."\n"
316 ."\trepourl = '" . util_make_url ('/anonscm/darcs/' . $repo_url) . "'\n"
317 ."\trepoprojurl = '" . util_make_url ('/projects/' . $repo_url) . "'\n"
318 ."\trepoencoding = 'utf8'\n"
323 function updateRepositoryList ($params) {
324 $groups = $this->getGroups () ;
326 foreach ($groups as $project) {
327 if ($this->browserDisplayable ($project)) {
332 $fname = '/etc/gforge/plugins/scmdarcs/config.py' ;
334 $f = fopen ($fname.'.new', 'w') ;
336 fwrite ($f, "class base:\n"
337 ."\tdarcslogo = '".util_make_url ('/plugins/scmdarcs/darcsweb/darcs.png')."'\n"
338 ."\tdarcsfav = '".util_make_url ('/plugins/scmdarcs/darcsweb/minidarcs.png')."'\n"
339 ."\tcssfile = '".util_make_url ('/plugins/scmdarcs/darcsweb/style.css')."'\n"
342 foreach ($list as $project) {
343 $unix_name = $project->getUnixName();
344 $toprepo = $this->getRootRepositories($project);
345 $repo_names = $this->getRepositories($project);
346 foreach ($repo_names as $repo_name) {
347 if ($repo_name == $unix_name)
349 # Default repository name, we create a default entry for it
351 $this->darcswebRepository($project,
353 "$unix_name/$repo_name",
354 "$toprepo/$repo_name"));
357 $this->darcswebRepository($project,
358 "$unix_name/$repo_name",
359 "$unix_name/$repo_name",
360 "$toprepo/$repo_name"));
364 chmod ($fname.'.new', 0644) ;
365 rename ($fname.'.new', $fname) ;
368 function generateSnapshots ($params) {
371 $project = $this->checkParams ($params) ;
376 $group_name = $project->getUnixName() ;
378 $tarball = forge_get_config('scm_tarballs_path').'/'.$group_name.'-scmroot.tar'.util_get_compressed_file_extension();
380 if (! $project->usesPlugin ($this->name)) {
384 if (! $project->enableAnonSCM()) {
390 $toprepo = forge_get_config('repos_path', 'scmdarcs') ;
391 $repo = $this->getRootRepositories($project);
393 if (!is_dir ($repo)) {
398 $tmp = trim (`mktemp -d`) ;
402 $today = date ('Y-m-d') ;
403 $dir = $project->getUnixName ()."-$today" ;
404 system ("mkdir -p $tmp/$dir") ;
405 system ("cd $tmp ; darcs $repo $dir > /dev/null 2>&1") ;
406 system ("tar cCf $tmp - $dir |".forge_get_config('compression_method')."> snapshot") ;
407 chmod ("$tmp/snapshot", 0644) ;
408 copy ("$tmp/snapshot", $snapshot) ;
409 unlink ("$tmp/snapshot") ;
410 system ("rm -rf $tmp/$dir") ;
412 system ("tar cCf $toprepo - ".$project->getUnixName() ."|".forge_get_config('compression_method')."> $tmp/tarball") ;
413 chmod ("$tmp/tarball", 0644) ;
414 copy ("$tmp/tarball", $tarball) ;
415 unlink ("$tmp/tarball") ;
416 system ("rm -rf $tmp") ;
419 function gatherStats ($params) {
420 global $adds, $deletes, $updates, $commits,
421 $usr_adds, $usr_deletes, $usr_updates;
423 $project = $this->checkParams ($params) ;
428 if (! $project->usesPlugin ($this->name)) {
432 if ($params['mode'] == 'day') {
435 $year = $params ['year'] ;
436 $month = $params ['month'] ;
437 $day = $params ['day'] ;
438 $month_string = sprintf( "%04d%02d", $year, $month );
439 $start_time = gmmktime( 0, 0, 0, $month, $day, $year);
440 $end_time = $start_time + 86400;
445 $usr_adds = array () ;
446 $usr_updates = array () ;
447 $usr_deletes = array ();
449 $toprepo = $this->getRootRepositories($project) ;
450 $from_date = date("c", $start_time);
451 $to_date = date("c", $end_time);
453 // cleaning stats_cvs_* table for the current day
454 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE month=$1 AND day=$2 AND group_id=$3',
455 array ($month_string,
457 $project->getID())) ;
459 echo "Error while cleaning stats_cvs_group\n" ;
464 $res = db_query_params ('DELETE FROM stats_cvs_user WHERE month=$1 AND day=$2 AND group_id=$3',
465 array ($month_string,
467 $project->getID())) ;
469 echo "Error while cleaning stats_cvs_user\n" ;
474 foreach ($this->getRepositories($project) as $repo_name)
476 $repo = $toprepo . '/' . $repo_name;
477 if (!is_dir ($repo) || !is_dir ("$repo/_darcs")) {
478 echo "No repository $repo\n" ;
487 $pipe = popen("darcs changes --repodir='$repo' "
488 ."--match 'date \"between $from_date and $to_date\"' "
491 $xml_parser = xml_parser_create();
492 xml_set_element_handler($xml_parser, "DarcsPluginStartElement", "DarcsPluginEndElement");
494 // Analyzing history stream
495 while (!feof($pipe) &&
496 $data = fgets ($pipe, 4096)) {
498 if (!xml_parse ($xml_parser, $data, feof ($pipe))) {
499 debug("Unable to parse XML with error " .
500 xml_error_string(xml_get_error_code($xml_parser)) .
502 xml_get_current_line_number($xml_parser));
509 xml_parser_free ($xml_parser);
512 // inserting group results in stats_cvs_groups
514 if (!db_query_params ('INSERT INTO stats_cvs_group (month,day,group_id,checkouts,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
515 array ($month_string,
521 echo "Error while inserting into stats_cvs_group\n" ;
526 // build map for email -> login
528 $email_login = array();
529 $email_login_fn = $repo."/_darcs/email-login.txt";
530 if (!file_exists($email_login_fn))
532 $email_login_fn = $repo."/.email-login.txt";
534 if (!file_exists($email_login_fn))
536 unset($email_login_fn);
539 if (isset($email_login_fn))
541 $fh = fopen($email_login_fn, 'r');
544 $a = explode(" ", fgets($fh));
547 $email_login[$a[0]] = rtrim($a[1]);
553 // building the user list
554 $user_list = array_unique( array_merge( array_keys( $usr_adds ), array_keys( $usr_updates ) ) );
556 foreach ( $user_list as $user ) {
557 // trying to get user id from darcs user name
559 $tmp_email = explode("<", $id, 2);
560 if (isset($tmp_email[1]))
562 $tmp_email = explode(">", $tmp_email[1]);
565 if (isset($email_login[$id]))
567 $id = $email_login[$id];
570 $u = &user_get_object_by_name ($id) ;
572 $user_id = $u->getID();
577 if (!db_query_params ('INSERT INTO stats_cvs_user (month,day,group_id,user_id,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
578 array ($month_string,
582 $usr_updates[$user] ? $usr_updates[$user] : 0,
583 $usr_adds[$user] ? $usr_adds[$user] : 0))) {
584 echo "Error while inserting into stats_cvs_user\n" ;
594 function printAdminPage ($params) {
595 parent::printAdminPage($params);
597 $project = $this->checkParams($params);
603 if ($project->usesPlugin($this->name))
605 $result = db_query_params(
606 "SELECT repo_name FROM plugin_scmdarcs_create_repos WHERE group_id=$1",
607 array($project->getID()));
608 if ($result && db_numrows($result) > 0)
611 while ($res = db_fetch_array($result))
613 array_push($nm, $res['repo_name']);
615 print '<p><strong>'._('Repository to be created: ') . '</strong>' .
616 implode(_(', '), $nm) . '</p>';
619 print '<p><strong>Create new repository:</strong></p>';
620 print '<p>'._('Repository name: ').
621 '<input type="string" name="scm_create_repo_name" size=16 maxlength=128 /></p>';
622 print '<p>'._('Clone: ').
623 '<select name="scm_clone_repo_name">';
624 print '<option value=""><none></option>';
625 foreach ($this->getRepositories($project) as $repo_name)
627 print '<option value="'.$repo_name.'">'.$repo_name.'</option>';
629 print '</select></p>';
633 function adminUpdate ($params) {
634 parent::adminUpdate($params);
636 $project = $this->checkParams($params);
642 $new_repo_name = $params['scm_create_repo_name'];
643 $clone_repo_name = $params['scm_clone_repo_name'];
644 if ($new_repo_name != '')
646 $repo_names = $this->getRepositories($project);
647 if (in_array($new_repo_name, $repo_names))
649 html_error_top(_("Repository $new_repo_name already exists"));
653 if ($clone_repo_name != '' && !in_array($clone_repo_name, $repo_names))
655 html_error_top(_("Clone repository $clone_repo_name doesn't exist"));
658 if ($clone_repo_name == '<none>')
660 $clone_repo_name = '';
663 if (!preg_match('/^[\w][-_\w\d\.]+$/', $new_repo_name))
665 html_error_top("Invalid repository name $new_repo_name");
670 if (!db_query_params ('INSERT INTO plugin_scmdarcs_create_repos (group_id,repo_name,clone_repo_name)
672 array($project->getID(), $new_repo_name, $clone_repo_name)))
674 html_error_top("SQL error while scheduling new repository $new_repo_name");
680 html_feedback_top(_("Repository $new_repo_name schedule for creation"));
686 function DarcsPluginStartElement($parser, $name, $attrs) {
687 global $last_user, $commits,
688 $adds, $updates, $deletes,
689 $usr_adds, $usr_updates, $usr_deletes;
692 $last_user = $attrs['AUTHOR'];
693 if (!array_key_exists($last_user, $usr_deletes))
695 $usr_deletes[$last_user] = 0;
697 if (!array_key_exists($last_user, $usr_updates))
699 $usr_updates[$last_user] = 0;
701 if (!array_key_exists($last_user, $usr_adds))
703 $usr_adds[$last_user] = 0;
708 case "REMOVE_DIRECTORY":
711 $usr_deletes[$last_user]++;
718 $usr_updates[$last_user]++;
722 case "ADD_DIRECTORY":
725 $usr_adds[$last_user]++;
731 function DarcsPluginEndElement ($parser, $name) {
735 // c-file-style: "bsd"