check_trans.pl 31.8 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/perl
#
#  This is a little utility designed to keep track of translations
#  in the Debian web site Subversion repository.
#
## For information about translation revisions please see
7
## https://www.debian.org/devel/website/uptodate
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#
#  Copyright (C) 2008 Bas Zoetekouw <bas@debian.org>
#  Based on on code from:
#   Copyright (C) 1998 Paolo Molaro <lupus@debian.org>
#   Copyright (C) 1999-2003 Peter Karlsson <peterk@debian.org>
#   Copyright (C) 2000,2001 Martin Quinson <mquinson@ens-lyon.fr>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of version 2 of the GNU General Public License as
#  published by the Free Software Foundation.
#
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
#
#
#  Invocation:
26
#    check_trans.pl [-cdlvqQ] [-C dir] [-p pattern] [-s subtree]
27 28
#                   [-m { -n <num> | -M <email> } [-g] ]
#                   [-t outputtype]
29 30 31 32 33 34 35 36 37 38 39 40
#                   [language]
#
#  It needs to be run from the top level webwml directory.
#  If you don't specify a language on the command line, the language name
#  will be loaded from a file called language.conf, if such a file exists.
#
#  For example:
#    $ check_trans.pl -v italian
#  You may also check only some subtrees as in:
#    $ check_trans.pl -s devel italian
#
#  Options:
41
#       -Q            be really quiet (only show errors/warnings on stderr)
42 43 44 45 46 47 48 49 50 51
#       -q            just don't whine about missing files
#       -v            show the status of all files (verbose)
#       -V            output what we're doing (very verbose)
#       -d            output diffs
#       -l            output log messages
#       -T            output translated diffs
#       -p <pattern>  include only files matching <pattern>,
#                     default is *.src|*.wml
#       -s <subtree>  check only that subtree
#       -a            output age of translation (if older than 2 months)
52
#       -c            disable use of color in the output
53 54
#
#  Options useful when sending mails:
55 56
#       -m            sends mails to translation maintainers as specified in
#                     in database in $lang/international/$lang/translator.db.pl
57
#                     PLEASE CAREFULLY READ THE BELOW TEXT ABOUT MAKING MAILS!
58 59 60 61 62 63 64 65
#       -n <1|2|3>    send mails of priority upper or equal to 1 (monthly),
#                     2 (weekly) or 3 (daily), as specified in the translator
#                     database
#       -M <email>    instead of using the translator database, send all email
#                     the specified address.  The translator database is not
#                     used.
#       -g            instead of sending mails, dump them to the console
#                     (no mails will be sent)
66
#
67
#  GENERATING EMAILS
68 69 70 71 72 73 74
#   If you want to, this script send mails to the maintainer of the mails.
#   BEWARE, SOME PEOPLE DO NOT LIKE TO RECEIVE AUTOMATIC MAILS!
#
#   PREREQUISITES:
#    You will need one database:
#      - one in which to get info about translators and the frequency at
#        which they want to get mails. It must be named
75
#        webwml/$lang/international/$lang/translator.db.pl
76 77 78
#        Please refer to the French one for more info.
#
#   USAGE:
79 80
#    If you give the "-g" option, all mails are written to the console.  No
#    mails are sent out at all.  This is useful for debugging.
81
#    If you specify an email address with the "-M" options, all mails are sent
82 83 84 85 86
#    to the specified addressee.  No mails are sent to any other addresses.  It
#    is useful if you want to run it for yourself.
#    Without either of these options, real mails will be sent to real
#    addresses.
#    MAKE SURE THE ADDRESSEES REALLY WANT TO GET THESE MAILS!
87 88

use Getopt::Std;
89 90 91 92
use File::Basename;
use File::Spec::Functions;
use Term::ANSIColor;
use Encode;
93
#use Data::Dumper;
94 95
use FindBin;
FindBin::again();
Denis Barbier's avatar
Denis Barbier committed
96

97
# These modules reside under webwml/Perl
98 99
use lib "$FindBin::Bin/Perl";
use Local::VCS ':all';
100
use Local::Util qw/ uniq read_file /;
101
use Local::WmlDiffTrans;
102 103 104
use Webwml::TransCheck;
use Webwml::TransIgnore;

105 106 107
use strict;
use warnings;

108

109 110 111
# global variable to record verbosity
my $VERBOSE  = 0;

112 113 114
# default files to process
my $DEFAULT_PATTERN = '(?:\.wml|\.src)$';

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
# status codes
use constant {
	ST_MISSING     => 1,
	ST_NEEDSUPDATE => 3,
	ST_UPTODATE    => 4,
	ST_NOTATRANSL  => 5,
	ST_BROKEN      => 6,
	ST_OBSOLETE    => 7,
	ST_UNDEFINED   => 8,
};

