3 * FusionForge Darcs plugin
5 * Copyright 2009, Roland Mas
6 * Copyright 2013, Franck Villaume - TrivialDev
8 * This file is part of FusionForge.
10 * FusionForge is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published
12 * by the Free Software Foundation; either version 2 of the License,
13 * or (at your option) any later version.
15 * FusionForge is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 forge_define_config_item ('default_server', 'scmdarcs', forge_get_config ('web_host')) ;
26 forge_define_config_item ('repos_path', 'scmdarcs', forge_get_config('chroot').'/scmrepos/darcs') ;
28 class DarcsPlugin extends SCMPlugin {
29 function DarcsPlugin () {
32 $this->name = 'scmdarcs';
33 $this->text = 'Darcs';
34 $this->hooks[] = 'scm_generate_snapshots' ;
35 $this->hooks[] = 'scm_update_repolist' ;
36 $this->hooks[] = 'scm_browser_page' ;
37 $this->hooks[] = 'scm_gather_stats' ;
42 function getDefaultServer() {
43 return forge_get_config('default_server', 'scmdarcs') ;
46 function getRootRepositories ($project) {
47 return (forge_get_config('repos_path', 'scmdarcs') . '/' . $project->getUnixName());
50 function getRepositories ($project) {
52 $toprepo = $this->getRootRepositories($project);
55 foreach (scandir($toprepo) as $repo_name)
57 $repo = $toprepo . '/' . $repo_name;
58 if (is_dir($repo) && is_dir($repo . '/_darcs'))
67 function printShortStats ($params) {
68 $project = $this->checkParams ($params) ;
73 if ($project->usesPlugin($this->name) && forge_check_perm('scm', $project->getID(), 'read')) {
74 $result = db_query_params('SELECT sum(commits) AS commits, sum(adds) AS adds FROM stats_cvs_group WHERE group_id=$1',
75 array ($project->getID())) ;
76 $commit_num = db_result($result,0,'commits');
77 $add_num = db_result($result,0,'adds');
84 echo ' (Darcs: '.sprintf(_('<strong>%1$s</strong> commits, <strong>%2$s</strong> adds'), number_format($commit_num, 0), number_format($add_num, 0)).")";
88 function getBlurb () {
89 return '<p>' . _('Documentation for Darcs is available <a href="http://darcs.net/">here</a>.') . '</p>';
92 function getInstructionForDarcs ($project, $rw) {
93 $repo_names = $this->getRepositories($project);
94 if (count($repo_names) > 0)
96 $default_repo = "REPO";
97 if (count($repo_names) == 1)
99 $default_repo = $repo_names[0];
103 $url = $this->getBoxForProject($project) . ':'. $this->getRootRepositories($project) . '/' . $default_repo;
107 $url = util_make_url ('/anonscm/darcs/'.$project->getUnixName().'/' . $default_repo);
109 $b = '<p><tt>darcs get ' . $url . '</tt></p>';
110 if (count($repo_names) > 1)
112 $b .= _('<p>where REPO can be: ') . implode(_(', '), $repo_names) . '</p>';
115 else if (is_dir($this->getRootRepositories($project)))
117 $b = _('<p><em>No repositories defined.</em></p>');
121 $b = _('<p><em>Repository not yet created, wait an hour.</em></p>');
126 function getInstructionsForAnon ($project) {
128 $b .= _('Anonymous Darcs Access');
131 $b .= _('This project\'s Darcs repository can be checked out through anonymous access with the following command.');
133 $b .= $this->getInstructionForDarcs($project, false);
138 function getInstructionsForRW ($project) {
140 $b .= _('Developer Darcs Access via SSH');
143 $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.');
145 $b .= $this->getInstructionForDarcs($project, true);
149 function getSnapshotPara ($project) {
152 $filename = $project->getUnixName().'-scm-latest.tar'.util_get_compressed_file_extension();
153 if (file_exists(forge_get_config('scm_snapshots_path').'/'.$filename)) {
155 $b .= util_make_link ("/snapshots.php?group_id=".$project->getID(),
156 _('Download the nightly snapshot')
163 function getBrowserLinkBlock ($project) {
165 $b = $HTML->boxMiddle(_('Darcs Repository Browser'));
167 $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.');
169 $repo_names = $this->getRepositories($project);
170 if (count($repo_names) > 0)
172 foreach ($repo_names as $repo_name)
175 $b .= util_make_link ("/scm/browser.php?group_id=".$project->getID()."&repo_name=".$repo_name,
176 _('Browse Darcs Repository '. $repo_name));
182 $b .= _('<p>No repositories to browse</p>');
187 function getStatsBlock ($project) {
191 $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',
192 array ($project->getID()));
194 if (db_numrows($result) > 0) {
195 $b .= $HTML->boxMiddle(_('Repository Statistics'));
197 $tableHeaders = array(
202 $b .= $HTML->listTableTop($tableHeaders);
205 $total = array('adds' => 0, 'commits' => 0);
207 while($data = db_fetch_array($result)) {
208 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
209 $b .= '<td width="50%">' ;
210 $b .= util_make_link_u ($data['user_name'], $data['user_id'], $data['realname']) ;
211 $b .= '</td><td width="25%" align="right">'.$data['adds']. '</td>'.
212 '<td width="25%" align="right">'.$data['commits'].'</td></tr>';
213 $total['adds'] += $data['adds'];
214 $total['commits'] += $data['commits'];
217 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
218 $b .= '<td width="50%"><strong>'._('Total').':</strong></td>'.
219 '<td width="25%" align="right"><strong>'.$total['adds']. '</strong></td>'.
220 '<td width="25%" align="right"><strong>'.$total['commits'].'</strong></td>';
222 $b .= $HTML->listTableBottom();
228 function printBrowserPage ($params) {
231 $project = $this->checkParams ($params) ;
236 if ($project->usesPlugin ($this->name)) {
237 if ($this->browserDisplayable ($project)) {
238 print '<iframe src="'.
239 util_make_url ("/plugins/scmdarcs/cgi-bin/darcsweb.cgi?r=".
240 $project->getUnixName()). '/' . $params['repo_name'] .
241 '" frameborder="0" width=100% height=700></iframe>' ;
246 function createOrUpdateRepo ($params) {
247 $project = $this->checkParams ($params) ;
252 if (! $project->usesPlugin ($this->name)) {
256 $toprepo = $this->getRootRepositories($project);
257 $unix_group = 'scm_' . $project->getUnixName() ;
259 system("chmod g+ws $toprepo");
261 $result = db_query_params(
262 "SELECT repo_name, clone_repo_name FROM plugin_scmdarcs_create_repos WHERE group_id=$1",
263 array($project->getID()));
266 echo "Error while retrieving darcs repository to create\n";
270 while ($res = db_fetch_array($result))
272 $repo = $toprepo . '/' . $res['repo_name'];
274 if ($res['clone_repo_name'] != '')
276 $clone_repo = $toprepo . '/' . $res['clone_repo_name'];
278 if (!is_dir ($repo."/_darcs")) {
279 system ("mkdir -p '$repo'") ;
280 system ("cd $repo ; darcs init >/dev/null") ;
283 system ("darcs fetch '$clone_repo'") ;
285 system ("find $repo -type d | xargs chmod g+s") ;
287 $result1 = db_query_params(
288 "DELETE FROM plugin_scmdarcs_create_repos WHERE group_id=$1 AND repo_name=$2",
289 array($project->getID(), $res['repo_name']));
292 echo "Cannot remove scheduling of darcs repository creation ".$res['repo_name']."\n";
298 foreach ($this->getRepositories($project) as $repo_name)
300 $repo = $toprepo . '/' . $repo_name ;
302 system ("chgrp -R $unix_group $repo") ;
303 if ($project->enableAnonSCM()) {
304 system ("chmod -R g+wX,o+rX-w $repo") ;
306 system ("chmod -R g+wX,o-rwx $repo") ;
311 function darcswebRepository ($project, $repo_name, $repo_url, $repo_dir) {
312 $classname = preg_replace ('/\W/', '_', 'repo_' . $repo_name) ;
313 return ("class $classname:\n"
314 ."\trepodir = '$repo_dir'\n"
315 ."\treponame = '$repo_name'\n"
316 ."\t".'repodesc = """Repository ' . $repo_name . ' of '.$project->getPublicName().'"""'."\n"
317 ."\trepourl = '" . util_make_url ('/anonscm/darcs/' . $repo_url) . "'\n"
318 ."\trepoprojurl = '" . util_make_url ('/projects/' . $repo_url) . "'\n"
319 ."\trepoencoding = 'utf8'\n"
324 function updateRepositoryList ($params) {
325 $groups = $this->getGroups () ;
327 foreach ($groups as $project) {
328 if ($this->browserDisplayable ($project)) {
333 $fname = '/etc/gforge/plugins/scmdarcs/config.py' ;
335 $f = fopen ($fname.'.new', 'w') ;
337 fwrite ($f, "class base:\n"
338 ."\tdarcslogo = '".util_make_url ('/plugins/scmdarcs/darcsweb/darcs.png')."'\n"
339 ."\tdarcsfav = '".util_make_url ('/plugins/scmdarcs/darcsweb/minidarcs.png')."'\n"
340 ."\tcssfile = '".util_make_url ('/plugins/scmdarcs/darcsweb/style.css')."'\n"
343 foreach ($list as $project) {
344 $unix_name = $project->getUnixName();
345 $toprepo = $this->getRootRepositories($project);
346 $repo_names = $this->getRepositories($project);
347 foreach ($repo_names as $repo_name) {
348 if ($repo_name == $unix_name)
350 # Default repository name, we create a default entry for it
352 $this->darcswebRepository($project,
354 "$unix_name/$repo_name",
355 "$toprepo/$repo_name"));
358 $this->darcswebRepository($project,
359 "$unix_name/$repo_name",
360 "$unix_name/$repo_name",
361 "$toprepo/$repo_name"));
365 chmod ($fname.'.new', 0644) ;
366 rename ($fname.'.new', $fname) ;
369 function generateSnapshots ($params) {
372 $project = $this->checkParams ($params) ;
377 $group_name = $project->getUnixName() ;
379 $tarball = forge_get_config('scm_tarballs_path').'/'.$group_name.'-scmroot.tar'.util_get_compressed_file_extension();
381 if (! $project->usesPlugin ($this->name)) {
385 if (! $project->enableAnonSCM()) {
391 $toprepo = forge_get_config('repos_path', 'scmdarcs') ;
392 $repo = $this->getRootRepositories($project);
394 if (!is_dir ($repo)) {
399 $tmp = trim (`mktemp -d`) ;
403 $today = date ('Y-m-d') ;
404 $dir = $project->getUnixName ()."-$today" ;
405 system ("mkdir -p $tmp/$dir") ;
406 system ("cd $tmp ; darcs $repo $dir > /dev/null 2>&1") ;
407 system ("tar cCf $tmp - $dir |".forge_get_config('compression_method')."> $tmp/snapshot") ;
408 chmod ("$tmp/snapshot", 0644) ;
409 copy ("$tmp/snapshot", $snapshot) ;
410 unlink ("$tmp/snapshot") ;
411 system ("rm -rf $tmp/$dir") ;
413 system ("tar cCf $toprepo - ".$project->getUnixName() ."|".forge_get_config('compression_method')."> $tmp/tarball") ;
414 chmod ("$tmp/tarball", 0644) ;
415 copy ("$tmp/tarball", $tarball) ;
416 unlink ("$tmp/tarball") ;
417 system ("rm -rf $tmp") ;
420 function gatherStats ($params) {
421 global $adds, $deletes, $updates, $commits,
422 $usr_adds, $usr_deletes, $usr_updates;
424 $project = $this->checkParams ($params) ;
429 if (! $project->usesPlugin ($this->name)) {
433 if ($params['mode'] == 'day') {
436 $year = $params ['year'] ;
437 $month = $params ['month'] ;
438 $day = $params ['day'] ;
439 $month_string = sprintf( "%04d%02d", $year, $month );
440 $start_time = gmmktime( 0, 0, 0, $month, $day, $year);
441 $end_time = $start_time + 86400;
446 $usr_adds = array () ;
447 $usr_updates = array () ;
448 $usr_deletes = array ();
450 $toprepo = $this->getRootRepositories($project) ;
451 $from_date = date("c", $start_time);
452 $to_date = date("c", $end_time);
454 // cleaning stats_cvs_* table for the current day
455 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE month=$1 AND day=$2 AND group_id=$3',
456 array ($month_string,
458 $project->getID())) ;
460 echo "Error while cleaning stats_cvs_group\n" ;
465 $res = db_query_params ('DELETE FROM stats_cvs_user WHERE month=$1 AND day=$2 AND group_id=$3',
466 array ($month_string,
468 $project->getID())) ;
470 echo "Error while cleaning stats_cvs_user\n" ;
475 foreach ($this->getRepositories($project) as $repo_name)
477 $repo = $toprepo . '/' . $repo_name;
478 if (!is_dir ($repo) || !is_dir ("$repo/_darcs")) {
479 echo "No repository $repo\n" ;
488 $pipe = popen("darcs changes --repodir='$repo' "
489 ."--match 'date \"between $from_date and $to_date\"' "
492 $xml_parser = xml_parser_create();
493 xml_set_element_handler($xml_parser, "DarcsPluginStartElement", "DarcsPluginEndElement");
495 // Analyzing history stream
496 while (!feof($pipe) &&
497 $data = fgets ($pipe, 4096)) {
499 if (!xml_parse ($xml_parser, $data, feof ($pipe))) {
500 debug("Unable to parse XML with error " .
501 xml_error_string(xml_get_error_code($xml_parser)) .
503 xml_get_current_line_number($xml_parser));
510 xml_parser_free ($xml_parser);
513 // inserting group results in stats_cvs_groups
515 if (!db_query_params ('INSERT INTO stats_cvs_group (month,day,group_id,checkouts,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
516 array ($month_string,
522 echo "Error while inserting into stats_cvs_group\n" ;
527 // build map for email -> login
529 $email_login = array();
530 $email_login_fn = $repo."/_darcs/email-login.txt";
531 if (!file_exists($email_login_fn))
533 $email_login_fn = $repo."/.email-login.txt";
535 if (!file_exists($email_login_fn))
537 unset($email_login_fn);
540 if (isset($email_login_fn))
542 $fh = fopen($email_login_fn, 'r');
545 $a = explode(" ", fgets($fh));
548 $email_login[$a[0]] = rtrim($a[1]);
554 // building the user list
555 $user_list = array_unique( array_merge( array_keys( $usr_adds ), array_keys( $usr_updates ) ) );
557 foreach ( $user_list as $user ) {
558 // trying to get user id from darcs user name
560 $tmp_email = explode("<", $id, 2);
561 if (isset($tmp_email[1]))
563 $tmp_email = explode(">", $tmp_email[1]);
566 if (isset($email_login[$id]))
568 $id = $email_login[$id];
571 $u = &user_get_object_by_name ($id) ;
573 $user_id = $u->getID();
578 if (!db_query_params ('INSERT INTO stats_cvs_user (month,day,group_id,user_id,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
579 array ($month_string,
583 $usr_updates[$user] ? $usr_updates[$user] : 0,
584 $usr_adds[$user] ? $usr_adds[$user] : 0))) {
585 echo "Error while inserting into stats_cvs_user\n" ;
595 function printAdminPage ($params) {
596 parent::printAdminPage($params);
598 $project = $this->checkParams($params);
604 if ($project->usesPlugin($this->name))
606 $result = db_query_params(
607 "SELECT repo_name FROM plugin_scmdarcs_create_repos WHERE group_id=$1",
608 array($project->getID()));
609 if ($result && db_numrows($result) > 0)
612 while ($res = db_fetch_array($result))
614 array_push($nm, $res['repo_name']);
616 print '<p><strong>'._('Repository to be created: ') . '</strong>' .
617 implode(_(', '), $nm) . '</p>';
620 print '<p><strong>Create new repository:</strong></p>';
621 print '<p>'._('Repository name: ').
622 '<input type="string" name="scm_create_repo_name" size=16 maxlength=128 /></p>';
623 print '<p>'._('Clone: ').
624 '<select name="scm_clone_repo_name">';
625 print '<option value=""><none></option>';
626 foreach ($this->getRepositories($project) as $repo_name)
628 print '<option value="'.$repo_name.'">'.$repo_name.'</option>';
630 print '</select></p>';
634 function adminUpdate ($params) {
635 parent::adminUpdate($params);
637 $project = $this->checkParams($params);
643 $new_repo_name = $params['scm_create_repo_name'];
644 $clone_repo_name = $params['scm_clone_repo_name'];
645 if ($new_repo_name != '')
647 $repo_names = $this->getRepositories($project);
648 if (in_array($new_repo_name, $repo_names))
650 html_error_top(_("Repository $new_repo_name already exists"));
654 if ($clone_repo_name != '' && !in_array($clone_repo_name, $repo_names))
656 html_error_top(_("Clone repository $clone_repo_name doesn't exist"));
659 if ($clone_repo_name == '<none>')
661 $clone_repo_name = '';
664 if (!preg_match('/^[\w][-_\w\d\.]+$/', $new_repo_name))
666 html_error_top("Invalid repository name $new_repo_name");
671 if (!db_query_params ('INSERT INTO plugin_scmdarcs_create_repos (group_id,repo_name,clone_repo_name)
673 array($project->getID(), $new_repo_name, $clone_repo_name)))
675 html_error_top("SQL error while scheduling new repository $new_repo_name");
681 html_feedback_top(_("Repository $new_repo_name schedule for creation"));
687 function DarcsPluginStartElement($parser, $name, $attrs) {
688 global $last_user, $commits,
689 $adds, $updates, $deletes,
690 $usr_adds, $usr_updates, $usr_deletes;
693 $last_user = $attrs['AUTHOR'];
694 if (!array_key_exists($last_user, $usr_deletes))
696 $usr_deletes[$last_user] = 0;
698 if (!array_key_exists($last_user, $usr_updates))
700 $usr_updates[$last_user] = 0;
702 if (!array_key_exists($last_user, $usr_adds))
704 $usr_adds[$last_user] = 0;
709 case "REMOVE_DIRECTORY":
712 $usr_deletes[$last_user]++;
719 $usr_updates[$last_user]++;
723 case "ADD_DIRECTORY":
726 $usr_adds[$last_user]++;
732 function DarcsPluginEndElement ($parser, $name) {
736 // c-file-style: "bsd"