git-svn: move canonicalization to Git::SVN::Utils
[git] / perl / Git / SVN / Utils.pm
1 package Git::SVN::Utils;
2
3 use strict;
4 use warnings;
5
6 use base qw(Exporter);
7
8 our @EXPORT_OK = qw(
9         fatal
10         can_compress
11         canonicalize_path
12         canonicalize_url
13 );
14
15
16 =head1 NAME
17
18 Git::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
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.
30
31 =head1 FUNCTIONS
32
33 All functions can be imported only on request.
34
35 =head3 fatal
36
37     fatal(@message);
38
39 Display 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.
45 sub fatal (@) { print STDERR "@_\n"; exit 1 }
46
47
48 =head3 can_compress
49
50     my $can_compress = can_compress;
51
52 Returns true if Compress::Zlib is available, false otherwise.
53
54 =cut
55
56 my $can_compress;
57 sub 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
68 Converts $path into a canonical form which is safe to pass to the SVN
69 API as a file path.
70
71 =cut
72
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;
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
97 Converts $url into a canonical form which is safe to pass to the SVN
98 API as a URL.
99
100 =cut
101
102 sub canonicalize_url {
103         my ($url) = @_;
104         $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
105         return $url;
106 }
107
108
109 1;