git-svn: move canonicalization to Git::SVN::Utils
[alt-git.git] / perl / Git / SVN / Utils.pm
blobad5351e9baa202cec74b4ff546ac030642ac1ddc
1 package Git::SVN::Utils;
3 use strict;
4 use warnings;
6 use base qw(Exporter);
8 our @EXPORT_OK = qw(
9 fatal
10 can_compress
11 canonicalize_path
12 canonicalize_url
16 =head1 NAME
18 Git::SVN::Utils - utility functions used across Git::SVN
20 =head1 SYNOPSIS
22 use Git::SVN::Utils qw(functions to import);
24 =head1 DESCRIPTION
26 This module contains functions which are useful across many different
27 parts of Git::SVN. Mostly it's a place to put utility functions
28 rather than duplicate the code or have classes grabbing at other
29 classes.
31 =head1 FUNCTIONS
33 All functions can be imported only on request.
35 =head3 fatal
37 fatal(@message);
39 Display a message and exit with a fatal error code.
41 =cut
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.
45 sub fatal (@) { print STDERR "@_\n"; exit 1 }
48 =head3 can_compress
50 my $can_compress = can_compress;
52 Returns true if Compress::Zlib is available, false otherwise.
54 =cut
56 my $can_compress;
57 sub can_compress {
58 return $can_compress if defined $can_compress;
60 return $can_compress = eval { require Compress::Zlib; };
64 =head3 canonicalize_path
66 my $canoncalized_path = canonicalize_path($path);
68 Converts $path into a canonical form which is safe to pass to the SVN
69 API as a file path.
71 =cut
73 sub 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;
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;
93 =head3 canonicalize_url
95 my $canonicalized_url = canonicalize_url($url);
97 Converts $url into a canonical form which is safe to pass to the SVN
98 API as a URL.
100 =cut
102 sub canonicalize_url {
103 my ($url) = @_;
104 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
105 return $url;