# how to colour each different status
my %COLOURS = (
	main::ST_MISSING     => 'magenta',
	main::ST_NEEDSUPDATE => 'blue',
	main::ST_UPTODATE    => 'green',
	main::ST_NOTATRANSL  => 'yellow',
	main::ST_BROKEN      => 'red',
	main::ST_OBSOLETE    => 'red',
	main::ST_UNDEFINED   => 'red',
	'warn'               => 'bold red',
);
137

138 139 140 141 142 143 144 145 146 147 148 149 150
# default values for sending mails
my $MY_EMAIL = q{Debian WWW translation watch <debian-www@lists.debian.org>};
my $DEFAULT_SUBJECT = q{Debian web page translations needing updates};
(my $DEFAULT_BODY = <<"EOF") =~ s/^\t//gm;
	Hi!

	This is an automatic message providing an overview of Debian webpages
	of which the translation is outdated.

	Kind regards,
	Your automatic daemon.
EOF

Bas Zoetekouw's avatar
Bas Zoetekouw committed
151
# these is called in "main" so need to be declared here
152 153
sub switch_var(\$\$);
sub verbose;
154

155 156 157
#=================================================
#== "main"
#==
158
{
159 160 161
	# install a signal handler to catch Ctrl-C
	$SIG{'INT'} = \&handle_INT;

162
	# parse the command line
163
	my ($language,$file_pattern,%OPT) = parse_cmdargs();
164 165 166 167 168

	# read the tranlator db if we need it (-n was specified)
	my %translators = $OPT{n} ? read_translators( $language ) : ();

	# this hash will be used to store the emails we want to send out
169 170
	my %emails_to_send;

171
	# the subdirs where the english and translated files are located
172 173 174
	my $english_path  = 'english';
	my $language_path = $language;

175
	# -s allows the user to restrict processing to a subtree
176 177
	my $subdir = $OPT{'s'} || undef;

178
	my $VCS = Local::VCS->new();
179
	print "Caching VCS for performance...\n";
180 181
	$VCS->cache_repo();
	print "   ...done\n";
182

183
	# Global .transignore
184
	my $transignore = Webwml::TransIgnore->new($VCS->get_topdir());
185 186

	# first get a list with revision information from all files in english...
187
	my %english_revs = $VCS->path_info( $english_path,
188 189
		'recursive' => 1,
		'match_pat' => $file_pattern,
190
		'skip_pat'  => '^template/'
191
	);
192
	# ... and in the translation
193
	my %translation_revs = $VCS->path_info( $language_path,
194 195
		'recursive' => 1,
		'match_pat' => $file_pattern,
196
		'skip_pat'  => '^template/'
197 198 199 200 201 202 203 204 205
	);

	# construct a list with all files that either occur in english or
	# in the translation
	my @files = uniq ( keys %english_revs, keys %translation_revs );


	# now check each of the files
	foreach my $file (sort @files)
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
		# ignore this file?
		next if $transignore->is_global( $file );
		next if $subdir and not $file =~ m{^$subdir};

		# note: $language is the name of the current language we're
		# processing, whereas $transl is the name of the language which the
		# current file is translated into (which might be english!)
		my $orig   = 'english';
		my $transl = $language;

		my $file_orig   = catfile( $orig,   $file );
		my $file_transl = catfile( $transl, $file );

		my $revinfo_orig   = $english_revs{$file};
		my $revinfo_transl = $translation_revs{$file};

		# TODO: put this in a separate function
		# first we check if the translated file has an origin other than
		# english
		if ( -e $file_transl )
		{
			my $transcheck = Webwml::TransCheck->new( $file_transl );
			my $original_lang = $transcheck->original();

			if ( $original_lang  and  $original_lang ne 'english' )
			{
				die( "Unknown original language `$original_lang' "
				    ."for `$file_transl'\n" ) unless -d $original_lang;

				verbose "`$file_transl' is translated from $original_lang";

				# now, we use the correct (non-english) original file
				$file_orig  = catfile( $original_lang, $file );

				# and find the correct revision info for this file
242
				$revinfo_orig = { $VCS->file_info( $file_orig ) };
243 244

				$orig = $original_lang;
245 246
			}
		}
247

248 249 250 251 252 253 254 255 256 257 258
		# TODO: put this in a separate function
		# secondly, we check if perhaps the original file is a translation
		# (such as in the case of english/international/Swedish/index.wml)
		if ( -e $file_transl and -e $file_orig )
		{
			my $transcheck    = Webwml::TransCheck->new( $file_orig );
			my $original_lang = $transcheck->original();
			my $rev           = $transcheck->revision();

			if ( $rev )
			{
259 260 261 262 263 264 265 266 267 268 269 270
				## This check is too strict: some translators like to translate
				##from other translations rather than from the original english
				##(see e.g., danish/international/Norwegian.wml)
				#if ( not $original_lang )
				#{
				#	# TODO: ideally, this would also be mailed out to the
				#	# translation team
				#	warn "`$file_orig' has a revision header but no origin language\n";
				#	next;
				#}

				if ( $original_lang   and  $original_lang eq $language )
271 272 273 274 275 276 277 278 279
				{
					verbose "`$file_orig' is a translation from $language";

					# switch $orig and $transl
					switch_var( $orig,         $transl         );
					switch_var( $file_orig,    $file_transl    );
					switch_var( $revinfo_orig, $revinfo_transl );
				}
			}
280
		}
281

282 283 284
		# skip original files (i.e., most of english)
		next if ( $file_orig eq $file_transl );

285 286
		# determine the status of the file
		my ($status,$str,$rev_transl,$maintainer,$maxdelta) = check_file(
287
			$VCS,
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
			$file,
			$orig, $transl,
			$revinfo_orig, $revinfo_transl,
		);


		######################################################################
		## Everything below is just output logic
		######################################################################

		# print info
		if (    ( $OPT{v} )
		     or ( $status == ST_MISSING  and  not $OPT{q}  )
		     or ( $status != ST_MISSING  and  $status != ST_UPTODATE
		          and  $status != ST_NOTATRANSL )
		)
		{
			print colored( "$str\n", $COLOURS{$status} );
		}

		# check age of the translation
		if ( $OPT{a} and $status == ST_NEEDSUPDATE )
		{
311
			my $age = int get_revision_age( $revinfo_transl );
312 313 314 315 316 317 318 319

			# only warn if the translation is older than 2 weeks
			if ( $age > 14 )
			{
				print colored( "$file is outdated by $age days\n",
					$COLOURS{warn} );
			}
		}
320

321 322 323 324
		# print log if requested and an update is needed
		if ( $OPT{'l'}  and  $status == ST_NEEDSUPDATE )
		{
			my $log = get_log(
325
				$VCS,
326 327
				$file_orig,
				$rev_transl,
328
				$revinfo_orig->{'cmt_rev'},
329 330 331 332
			);
			print $log;
		}

333 334 335 336
		# print diff if requested and an update is needed
		if ( $OPT{'d'}  and  $status == ST_NEEDSUPDATE )
		{
			my $diff = get_diff(
337
				$VCS,
338 339
				$file_orig,
				$rev_transl,
340
				$revinfo_orig->{'cmt_rev'},
341 342 343
			);
			print $diff;
		}
344

345 346 347 348
		# print text diff, if requested and an update is needed
		if ( $OPT{'T'}  and  $status == ST_NEEDSUPDATE )
		{
			my $diff = get_diff_txt(
349
				$VCS,
350 351
				$file_orig,
				$rev_transl,
352
				$revinfo_orig->{'cmt_rev'},
353 354 355 356
				$file_transl
			);
			print $diff;
		}
357 358


359 360 361
		# prepare a mail to be sent
		if ( $OPT{'m'}  and  $status != ST_UPTODATE )
		{
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
			# -M was specified, so all mails to there
			if ( $OPT{'M'} )
			{
				$maintainer = 'default';

				# don't send mail about untranslated files if -q was specified
				$maintainer = 'none' 
					if $status == ST_MISSING and $OPT{'q'} 
			}
			else # addresses from the database is used
			{
				# handle special case maintainer fields
				$maintainer = 'unmaintained'
					unless $maintainer and exists $translators{$maintainer};
				$maintainer = 'untranslated'
					if $status == ST_MISSING;
			}

			verbose  "Found maintainer $maintainer for this file";
381 382 383 384 385 386 387

			# mail to send to the maintainer
			push @{ $emails_to_send{$maintainer} }, {
				'file'           => $file,
				'status'         => $status,
				'info'           => $str,
				'last_trans_rev' => $rev_transl,
388
			};
389

390 391 392
			# additionally, if -n was specified, also see if we need to
			# send a mail to maxdelta
			if ( $OPT{'n'}  and  $status != ST_MISSING  and  -e $file_orig )
393 394
			{
				$maxdelta ||= $translators{maxdelta}{maxdelta} || 5;
395

396
				my $delta;
397
				$delta = $VCS->count_changes( $file_orig, $rev_transl, 'HEAD' );
398 399 400
				if (!defined $delta) {
					print "ERROR: Can't get details for orig file $file_orig\n";
				}
401 402
				if ( $delta >= $maxdelta )
				{
403 404 405 406 407 408 409
					push @{ $emails_to_send{'maxdelta'} }, {
						'file'           => $file,
						'status'         => $status,
						'info'           => $str,
						'delta'          => $delta,
						'last_trans_rev' => $rev_transl,
					}
410 411
				}
			}
412

413
		}
414

415 416
	}

