perl / Git / SVN / Utils.pmon commit git-svn: move canonicalization to Git::SVN::Utils (91e6e0c)
   1package Git::SVN::Utils;
   2
   3use strict;
   4use warnings;
   5
   6use base qw(Exporter);
   7
   8our @EXPORT_OK = qw(
   9        fatal
  10        can_compress
  11        canonicalize_path
  12        canonicalize_url
  13);
  14
  15
  16=head1 NAME
  17
  18Git::SVN::Utils - utility functions used across Git::SVN
  19
  20=head1 SYNOPSIS
  21
  22    use Git::SVN::Utils qw(functions to import);
  23
  24=head1 DESCRIPTION
  25
  26This module contains functions which are useful across many different
  27parts of Git::SVN.  Mostly it's a place to put utility functions
  28rather than duplicate the code or have classes grabbing at other
  29classes.
  30
  31=head1 FUNCTIONS
  32
  33All functions can be imported only on request.
  34
  35=head3 fatal
  36
  37    fatal(@message);
  38
  39Display a message and exit with a fatal error code.
  40
  41=cut
  42
  43# Note: not certain why this is in use instead of die.  Probably because
  44# the exit code of die is 255?  Doesn't appear to be used consistently.
  45sub fatal (@) { print STDERR "@_\n"; exit 1 }
  46
  47
  48=head3 can_compress
  49
  50    my $can_compress = can_compress;
  51
  52Returns true if Compress::Zlib is available, false otherwise.
  53
  54=cut
  55
  56my $can_compress;
  57sub can_compress {
  58        return $can_compress if defined $can_compress;
  59
  60        return $can_compress = eval { require Compress::Zlib; };
  61}
  62
  63
  64=head3 canonicalize_path
  65
  66    my $canoncalized_path = canonicalize_path($path);
  67
  68Converts $path into a canonical form which is safe to pass to the SVN
  69API as a file path.
  70
  71=cut
  72
  73sub canonicalize_path {
  74        my ($path) = @_;
  75        my $dot_slash_added = 0;
  76        if (substr($path, 0, 1) ne "/") {
  77                $path = "./" . $path;
  78                $dot_slash_added = 1;
  79        }
  80        # File::Spec->canonpath doesn't collapse x/../y into y (for a
  81        # good reason), so let's do this manually.
  82        $path =~ s#/+#/#g;
  83        $path =~ s#/\.(?:/|$)#/#g;
  84        $path =~ s#/[^/]+/\.\.##g;
  85        $path =~ s#/$##g;
  86        $path =~ s#^\./## if $dot_slash_added;
  87        $path =~ s#^/##;
  88        $path =~ s#^\.$##;
  89        return $path;
  90}
  91
  92
  93=head3 canonicalize_url
  94
  95    my $canonicalized_url = canonicalize_url($url);
  96
  97Converts $url into a canonical form which is safe to pass to the SVN
  98API as a URL.
  99
 100=cut
 101
 102sub canonicalize_url {
 103        my ($url) = @_;
 104        $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
 105        return $url;
 106}
 107
 108
 1091;