417
	send_email( $VCS, \%emails_to_send, \%translators, $language, 
418
		$OPT{'n'}, $OPT{'M'}, $OPT{'g'} );
419 420 421 422 423 424 425

	exit 0;
}
die("Never reached");


#=================================================
426
#== switch two variables around
427 428 429 430 431 432 433 434 435 436
#==
sub switch_var(\$\$)
{
	my $a = shift;
	my $b = shift;

	my $c = $$a;
	$$a = $$b;
	$$b = $c;
}
437

438

439 440 441 442
#=================================================
#== output verbose messages
#==
sub verbose
443
{
444 445
	return unless $VERBOSE;
	print @_, "\n";
446
}
447

448 449 450 451 452 453 454 455 456
#=================================================
#== handles INT signal
#==
sub handle_INT
{
	# reset terminal color
	print color('reset');
	die( "Interrupted by user" );
}
457 458 459 460 461

#=================================================
#== send out the emails
#==
sub send_email
462
{
463
	my $VCS         = shift;
464 465 466
	my $emails      = shift  or  die("No emails specified");
	my $translators = shift  or  die("No translators specified");
	my $lang        = shift  or  die("No language specified");
467 468 469
	my $priority    = shift;
	my $default_rec = shift;
	my $debug       = shift;
470 471

	foreach my $name (sort keys %$emails)
472
	{
473 474 475
		# special case
		next if $name eq 'none';

476 477
		verbose("Preparing email for $name");

478 479 480
		my $recipient;
		my $subject;
		my $mailbody;
481

482
		# First handle the case in which all mail goes to the -M address
483
		if ( $default_rec )
484
		{
485 486 487 488
			# address was already validated while parsing the command line
			$recipient = $default_rec;
			$subject   = $DEFAULT_SUBJECT;
			$mailbody  = $DEFAULT_BODY;
489
		}
490
		else # handle the case in which addresses are fetch from the db
491
		{
492 493 494 495 496 497 498
			# skip unconfigured users
			if ( not exists $translators->{$name}
					or  not $translators->{$name}{'email'} )
			{
				verbose( "Woops!  Can't find info for user `$name'\n" );
				next;
			}
499

500
			# check the user's email address
501 502 503 504 505 506
			if ( not Email::Address->parse( $translators->{$name}{'email'} ) )
			{
				printf STDERR "Can't parse email address `%s' for %s!\n",
					$translators->{$name}{'email'}, $name;
				next;
			}
507

508 509 510 511 512 513 514 515 516
			# skip if the user doesn't want a summary at all
			if ( $translators->{$name}{'summary'} < $priority )
			{
				verbose( "Not sending message to $name (prio "
					. $translators->{$name}{'summary'} . " < $priority)" );
				next;
			}

			$recipient = $translators->{$name}{'email'};
517
			$subject   = $translators->{'default'}{'mailsubject'};
518 519 520 521 522

			# read body and interpret perl that's embedded there
			$mailbody = read_file_enc( $translators->{'default'}{'mailbody'} )
				or die("Can't read $translators->{'default'}{'mailbody'}");
			{
523
				# a bit hackish, but I want to keep the current format of
524 525 526 527 528 529 530 531
				# the mail body files intact, for now
				# so we need to use the same old variable names as the original
				# script used
				my %translators = %{$translators};
				$mailbody =~ s{#(.*?)#}{eval $1}mge;
			}

		}
532 533 534

		my $msg = MIME::Lite->new(
			'From'    => $MY_EMAIL,
535 536
			'To'      => $recipient,
			'Subject' => $subject,
537 538 539 540
			'Type'    => 'multipart/mixed',
		);

		# and attach the body to the mail
541 542
		my $part = MIME::Lite->new(
			'Type' => 'text/plain',
543
			'Data' => encode('utf-8',$mailbody),
544
		);
545 546
		$part->attr( 'content-type.charset' => 'utf-8' );
		$msg->attach( $part );
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

		# attach part about NeedToUpdate files
		my $text = '';
		foreach my $file ( @{ $emails->{$name} } )
		{
			next unless $file->{'status'} == ST_NEEDSUPDATE;
			$text .= $file->{'info'};

			if ( exists $file->{'delta'} )
			{
				$text .= sprintf( " [out of date by %d revisions]",
					$file->{'delta'} );
			}

			$text .= "\n";
		}
		$msg->attach(
			'Type'     => 'TEXT',
			'Filename' => 'NeedToUpdate summary',
			'Data'     => $text,
		)
		if $text;

		# attach part about Missing files
571
		if ( not $default_rec )
572
		{
573 574 575 576 577 578 579 580 581 582 583 584 585
			$text = '';
			foreach my $file ( @{ $emails->{$name} } )
			{
				next unless $file->{'status'} == ST_MISSING;
				$text .= sprintf( "%s\n", $file->{'info'} );
			}
			$msg->attach(
				'Type'     => 'TEXT',
				'Filename' => 'Missing summary',
				'Data'     => $text,
				'Encoding' => 'quoted-printable',
			)
			if $text;
586 587 588
		}

		# add diffs, if requested
589
		if ( $default_rec  or  $priority <= $translators->{$name}{'diff'} )
590 591 592 593 594 595 596 597 598
		{
			foreach my $file ( @{ $emails->{$name} } )
			{
				# diffs really only make sense if there is an existing
				# translation
				next unless $file->{'status'} == ST_NEEDSUPDATE;

				my $filename = catfile( 'english', $file->{'file'} );
				my $rev      = $file->{'last_trans_rev'};
599
				my $diff     = get_diff( $VCS, $filename, $rev, 'HEAD' );
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
				$msg->attach(
					'Type'	   => 'TEXT',
					'Filename' => "$filename.diff",
					'Data'     => $diff,
					'Encoding' => 'quoted-printable',
				);
			}
		}
		else
		{
			verbose( "Not attaching diffs  (prio "
				. $translators->{$name}{'diff'} . " < $priority)" );
		}

		# add tdiffs, if requested
615
		if ( not $default_rec  and  $priority <= $translators->{$name}{'tdiff'} )
616 617 618 619 620 621 622 623 624 625
		{
			foreach my $file ( @{ $emails->{$name} } )
			{
				# diffs really only make sense if there is an existing
				# translation
				next unless $file->{'status'} == ST_NEEDSUPDATE;

				my $filename  = catfile( 'english', $file->{'file'} );
				my $filename2 = catfile( $lang,     $file->{'file'} );
				my $rev       = $file->{'last_trans_rev'};
626
				my $tdiff    =  get_diff_txt( $VCS, $filename, $rev, 'HEAD',
627 628 629 630 631 632 633 634 635 636 637 638
					$filename2 );
				$msg->attach(
					'Type'	   => 'TEXT',
					'Filename' => "$filename.tdiff",
					'Data'     => $tdiff,
					'Encoding' => 'quoted-printable',
				);
			}
		}
		else
		{
			verbose( "Not attaching tdiffs (prio "
639 640
				. $translators->{$name}{'tdiff'} . " < $priority)" )
			unless $default_rec;
641 642 643
		}

		# add logs, if requested
644
		if ( $default_rec  or  $priority <= $translators->{$name}{'logs'} )
645 646 647 648 649 650 651 652 653
		{
			foreach my $file ( @{ $emails->{$name} } )
			{
				# logs really only make sense if there is an existing
				# translation
				next unless $file->{'status'} == ST_NEEDSUPDATE;

				my $filename  = catfile( 'english', $file->{'file'} );
				my $rev       = $file->{'last_trans_rev'};
654
				my $log       = get_log( $VCS, $filename, $rev, 'HEAD' );
655
				my $part = MIME::Lite->new(
656
					'Type'     => 'TEXT',
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
					'Filename' => "$filename.log",
					'Data'     => $log,
					'Encoding' => 'quoted-printable',
				);
				$part->attr( 'content-type.charset' => 'utf-8' );
				$msg->attach( $part );
			}
		}
		else
		{
			verbose( "Not attaching logs   (prio "
				. $translators->{$name}{'logs'} . " < $priority)" );
		}

		# add file, if requested
672
		if ( not $default_rec  and  $priority <= $translators->{$name}{'file'} )
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
		{
			foreach my $file ( @{ $emails->{$name} } )
			{
				my $filename  = catfile( $lang, $file->{'file'} );
				my $part = MIME::Lite->new(
					'Type'	   => 'text/wml',
					'Filename' => $filename,
					'Path'     => $filename,
					'Encoding' => 'quoted-printable',
				);
				$part->attr( 'content-type.charset' => get_file_charset($filename) );
				$msg->attach( $part );

			}
		}
		else
		{
			verbose( "Not attaching files  (prio "
691 692
				. $translators->{$name}{'file'} . " < $priority)" )
				unless $default_rec;
693 694 695 696 697
		}



		# check if we really want to send the mail
698
		if ( $debug )
699
		{
700 701 702 703 704 705 706
			print color('bold yellow');
			print '*'x72, "\n";
			printf "Would send email to %s (but -g was specified):\n",
				$recipient;
			print '-'x72, "\n";
			print color('reset');

707
			# make sure perl doesn't do any annoying charset conversions
708
			binmode( \*STDOUT, ':bytes' );
709
			print $msg->as_string;
710 711 712 713

			print color('bold yellow');
			print '*'x72, "\n";
			print color('reset');
714 715 716
		}
		else
		{
717 718
			verbose "Sending email to $recipient";
			$msg->send  or  warn("Couldn't send message to $name");
719
		}
720
	}
721 722
}

723

724 725 726 727
#=================================================
#== return the age of the revision (in days)
#==
sub get_revision_age
728
{
729
	my $rev_info = shift;
730

731
	die("No revision info specified") unless ref $rev_info eq 'HASH';
732

733
	my $rev_timestamp = $rev_info->{'cmt_date'};
734 735 736 737 738 739
	my $age = time - $rev_timestamp;

	warn( "Timestamp is in the future!" ) if $age < 0;

	# return age in days
	return $age / ( 60*60*24 );
740 741
}

742

Denis Barbier's avatar
Denis Barbier committed
743

744 745 746 747 748
#=================================================
#== get a log
#==
sub get_log
{
749
	my $VCS = shift;
750 751 752 753 754 755
	my $file = shift or die("No file specified for diff");
	my $rev1 = shift;
	my $rev2 = shift;

	die("NO such file `$file'") unless -e $file;

756
	my @log = $VCS->get_log( $file, $rev1, $rev2 );
757 758 759 760 761 762 763 764 765 766

	# remove the first item of the log, because we only want
	# to see when changed in the (left-open) range (rev1,rev2]
	shift @log;

	# format it nicely
	my $str = '-' x 78 . "\n";
	foreach my $l (@log)
	{
		chomp $l->{'message'};
Denis Barbier's avatar
Denis Barbier committed
767

768
		$str .= sprintf( "%s | %s | %s\n",
769 770 771 772 773 774
			$l->{'rev'}, $l->{'author'}, scalar localtime $l->{'date'} );
		$str .= "\n";
		$str .= $l->{'message'} . "\n";
		$str .= "\n";

		$str .= '-' x 78 . "\n";
775

776
	}
777 778 779


	return $str;
780 781
}

782 783 784 785 786
#=================================================
#== get a diff
#==
sub get_diff
{
787
	my $VCS = shift;
788 789 790 791 792 793
	my $file = shift or die("No file specified for diff");
	my $rev1 = shift;
	my $rev2 = shift;

	die("NO such file `$file'") unless -e $file;

794
	my %diffs = $VCS->get_diff( $file, $rev1, $rev2 );
795 796 797 798 799

	# just glue all diffs together and return it as a big string
	my $difftxt = join( '', values %diffs );

	return $difftxt;
800 801
}

802 803 804 805
#=================================================
#== get a diff while trying to match html tags
#==
sub get_diff_txt
806
{
807
	my $VCS = shift;
808 809 810 811 812 813 814 815 816
	my $english_file = shift or die("No file specified");
	my $rev1         = shift or die("No revision specified");
	my $rev2         = shift or die("No revision specified");
	my $transl_file  = shift or die("No transl file specified");

	die("No such file $english_file") unless -e $english_file;
	die("No such file $transl_file")  unless -e $transl_file;

	# Get old revision file
817
	my @english_txt = split( "\n", $VCS->get_file( $english_file, $rev1 ) );
818 819

	# Get translation file
820
	my $transl_txt = read_file( $transl_file )
821
		or die("Couldn't read `$transl_file': $!");
822
	my @transl_txt = split( "\n", $transl_txt );
823 824

	# Get diff lines
825
	my @diff_txt = split( "\n", get_diff( $VCS, $english_file, $rev1, $rev2 ) );
826 827 828 829 830 831 832 833 834

	# do the matching
	my $txt = Local::WmlDiffTrans::find_trans_parts(
		\@english_txt,
		\@transl_txt,
		\@diff_txt
	);

	return $txt;
835 836
}

837 838 839 840 841

#=================================================
#== show help from the top of this file
#==
sub show_help
842
{
843 844
	# read the help from the comments above and display it
	open( my $me, '<', $0 ) or die "Unable to display help: $!\n";
845

846
	while ( my $line = <$me> )
847
	{
848 849 850
		last        if     $line =~ m{^use};
		print "\n"  if     $line =~ m{^#$};
		next        unless $line =~ m{^# };
851

852
		$line =~ s{^#  ?}{};
853

854
		print $line;
855 856
	}

857
	close( $me );
858 859 860
}


861 862 863 864 865 866 867 868 869
#=================================================
#== parse command line options and read defaults
#==
sub parse_cmdargs
{
	my %OPT;
	$OPT{s} = '';

	# parse options
870
	if ( not getopts( 'acdghlmM:n:p:Qqs:TvV', \%OPT )  )
871 872 873
	{
		show_help();
		exit -1;
874 875
	}

876 877 878 879 880 881 882 883
	# show help
	if ( $OPT{h} )
	{
		show_help();
		exit 0;
	}

	# handle verbosity setting
884
	if ( ( $OPT{'v'} or $OPT{'V'} ) and ( $OPT{'q'} or $OPT{'Q'} ) )
885 886 887 888 889
	{
		die "you can't have both verbose and quiet, doh!\n";
	}
	$VERBOSE  = 1  if $OPT{'V'};
	$OPT{'v'} = 1  if $OPT{'V'};
890

891 892 893 894 895
	# handle really quiet setting
	if ( $OPT{'Q'} )
	{
		# redirect stdout to /dev/null
		close( STDOUT );
Bas Zoetekouw's avatar
Bas Zoetekouw committed
896
		open( STDOUT, '>', '/dev/null' )
897 898 899
			or die( "Can't redirect STDOUT to /dev/null: $!" );
	}

900 901 902 903 904 905
	# handle -c (disable color) setting
	if ( $OPT{'c'} )
	{
		# nice feature of Term::ANSIColor
		$ENV{'ANSI_COLORS_DISABLED'} = '1';
	}
906 907 908 909 910 911
	else
	{
		# we need flushed STDOUT putput, because otherwise the colours wills
		# blend into STDERR
		$| = 1;
	}
912

913 914 915 916
	# handle -s (subtree check) setting
	if ( $OPT{s})
	{
		verbose "Checking subtree $OPT{s} only\n";
917
	}
918

919 920 921 922
	# check validity of mail options
	# if -m is specified, either -n or -M must also be given
	# furthermore, the argument to -n must be 1, 2, or 3, and
	# the argument to -M must be a valid email address
923 924
	if ( $OPT{'m'} )
	{
925
		# load additional module we need for mail
926 927 928 929 930 931 932 933 934 935 936 937 938
		eval {
			require MIME::Lite;
			import MIME::Lite;
		};
		die "The module MIME::Lite could not be loaded.\n"
		   ."Please install libmime-lite-perl\n"   if $@;

		eval {
			require Email::Address;
			import Email::Address;
		};
		die "The module Email::Address could not be loaded.\n"
		   ."Please install libemail-address-perl\n"   if $@;
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958

		# now check the options
		if ( $OPT{'n'} and $OPT{'M'} )
		{
			die "You can't specify both -n and -M\n";
		}
		elsif ( $OPT{'n'} )
		{
			die "Invalid priority `$OPT{n}'. "
			   ."Please set -n value to 1, 2 or 3.\n"
				unless $OPT{'n'} =~ m{^[123]$}
		}
		elsif ( $OPT{'M'} )
		{
			die "Invalid email address `$OPT{M}'\n"
				unless Email::Address->parse( $OPT{M} );
		}
		else
		{
			die "You specified -m (send mails), but you didn't specify "
959
			   ."either -n or -M, so I don't know where to send my mails\n";
960 961
		}

962 963
	}

964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
	if ( $OPT{'g'} and not $OPT{'m'} )
	{
		die "Option -g (debuG mail) without -m (use mail) "
		   ."really doesn't make much sense\n";
	}

	# include only files matching $filename
	my $file_pattern = $OPT{'p'} || $DEFAULT_PATTERN;

	my $translation = shift @ARGV || '';

	# language configuration
	if ( not $translation )
	{
		if ( exists $ENV{DWWW_LANG} )
		{
			$translation = $ENV{DWWW_LANG};
		}
		elsif ( -e "language.conf" )
		{
			open( my $conf, '<', 'language.conf' )
				or die("Can't read language.conf: $!\n");
			while (<$conf>)
			{
				next if /^#/;
				chomp;
				$translation = $_;
				last;
			}
			close $conf;
		}
	}
996

997 998 999 1000 1001 1002 1003 1004 1005 1006
	# Remove slash from the end
	$translation =~ s{/$}{};

	if ( $translation eq '' )
	{
		die "Language not defined in DWWW_LANG, language.conf, "
		   ."or on command line\n";
	}

	return ($translation,$file_pattern,%OPT);
1007 1008
}

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
#=================================================
#== read the translators from translator.db
#==
sub read_translators
{
	my $lang = shift or die("Internal error: no language specified");

	my %translators;

	my $db_file = catfile( $lang, 'international', $lang, 'translator.db.pl' );

	verbose "Reading translation database $db_file";

	if ( -e $db_file)
	{
		require $db_file;

		verbose "READ TRANSLATOR DB: $db_file\n";

		%translators = %{ init_translators() };

		if ( exists $translators{default} )
		{
			my @field_list = keys %{ $translators{default} };
			foreach my $user (keys %translators)
			{
				next if $user eq 'default';
				foreach my $f (@field_list)
				{
					$translators{$user}{$f} = $translators{default}{$f}
						unless exists $translators{$user}{$f};
				}
			}
		}
1043 1044
	} 
	else
1045
	{
1046 1047
		die "File `$db_file' doesn't exist!\n"
		   ."I need my DBs to send mails.\n"
1048 1049 1050 1051
		   ."Please read the comments in the script and try again\n";
	}

	return %translators;
1052
}
1053

1054 1055 1056 1057 1058 1059 1060
#=================================================
#== check if a single file is up to date
#== returns ($status,$message)
#== where status is one of the ST_* constants (see top of file)
#==
sub check_file
{
1061
	my $VCS             = shift;
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	my $file            = shift;
	my $orig            = shift;
	my $lang            = shift;
	my $english_rev     = shift; # might be undef
	my $translation_rev = shift; # might be undef

	die("Internal error: insufficient arguments")
		unless $file and $orig and $lang;

	# filename of english and translated files
	my $file_orig        = catfile( $orig, $file );
	my $file_translation = catfile( $lang, $file );

	# revision of the latest change in the english file
	my $orig_last_change = $english_rev ? $english_rev->{cmt_rev} : 'n/a';

	# revision of the english file that was translated
    my $transcheck = Webwml::TransCheck->new( $file_translation );
	my $translation_last_change = $transcheck->revision()   || 'n/a';
	my $translation_translator  = $transcheck->maintainer() || undef;
	my $translation_maxdelta    = $transcheck->maxdelta()   || undef;

1084 1085 1086
	if (!defined $orig_last_change) {
		$orig_last_change = "<UNKNOWN>";
	}
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
	verbose "Checking $file_translation, $orig revision $orig_last_change";

	# status information
	my $status = undef;
	my $str    = undef;

	# at this point, there are several possibilities:
	#   1) file exists both in english and translation
	#   2) file exists only in english
	#   3) file exists only in translation
	#   4) file exists in neither original or translation: can't happen
	# we handle those cases one by one

	# 1) both files exist
	if ( -e $file_orig and -e $file_translation )
	{
		# now check if both files have correct revisions
		# again, three cases
		# 1a) original file doesn't have a revision (can't happen)
		# 1b) translated file doesn't have a revision (error in wml file)
		# 1c) revision of both files is known

		# 1a) no revision for english file
		if ( $orig_last_change eq 'n/a' )
		{
			# this can't happen: something must be wrong with this script
			die( "internal error: no revision for english file" );
		}

		# 1b) no revision on translated file: error
		elsif ( $translation_last_change eq 'n/a' )
		{
			$status = ST_UNDEFINED;
			$str = "Unknown status of $file_translation "
			      ."(revision should be $orig_last_change)";
		}

		# 1c) both files have revisions
		else
		{
			# check the revisions to see if they're up to date
1128
			my $cmp = $VCS->cmp_rev( $file_orig, $translation_last_change,
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
				$orig_last_change );

			if ( $cmp == 0 ) # revisions equal
			{
				# up to date
				$str = "UpToDate $file_translation";
				$status = ST_UPTODATE;
			}
			elsif ( $cmp == -1 ) # $translation_last_change < $orig_last_change
			{
				# out of date
				$status = ST_NEEDSUPDATE;
				$str = "NeedToUpdate $file_translation from revision "
				      ."$translation_last_change to revision $orig_last_change";
			}
			else # $translation_last_change > $orig_last_change
			{
				# weirdness: translation is newer than original
				$status = ST_BROKEN;
				$str = "Broken revision number r$translation_last_change "
				."for $file_translation, it should be $orig_last_change";
			}
		}
1152
	}
1153 1154 1155 1156 1157 1158

	# 2) original file exists, but translation is missing
	elsif ( -e $file_orig and not -e $file_translation )
	{
		$status = ST_MISSING;
		$str = "Missing $file_translation version $orig_last_change";
1159
	}
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

	# 3) translation exists, but original is missing
	elsif ( not -e $file_orig and -e $file_translation )
	{
		# the translated file doesn't have a translation header,
		# so it probably is an original
		if ( $translation_last_change eq 'n/a' )
		{
			$status = ST_NOTATRANSL;
			$str = "NotATranslation $file_translation";
		}
Bas Zoetekouw's avatar
Bas Zoetekouw committed
1171
		# otherwise, it has a translation header,
1172 1173 1174 1175 1176 1177
		# so the english file was removed
		else
		{
			$status = ST_OBSOLETE;
			$str = "Obsolete $file_translation";
		}
1178 1179
	}

1180 1181 1182 1183 1184 1185
	# neither original nor translation exists
	else
	{
		# this should never occur, because it means the function was
		# called with an invalid argument
		die( "Internal error: file not present in english nor $lang" );
1186 1187
	}

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
	# add name of translator
	$str .= " (maintainer $translation_translator)" if $translation_translator;

	return ($status,$str,$translation_last_change,
	        $translation_translator,$translation_maxdelta);
}


# get the encoding of a certain file, by looking for wmlrc
sub get_file_charset
{
	my $file = shift or croak("No file specified");

	# default charset
	my $charset = 'utf-8';

	# read the wmlrc file
	my $wmlrc_dir = dirname($file);
	while ( not -e catfile( $wmlrc_dir, '.wmlrc' ) )
	{
		$wmlrc_dir = dirname $wmlrc_dir;
		last if  length( $wmlrc_dir ) < 3
1210
	}
1211

1212 1213 1214 1215 1216 1217
	# now read the wmlrc file to find the charset
	my $wmlrc = catfile( $wmlrc_dir,'.wmlrc' );
	if ( open( my $fd, '<', $wmlrc ) )
	{
		while ( my $line = <$fd> )
		{
1218
			next if $line =~ m{^[#%]};
1219 1220 1221 1222 1223
			next unless $line =~ m{CHARSET=(.*?)\s*$};
			$charset = $1;
			last;
		}
		close($fd);
1224
	}
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	else
	{
		verbose "wmlrc for `$file' not found; assuming $charset charset";
	}

	return $charset;
}

sub read_file_enc
{
    my $file = shift or croak("No file specified");
1236

1237 1238
	my $charset = get_file_charset( $file );

1239
	return read_file( $file, $charset );
1240
}
1241 1242

__END__