Subversion Repositories DevTools

Rev

Rev 6276 | Rev 7236 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
267 dpurdie 1
########################################################################
6177 dpurdie 2
# COPYRIGHT - VIX IP PTY LTD ("VIX"). ALL RIGHTS RESERVED.
267 dpurdie 3
#
4
# Module name   : jats.sh
5
# Module type   : Makefile system
6
# Compiler(s)   : n/a
7
# Environment(s): jats
8
#
9
# Description   : JATS Subversion Interface Functions
10
#
11
#                 Requires a subversion client to be present on the machine
12
#                 Does require at least SubVersion 1.5
13
#                 Uses features not available in 1.4
14
#
15
#                 The package currently implements a set of functions
16
#                 There are some intentional limitations:
17
#                   1) Non recursive
18
#                   2) Errors terminate operation
19
#
20
#                 This package contains experimental argument passing
21
#                 processes. Sometimes use a hash of arguments
22
#
23
#......................................................................#
24
 
25
require 5.008_002;
26
use strict;
27
use warnings;
341 dpurdie 28
our $USER;
267 dpurdie 29
use JatsEnv;
30
 
31
package JatsSvn;
32
 
33
use JatsError;
34
use JatsSystem;
35
use JatsSvnCore qw(:All);
4185 dpurdie 36
use JatsLocateFiles;
267 dpurdie 37
 
38
use File::Path;             # Instead of FileUtils
39
use File::Basename;
40
use Cwd;
41
 
42
 
43
# automatically export what we need into namespace of caller.
44
use Exporter();
45
our (@ISA, @EXPORT, %EXPORT_TAGS, @EXPORT_OK);
46
@ISA         = qw(Exporter JatsSvnCore);
47
 
48
@EXPORT      = qw(
49
                    NewSession
50
                    NewSessionByWS
51
                    NewSessionByUrl
52
 
53
                    SvnRmView
54
                    SvnIsaSimpleLabel
55
                    SvnComment
56
 
57
                    SvnUserCmd
361 dpurdie 58
 
59
                    SvnPath2Url
369 dpurdie 60
                    SvnPaths
267 dpurdie 61
                );
62
@EXPORT_OK =  qw(
63
                );
64
 
65
%EXPORT_TAGS = (All => [@EXPORT, @EXPORT_OK]);
66
 
67
#
68
#   Global Variables
69
#
70
 
71
#-------------------------------------------------------------------------------
72
# Function        : SvnCo
73
#
74
# Description     : Create a workspace
75
#                   Can be used to extract files, without creating the
76
#                   subversion control files.
77
#
1403 dpurdie 78
# Inputs          : $self                   - Instance data
79
#                   $RepoPath               - Within the repository
80
#                   $Path                   - Local path
81
#                   Hash of Options
82
#                           export          - Bool: Export Only
2429 dpurdie 83
#                           escrow          - Bool: Less sanity testing
1403 dpurdie 84
#                           force           - Bool: Force export to overwrite
85
#                           print           - Bool: Don't print files exported
86
#                           pretext=aa      - Text: Display before operation
267 dpurdie 87
#
88
# Returns         : Nothing
89
#
90
sub SvnCo
91
{
1403 dpurdie 92
    my $self = shift;
93
    my $RepoPath = shift;
94
    my $path = shift;
95
    my %opt = @_;
2429 dpurdie 96
 
341 dpurdie 97
    Debug ("SvnCo", $RepoPath, $path);
1403 dpurdie 98
    Error ("SvnCi: Odd number of args") unless ((@_ % 2) == 0);
267 dpurdie 99
 
100
    #
1403 dpurdie 101
    #   Set some defaults
102
    #
103
    my $cmd = $opt{export} ? 'export' : 'checkout';
104
    my $print = exists $opt{print} ? $opt{print} : 1;
105
    $self->{CoText} =  $opt{pretext} || 'Extracting';
106
 
2429 dpurdie 107
    #   Define RE to be used to test extraction
108
    #       Bad news: Some Cots packages have /tags/
109
    #       Kludge  : Allow /tags/ in escrow mode
1403 dpurdie 110
    #
6276 dpurdie 111
#    $self->{CoRe} = '((/)(tags|branches|trunk)(/|$))';
112
#    $self->{CoRe} =~ s~tags\|~~ if ( $opt{escrow} );
113
    $self->{CoRe} = '((/)(branches|trunk)(/|$))';
2429 dpurdie 114
 
115
    #
267 dpurdie 116
    #   Ensure that the output path does not exist
117
    #   Do not allow the user to create a local work space
118
    #   where one already exists
119
    #
120
    Error ("SvnCo: No PATH specified" ) unless ( $path );
1403 dpurdie 121
    Error ("SvnCo: Target path already exists", "Path: " . $path ) if ( ! $opt{force} && -e $path  );
267 dpurdie 122
 
123
    #
124
    #   Build up the command line
125
    #
1403 dpurdie 126
    my @args = $cmd;
267 dpurdie 127
    push @args, qw( --ignore-externals );
1403 dpurdie 128
    push @args, qw( --force ) if ( $opt{force} );
267 dpurdie 129
    push @args, $RepoPath, $path;
130
 
131
    my @co_list;
132
    if ( $self->SvnCmd ( @args,
133
                            {
134
                                'process' => \&ProcessCo,
135
                                'data' => \@co_list,
136
                                'credentials' => 1,
137
                                'nosavedata' => 1,
1403 dpurdie 138
                                'printdata' => $print,
267 dpurdie 139
                            }
140
                       ) || @co_list )
141
    {
142
        #
143
        #   We have a checkout limitation
144
        #   Delete the workspace and then report the error
145
        #
385 dpurdie 146
        #   Note: For some reason a simple rmtree doesn't work
147
        #         Nor does glob show all the directories
148
        #
267 dpurdie 149
        Verbose2 ("Remove WorkSpace: $path");
150
        rmtree( $path, IsVerbose(3) );
385 dpurdie 151
        rmtree( $path, IsVerbose(3) );
267 dpurdie 152
        Error ("Checking out Workspace", @{$self->{ERROR_LIST}}, @co_list );
153
    }
2429 dpurdie 154
 
155
    #
156
    #   Cleanup
157
    #
158
    delete $self->{CoText};
159
    delete $self->{CoRe};
267 dpurdie 160
    return;
161
 
162
    #
163
    #   Internal routine to scan each the checkout
164
    #
165
    #   Due to the structure of a SubVersion repository it would be
166
    #   possible for a user to extract the entire repository. This is
167
    #   not good as the repo could be very very large
168
    #
169
    #   Assume that the structure of the repo is such that our
170
    #   user is not allowed to extract a directory tree that contains
171
    #   key paths - such as /tags/ as this would indicate that they are
172
    #   attempting to extract something that is not a package
173
    #
174
    #
175
    sub ProcessCo
176
    {
177
        my $self = shift;
1329 dpurdie 178
        my $data = shift;
179
 
180
        if ( $self->{PRINTDATA} )
267 dpurdie 181
        {
1329 dpurdie 182
            #
183
            #   Pretty display for user
1403 dpurdie 184
            #   Hide some noise, but not much
1329 dpurdie 185
            #
1403 dpurdie 186
            unless ( $data =~ m~^Export complete.~ )
187
            {
188
                Information1 ( $self->{CoText} . ': ' . $data);
189
            }
1329 dpurdie 190
        }
191
 
2429 dpurdie 192
        #
193
        #   Detect user attempting to checkout too much of a repo
194
        #   If the extract contains a 'key' directory then create error
195
        #
196
        #   Re is provide by caller such that $1 is the dirpath
197
        #
198
        if ( $data =~ m~$self->{CoRe}~ )
1329 dpurdie 199
        {
267 dpurdie 200
            my $bad_dir = $1;
201
            push @{$self->{ERROR_LIST}}, "Checkout does not describe the root of a package. Contains: $bad_dir";
202
            return 1;
203
        }
204
 
205
        ##
206
        ##   Limit the size of the WorkSpace
207
        ##   This limit is a bit artificial, but does attempt to
208
        ##   limit views that encompass too much.
209
        ##
210
        #if ( $#{$self->{RESULT_LIST}} > 100 )
211
        #{
212
        #    Warning ("View is too large - DEBUG USE ONLY. WILL BE REMOVED" );
213
        #    push @{$self->{ERROR_LIST}}, "View too large";
214
        #    return 1;
215
        #}
216
    }
217
}
218
 
219
#-------------------------------------------------------------------------------
1403 dpurdie 220
# Function        : SvnSwitch
221
#
222
# Description     : Switches files and directories
223
#
224
# Inputs          : $self               - Instance data
225
#                   $RepoPath           - Within the repository
226
#                   $Path               - Local path
227
#                   Options             - Options
228
#                           --NoPrint   - Don't print files exported
2054 dpurdie 229
#                           --KeepWs    - Don't delete the WorkSpace on error
1403 dpurdie 230
#
231
# Returns         : Nothing
232
#
233
sub SvnSwitch
234
{
235
    my ($self, $RepoPath, $path, @opts) = @_;
236
    my $printdata = ! grep (/^--NoPrint/, @opts );
2054 dpurdie 237
    my $keepWs = grep (/^--KeepWs/, @opts );
1403 dpurdie 238
    Debug ("SvnSwitch", $RepoPath, $path);
239
 
240
    #
241
    #   Build up the command line
242
    #
243
    my @sw_list;
244
    if ( $self->SvnCmd ( 'switch', $RepoPath, $path,
245
                            {
246
                                'process' => \&ProcessSwitch,
247
                                'data' => \@sw_list,
248
                                'credentials' => 1,
249
                                'nosavedata' => 1,
250
                                'printdata' => $printdata,
251
                            }
252
                       ) || @sw_list )
253
    {
254
        #
255
        #   We have a switch problem
256
        #   Delete the workspace and then report the error
257
        #
258
        #   Note: For some reason a simple rmtree doesn't work
259
        #         Nor does glob show all the directories
260
        #
2054 dpurdie 261
        unless ( $keepWs )
262
        {
263
            Verbose2 ("Remove WorkSpace: $path");
264
            rmtree( $path, IsVerbose(3) );
265
            rmtree( $path, IsVerbose(3) );
266
            Error ("Switch elements", @{$self->{ERROR_LIST}}, @sw_list );
267
        }
268
        Warning("Switch error: Workspace state unkwown", @{$self->{ERROR_LIST}}, @sw_list);
1403 dpurdie 269
    }
270
    return;
271
 
272
    #
273
    #   Internal routine to scan each line of the Switch output
274
    #   Use to provide a nice display
275
    #
276
    sub ProcessSwitch
277
    {
278
        my $self = shift;
279
        my $data = shift;
280
 
281
        if ( $self->{PRINTDATA} )
282
        {
283
            #
284
            #   Pretty display for user
285
            #
286
            Information1 ("Switching : $data");
287
        }
288
    }
289
}
290
 
291
#-------------------------------------------------------------------------------
267 dpurdie 292
# Function        : SvnCi
293
#
294
# Description     : Check in the specified WorkSpace
295
#
296
# Inputs          : $self           - Instance data
297
#                   A hash of named arguments
298
#                       comment     - Commit comment
379 dpurdie 299
#                       allowSame   - Allow no change to the workspace
267 dpurdie 300
#
301
# Returns         : Tag of the checkin
302
#
303
sub SvnCi
304
{
305
    my $self = shift;
306
    my %opt = @_;
307
    my $status_url;
379 dpurdie 308
    my $ws_rev;
267 dpurdie 309
 
310
    Debug ("SvnCi");
311
    Error ("SvnCi: Odd number of args") unless ((@_ % 2) == 0);
312
 
313
    #
314
    #   Validate the source path
1329 dpurdie 315
    #   Note: populates %{$self->{InfoWs}} with 'info' data
267 dpurdie 316
    #
317
    my $path = SvnValidateWs ($self, 'SvnCi');
318
 
319
    #
1329 dpurdie 320
    #   Examine %{$self->{InfoWs}}, which has the results of an 'info'
267 dpurdie 321
    #   command the locate the URL.
322
    #
323
    #   This contains the target view space
324
    #   Sanity test. Don't allow Checkin to a /tags/ area
325
    #
1329 dpurdie 326
    $status_url = $self->{InfoWs}{URL};
327
    $ws_rev = $self->{InfoWs}{Revision};
379 dpurdie 328
 
267 dpurdie 329
    Error ("SvnCi: Cannot determine Repositoty URL")
330
        unless ( $status_url );
331
 
332
    Error ("SvnCi: Not allowed to commit to a 'tags' area", "URL: $status_url")
333
        if ( $status_url =~ m~/tags(/|$)~ );
334
 
335
    #
336
    #   Commit
1329 dpurdie 337
    #   Will modify Repo, so kill the cached Info
338
    #   Will only be a real issue if we tag in the same session
267 dpurdie 339
    #
1329 dpurdie 340
    delete $self->{'InfoWs'};
341
    delete $self->{'InfoRepo'};
342
 
267 dpurdie 343
    $self->SvnCmd ( 'commit', $path
344
                    , '-m', SvnComment( $opt{'comment'}, 'Created by SvnCi' ),
345
                    , { 'credentials' => 1,
346
                        'process' => \&ProcessRevNo,
379 dpurdie 347
                        'error' => "SvnCi: Copy Error",
348
                         }
267 dpurdie 349
                        );
379 dpurdie 350
 
351
    #
352
    #   No error and no commit
353
    #   Workspace was not changed, may be allowed
354
    #
4076 dpurdie 355
    delete $self->{NoRepoChanges};
379 dpurdie 356
    if ( ! $self->{REVNO} && $opt{allowSame} )
357
    {
358
        Warning ("SvnCi: Workspace matches Repository. No commit");
359
        $self->{REVNO} = $ws_rev;
4076 dpurdie 360
        $self->{NoRepoChanges} = 1;
379 dpurdie 361
    }
362
 
267 dpurdie 363
    Error ("SvnCi: Cannot determine Revision Number", @{$self->{RESULT_LIST}})
364
        unless ( $self->{REVNO} );
365
 
366
    #
367
    #   Update the view
368
    #   Doing this so that the local view contains an up to date
369
    #   revision number. If not done, and a 'copy' is done based
370
    #   on this view then the branch information will indicate that
371
    #   the copy is based on an incorrect version.
372
    #   This can be confusing!
373
    #
374
    $self->SvnCmd ( 'update'   , $path
375
                        , '--ignore-externals'
376
                        , { 'credentials' => 1,
377
                            'error' => "SvnCi: Updating WorkSpace" }
378
                        );
379
    #
380
    #   Pass the updated revision number back to the user
381
    #
382
    $self->CalcRmReference($status_url);
379 dpurdie 383
    Message ("Commit Tag is: " . $self->{RMREF} );
267 dpurdie 384
    return $self->{RMREF} ;
385
}
386
 
387
#-------------------------------------------------------------------------------
388
# Function        : SvnCreatePackage
389
#
390
# Description     : Create a package and any associated files
391
#
392
# Inputs          : $self        - Instance data
393
#                   A hash of named arguments
1403 dpurdie 394
#                       package     - Name of the package
395
#                                     May include subdirs
396
#                       new         - True: Must not already exist
397
#                       replace     - True: Replace targets
398
#                       import      - DirTree to import
399
#                       label       - Tag for imported DirTree
400
#                       type        - Import TTB target
401
#                       printdata   - True: Print extracted files (default)
267 dpurdie 402
#
1403 dpurdie 403
#
267 dpurdie 404
# Returns         : Revision of the copy
405
#
406
sub SvnCreatePackage
407
{
408
    my $self = shift;
409
    my %opt = @_;
410
    my $target;
411
 
412
    Debug ("SvnCreatePackage", @_);
413
    Error ("Odd number of args to SvnCreatePackage") unless ((@_ % 2) == 0);
414
    my %dirs = ( 'trunk/'       => 0,
415
                 'tags/'        => 0,
416
                 'branches/'    => 0 );
417
 
418
    #
1403 dpurdie 419
    #   Sanity Tests and defaul values
267 dpurdie 420
    #
421
    my $package = $self->Full || Error ("SvnCreatePackage: No package name provided");
422
    Error ("SvnCreatePackage: Invalid import path") if ( $opt{'import'} && ! -d $opt{'import'} );
423
    Error ("SvnCreatePackage: Tag without Import") if ( $opt{'label'} && ! $opt{'import'} );
424
    $opt{'label'} = SvnIsaSimpleLabel( $opt{'label'} ) if (  $opt{'label'} );
1403 dpurdie 425
    $opt{'printdata'} = 1 unless ( exists $opt{'printdata'} );
267 dpurdie 426
 
427
    #
428
    #   Package path cannot contain any of the keyword paths tags,trunk,branches
429
    #   as this would place a package with a package
430
    #
431
    Error ("Package path contains a reserved word ($1)", "Path: $package")
432
        if (  $package =~ m~/(tags|branches|trunk)(/|$)~ );
433
 
434
    #
435
    #   Package path cannot be pegged, or look like one
436
    #
437
    Error ("Package name contains a Peg ($1)", "Path: $package")
438
        if ( $package =~ m~.*(@\d+)$~ );
439
 
440
    #
441
    #   Determine TTB target
1403 dpurdie 442
    #   The TTB type for branches and tags also conatins the branch or tag
267 dpurdie 443
    #
444
    $opt{'type'} = 'trunk' unless ( $opt{'type'} );
1403 dpurdie 445
    if ( $opt{'type'} =~ m~^(tags|branches|trunk)(/|$)(.*)~ ) {
446
        Error ("SvnCreatePackage: TTB type ($1) must be followed by a path element")
447
            if ( (($1 eq 'tags') or ($1 eq 'branches' )) && ! $3  );
448
        Error ('SvnCreatePackage: TTB type of trunk must not be followed by a path element: ' . $opt{'type'})
449
            if ( ($1 eq 'trunk') && $3  );
450
    } else {
451
        Error ("SvnCreatePackage: Invalid TTB Type: " . $opt{'type'} );
452
    }
267 dpurdie 453
 
454
    #
455
    #   Before we import data we must ensure that the targets do not exist
456
    #   Determine the import target(s)
457
    #
458
    my $import_target;
459
    my $copy_target;
460
 
1403 dpurdie 461
    $self->{DEVBRANCH} = 'trunk';
267 dpurdie 462
    if ( $opt{'import'} )
463
    {
464
        #
465
        #   Primary target
466
        #   trunk, branck or tag
467
        #
468
        $import_target = $package . '/' . $opt{'type'};
1403 dpurdie 469
        $self->{DEVBRANCH} = $opt{'type'} ;
267 dpurdie 470
 
471
        $self->SvnValidateTarget( 'target'    => $import_target,
472
                                  'delete'    => $opt{'replace'},
473
                                  'available' => 1 );
474
 
475
        #
476
        #   Secondary target
1403 dpurdie 477
        #   Are we tagging the import too
267 dpurdie 478
        #
1403 dpurdie 479
        if ( $opt{'label'} )
267 dpurdie 480
        {
481
            $copy_target = $package . '/tags/' . $opt{'label'};
482
            $self->SvnValidateTarget( 'target'    => $copy_target,
483
                                      'delete'    => $opt{'replace'},
484
                                      'available' => 1 );
485
        }
486
    }
487
 
488
    #
489
    #   Probe to see if the package exists
490
    #
491
    my ( $ref_files, $ref_dirs, $ref_svn, $found ) = $self->SvnScanPath ( 'SvnCreatePackage', $package );
492
    if ( @$ref_dirs )
493
    {
494
        Error ("SvnCreatePackage: Package directory exists",
495
               "Cannot create a package here. Unexpected subdirectories:", @$ref_dirs);
496
    }
497
 
498
    if ( @$ref_files )
499
    {
500
        Warning ("SvnCreatePackage: Unexpected files found",
501
               "Path: $package",
502
               "Unexpected files found: @$ref_files");
503
    }
504
 
4094 dpurdie 505
    #
506
    #   Check sanity of the users source directory - if importing
507
    #   The following directories are not allowed
508
    #       .svn - attempting to import an svn workspace
509
    #       tags, trunk, branches - attempt to import directory with reserved names
510
    #       .git, .hg, .cvs  - other  version control systems
511
    #
512
    if ( $import_target )
513
    {
514
        my $search = JatsLocateFiles->new("--Recurse=1",
515
                                           "--DirsOnly", 
516
                                           "--FullPath",
517
                                           "--FilterIn=.svn",
518
                                           "--FilterIn=.git",
519
                                           "--FilterIn=.hg",
520
                                           "--FilterIn=.cvs",
521
                                           "--FilterIn=tags",
522
                                           "--FilterIn=trunk",
523
                                           "--FilterIn=branches",
524
                                           );
525
        my @badDirs = $search->search($opt{'import'});
526
        if (@badDirs)
527
        {
528
            Error("SvnCreatePackage: Invalid directories found within imported source tree:", @badDirs);
529
        }
530
    }
531
 
267 dpurdie 532
    if ( @$ref_svn )
533
    {
534
        #
535
        #   Do we need a new one
536
        #
537
        Error ("SvnCreatePackage: Package exists: $package") if $opt{'new'};
538
 
539
        #
540
        #   Some subversion files have been found here
541
        #   Create the rest
542
        #   Assume that the directory tree is good
543
        #
544
        #
545
        #   Some, or all, of the required package subdirectories exist
546
        #   Determine the new ones to created so that it can be done
547
        #   in an atomic step
548
        #
549
        delete $dirs{$_} foreach  ( @$ref_svn );
550
        if ( keys %dirs )
551
        {
552
            Warning ("SvnCreatePackage: Not all package subdirs present",
553
                     "Remaining dirs will be created",
554
                     "Found: @$ref_svn") if @$ref_svn;
555
        }
556
        else
557
        {
558
            Warning ("SvnCreatePackage: Package already present");
559
        }
560
    }
561
    #
562
    #   Create package directories that have not been discovered
563
    #       trunk
564
    #       branches
565
    #       tags
566
    #
567
    my @dirs;
568
    push @dirs, $package . '/' . $_ foreach ( keys %dirs );
569
    $target = $package . '/trunk';
570
 
571
    #
572
    #   Create missing directories - if any
573
    #
574
    if ( @dirs )
575
    {
576
        $self->SvnCmd ('mkdir', @dirs
379 dpurdie 577
                       , '-m', $self->Path() . ': Created by SvnCreatePackage'
267 dpurdie 578
                       , '--parents'
385 dpurdie 579
                       , { 'credentials' => 1
580
                           ,'error' => "SvnCreatePackage"
581
                           ,'process' => \&ProcessRevNo
582
                         } );
267 dpurdie 583
    }
584
 
585
    #
586
    #   Import data into the package if required
587
    #   Import data. Possible cases:
588
    #       - Import to trunk - and then tag it
589
    #       - Import to branches
590
    #       - Import to tags
591
    #
592
    if ( $import_target )
593
    {
594
        Verbose ("Importing directory into new package: $opt{'import'}");
595
 
596
        $target = $import_target;
1403 dpurdie 597
        $self->{PRINTDATA} = $opt{'printdata'};
267 dpurdie 598
        $self->SvnCmd ('import', $opt{'import'}
599
                        , $target
600
                        , '-m', 'Import by SvnCreatePackage'
601
                        , '--force'
602
                        , { 'credentials' => 1
603
                           ,'error' => "Import Incomplete"
604
                           ,'process' => \&ProcessRevNo
1403 dpurdie 605
                           ,'printdata' => $opt{'printdata'}
267 dpurdie 606
                          })
607
    }
608
 
609
    #
610
    #   If imported to the trunk AND a label is provided
611
    #   then tag the import as well.
612
    #   A simple URL copy
613
    #
614
    if ( $copy_target )
615
    {
616
        Verbose ("Labeling imported trunk: $opt{'label'} ");
617
        $target = $copy_target;
618
        $self->SvnCmd ('copy'  , $import_target
619
                        , $target
620
                        , '-m', 'Import tagged by SvnCreatePackage'
621
                        , { 'credentials' => 1
622
                          , 'process' => \&ProcessRevNo
623
                          , 'error' => "Import Incomplete" } );
624
    }
625
 
626
    #
1403 dpurdie 627
    #   If we have done very little then we won't know the version
628
    #   of the repo. Need to force it
629
    #
630
    unless ( $self->{REVNO} || $self->{WSREVNO} )
631
    {
632
        $self->SvnInfo( $package, 'InfoRepo' );
633
        $self->{REVNO}  = $self->{'InfoRepo'}{'Last Changed Rev'} || Error ("SvnCreatePackage: Bad info for Repository");
634
    }
635
 
636
 
637
    #
267 dpurdie 638
    #   Pass the updated revision number back to the user
639
    #
640
    $self->CalcRmReference($target);
1403 dpurdie 641
    Message ("Create Package Rm Ref : " . $self->RmRef);
642
    Message ("Create Package Vcs Tag: " . $self->SvnTag);
267 dpurdie 643
    return $self->{RMREF} ;
644
}
645
 
646
#-------------------------------------------------------------------------------
647
# Function        : SvnRmView
648
#
649
# Description     : Remove a Subversion view
650
#                   Will run sanity checks and only remove the view if
651
#                   all is well
652
#
653
# Inputs          : A hash of named arguments
654
#                       path     - Path to local workspace
655
#                       modified - Array of files that are allowed to be modified
656
#                       force    - True: Force deletion
657
#
658
# Returns         :
659
#
660
sub SvnRmView
661
{
662
    my %opt = @_;
663
    Debug ("SvnRmView");
664
    Error ("Odd number of args to SvnRmView") unless ((@_ % 2) == 0);
665
 
666
    #
667
    #   Sanity test
668
    #
669
    my $path = $opt{'path'} || '';
670
    my $path_length = length ($path);
671
    Verbose2 ("Delete WorkSpace: $path");
672
 
673
    #
674
    #   If the path does not exist then assume that its already deleted
675
    #
676
    unless ( $path && -e $path )
677
    {
678
        Verbose2 ("SvnRmView: Path does not exist");
679
        return;
680
    }
681
 
682
    #
683
    #   Create information about the workspace
684
    #   This will also validate the path
685
    #
361 dpurdie 686
    my $session = NewSessionByWS ( $path, 0, 1 );
267 dpurdie 687
 
688
    #
689
    #   Validate the path
690
    #
691
    $session->SvnValidateWs ($path, 'SvnRmView');
692
 
693
    #
694
    #   Ask subversion if there are any files to be updated
695
    #   Prevent deletion of a view that has modified files
696
    #
697
    unless ( $opt{'force'} )
698
    {
699
        $session->SvnWsModified ( 'cmd' => 'SvnRmView', %opt );
700
    }
701
 
702
    #
703
    #   Now we can delete it
704
    #
705
    Verbose2 ("Remove WorkSpace: $path");
706
    rmtree( $path, IsVerbose(3) );
707
}
708
 
709
 
710
#-------------------------------------------------------------------------------
711
# Function        : SvnCopyWs
712
#
713
# Description     : Copy a workspace to a new place in the repository
714
#                   Effectively 'label' the workspace
715
#
716
#                   It would appear that the 'copy' command is very clever
717
#                   If a version-controlled file has been changed
718
#                   in the source workspace, then it will automatically be
719
#                   copied. This is a trap.
720
#
721
#                   Only allow a 'copy' if there are no modified
722
#                   files in the work space (unless overridden)
723
#
1329 dpurdie 724
#                   Only allow a 'copy' if the local workspace is
725
#                   up to date with respect with the repo. It possible
726
#                   to do a 'commit' and then a 'copy' (tag) and have
727
#                   unexpected results as the workspace has not been
728
#                   updated. This is a trap.
267 dpurdie 729
#
1329 dpurdie 730
#
267 dpurdie 731
# Inputs          : $self        - Instance data
732
#                   A hash of named arguments
733
#                       path     - Path to local workspace
734
#                       target   - Location within the repository to copy to
735
#                       comment  - Commit comment
736
#                       modified - Array of files that are allowed to
737
#                                  be modified in the workspace.
385 dpurdie 738
#                       noswitch        - True: Don't switch to the new URL
739
#                       replace         - True: Delete existing tag if present
740
#                       allowLocalMods  - True: Allow complex tagging
1403 dpurdie 741
#                       noupdatecheck   - True: Do not check that the WS is up to date
267 dpurdie 742
#
743
# Returns         : Revision of the copy
744
#
745
sub SvnCopyWs
746
{
747
    my $self = shift;
748
    my %opt = @_;
385 dpurdie 749
    my $rv;
267 dpurdie 750
    Debug ("SvnCopyWs");
751
    Error ("Odd number of args to SvnCopyWs") unless ((@_ % 2) == 0);
752
    Error ("SvnCopyWs: No Workspace" ) unless ( $self->{WS} );
753
 
754
    #
755
    #   Insert defaults
756
    #
757
    my $target = $opt{target} || Error ("SvnCopyWs: Target not specified" );
758
 
759
    #
760
    #   Validate the source path
761
    #
762
    my $path = SvnValidateWs ($self, 'SvnCopyWs');
763
 
764
    #
765
    #   Validate the target
766
    #   Cannot have a 'peg'
767
    #
768
    Error ("SvnCopyWs: Target contains a Peg: ($1)", $target)
769
        if ( $target =~ m~(@\d+)\s*$~ );
770
 
771
    #
1329 dpurdie 772
    #   Ensure the Workspace is up to date
773
    #       Determine the state of the Repo and the Workspace
774
    #
1403 dpurdie 775
    unless ( $opt{noupdatecheck} )
776
    {
777
        $self->SvnInfo( $self->{WS} , 'InfoWs' );
778
        $self->SvnInfo( $self->FullWs, 'InfoRepo' );
1329 dpurdie 779
 
5315 dpurdie 780
        my $wsLastChangedRev = $self->{'InfoWs'}{'Last Changed Rev'} || Error ("SvnCopyWs: Bad info for Workspace. No 'Last Changed Rev'");
781
        my $repoLastChangedRev = $self->{'InfoRepo'}{'Last Changed Rev'} || Error ("SvnCopyWs: Bad info for Repository. No 'Last Changed Rev'");
1329 dpurdie 782
 
1403 dpurdie 783
        Verbose("WS Rev  : $wsLastChangedRev");
784
        Verbose("Repo Rev: $repoLastChangedRev");
785
        Error ('SvnCopyWs: The repository has been modified since the workspace was last updated.',
786
               'Possibly caused by a commit without an update.',
787
               'Update the workspace and try again.',
788
               "Last Changed Rev. Repo: $repoLastChangedRev. Ws:$wsLastChangedRev") if ( $repoLastChangedRev > $wsLastChangedRev );
789
    }
1329 dpurdie 790
 
791
    #
267 dpurdie 792
    #   Examine the workspace and ensure that there are no modified
793
    #   files - unless they are expected
794
    #
795
    $self->SvnWsModified ( 'cmd' => 'SvnCopyWs', %opt );
385 dpurdie 796
 
267 dpurdie 797
    #
798
    #   Validate the repository
799
    #   Ensure that the target does not exist
800
    #   The target may be deleted if it exists and allowed by the user
801
    #
802
    $self->SvnValidateTarget ( 'cmd'    => 'SvnCopyWs',
803
                        'target' => $target,
804
                        'delete' => $opt{replace},
805
                        'comment' => 'Deleted by SvnCopyWs'
806
                        );
369 dpurdie 807
 
267 dpurdie 808
    #
809
    #   Copy source to destination
1329 dpurdie 810
    #   Assuming the WorkSpace is up to date then, even though the source is a
811
    #   WorkSpace, the copy does not transfer data from the WorkSpace.
812
    #   It appears as though its all done on the server. This is good - and fast.
267 dpurdie 813
    #
1329 dpurdie 814
    #   If the Workspace is not up to date, then files that SVN thinks have not
815
    #   been transferred will be transferred - hence the need to update after
816
    #   a commit.
817
    #
385 dpurdie 818
    #   Moreover, files that are modified in the local workspace will
819
    #   be copied and checked into the target, but this is not nice.
267 dpurdie 820
    #
385 dpurdie 821
    $rv = $self->SvnCmd ( 'cp'  , $path
267 dpurdie 822
                        , $target
823
                        , '--parents'
824
                        , '-m', SvnComment( $opt{'comment'}, 'Created by SvnCopyWs' ),
825
                        , { 'process' => \&ProcessRevNo,
1403 dpurdie 826
                            'credentials' => 1,
827
                            'printdata' => 1,
828
                             }
385 dpurdie 829
                        );
830
    if ($rv)
267 dpurdie 831
    {
832
        #
833
        #   Error in copy
834
        #   Attempt to delete the target. Don't worry if we can't do that
835
        #
836
        my @err1 = @{$self->{ERROR_LIST}};
837
        $self->SvnCmd ( 'delete'
838
                    , $target
839
                    , '-m', 'Deleted by SvnCopyWs after creation failure'
840
                    , { 'credentials' => 1, }
841
               );
842
        Error ("SvnCopyWs: Copy Error", @err1);
843
    }
844
 
845
    Error ("SvnCopyWs: Cannot determine Revision Number", @{$self->{RESULT_LIST}})
846
        unless ( $self->{REVNO} );
847
 
848
    Verbose2 ("Copy committed as revision: " . $self->{REVNO} );
849
 
850
    unless ( $opt{'noswitch'} )
851
    {
852
        #
853
        #   Switch to the new URL
854
        #   This will link the Workspace with the copy that we have just made
855
        #
856
        $self->SvnCmd ( 'switch', $target
857
                         , $path
858
                         , { 'credentials' => 1,
859
                             'error' => "SvnCopyWs: Cannot switch to new URL" }
860
               );
861
    }
862
 
863
    #
864
    #   Pass the updated revision number back to the user
865
    #
1403 dpurdie 866
    $self->CalcRmReference($target);
353 dpurdie 867
    #Message ("Tag is: " . $self->{RMREF} );
267 dpurdie 868
    return $self->{RMREF} ;
869
}
870
 
871
#-------------------------------------------------------------------------------
872
# Function        : SvnWsModified
873
#
874
# Description     : Test a Workspace for modified files
875
#                   Allow some files to be modified
876
#
877
# Inputs          : $self           - Instance data
878
#                   A hash of named arguments
1431 dpurdie 879
#                       path            - Path to local workspace
880
#                       modifiedRoot    - Alternate base for files
881
#                       modified        - Files that are allowed to be modified
882
#                                         Relative to the 'path' or 'modifiedRoot'
883
#                                         May be a single file or an array of files
884
#                       allowLocalMods  - Only warn about local mods
885
#                       cmd             - Command name for error reporting
267 dpurdie 886
#
887
# Returns         :
888
#
889
sub SvnWsModified
890
{
891
    my $self = shift;
892
    my %opt = @_;
893
    Debug ("SvnWsModified");
894
    Error ("Odd number of args to SvnWsModified") unless ((@_ % 2) == 0);
895
 
896
    my $cmd = $opt{'cmd'} || 'SvnWsModified';
897
 
898
    #
899
    #   Validate the path
900
    #
901
    SvnValidateWs ($self, $cmd);
902
    my $path = $self->{WS};
1431 dpurdie 903
    my $modifiedRoot = $opt{'modifiedRoot'} || $path;
904
    my $path_length = length ($modifiedRoot);
267 dpurdie 905
    Verbose2 ("Test Workspace for Modifications: $path");
906
 
907
    #
908
    #   Ask subversion if there are any files to be updated
909
    #
910
    $self->SvnCmd ('status', $path, {'error' => "Svn status command error"} );
911
 
912
    #
913
    #   Examine the list of modified files
914
    #
915
    if ( @{$self->{RESULT_LIST}} )
916
    {
917
        #
351 dpurdie 918
        #   Create a hash of files that are allowed to change
267 dpurdie 919
        #   These are files relative to the base of the view
920
        #
921
        #   The svn command has the 'path' prepended, so this
922
        #   will be removed as we process the commands
923
        #
924
        my %allowed;
925
        my @unexpected;
926
 
927
        if ( exists $opt{'modified'}  )
928
        {
929
            $allowed{'/' . $_} = 1 foreach ( ref ($opt{'modified'}) ? @{$opt{'modified'}} : $opt{'modified'}  );
930
        }
931
 
932
        #
933
        #   Process the list of modified files
934
        #   Do this even if we aren't allowed modified files as we
935
        #   still need to examine the status and kill off junk entries
936
        #   ie: ?, I, ! and ~
937
        #
938
        #    First column: Says if item was added, deleted, or otherwise changed
939
        #      ' ' no modifications
940
        #      'A' Added
941
        #      'C' Conflicted
942
        #      'D' Deleted
943
        #      'I' Ignored
944
        #      'M' Modified
945
        #      'R' Replaced
946
        #      'X' item is unversioned, but is used by an externals definition
947
        #      '?' item is not under version control
948
        #      '!' item is missing (removed by non-svn command) or incomplete
949
        #      '~' versioned item obstructed by some item of a different kind
950
        #
951
        foreach my $entry ( @{$self->{RESULT_LIST}} )
952
        {
953
            #
954
            #   Extract filename from line
351 dpurdie 955
            #       First 8 chars are status
267 dpurdie 956
            #       Remove WS path too
957
            #
1329 dpurdie 958
            if ( length $entry >= 8 + $path_length)
959
            {
960
                my $file = substr ( $entry, 8 + $path_length );
961
                next if ( $allowed{$file} );
962
            }
267 dpurdie 963
 
4287 dpurdie 964
            #   Some (older) instances of SVN compail about externals as they scan them
965
            #   Note: Don't happen if we use --xml
267 dpurdie 966
            #
4287 dpurdie 967
            if ($entry =~ m~^Performing status on external item at~)
968
            {
969
                next;
970
            }
971
 
972
            #
267 dpurdie 973
            #   Examine the first char and rule out funny things
974
            #
975
            my $f1 =  substr ($entry, 0,1 );
976
            next if ( $f1 =~ m{[?I!~]} );
977
            push @unexpected, $entry;
978
        }
385 dpurdie 979
 
980
        if ( @unexpected )
981
        {
982
            if ( $opt{allowLocalMods} ) {
983
                Message ("Workspace contains locally modified files:", @unexpected);
984
            } else {
985
                Error ("Workspace contains unexpected modified files", @unexpected);
986
            }
987
        }
267 dpurdie 988
    }
989
}
990
 
991
#-------------------------------------------------------------------------------
992
# Function        : SvnListPackages
993
#
994
# Description     : Determine a list of packages within the repo
995
#                   This turns out to be a very slow process
996
#                   so don't use it unless you really really need to
997
#
1403 dpurdie 998
# Inputs          : $self       - Instance data
999
#                   $repo       - Name of the repository
1000
#                   Last argument may be a hash of options.
1001
#                           Progress    - True: Show progress
1002
#                           Show        - >1 : display matched Tags and stats
1003
#                                         >2 : display Packages
1004
#                           Tag         - Enable Tag Matching
1005
#                                         Value is the tag to match
267 dpurdie 1006
#
1403 dpurdie 1007
# Returns         : Ref to an array of all packages
1008
#                   Ref to an array of all packahes with matched tag
267 dpurdie 1009
#
1010
sub SvnListPackages
1011
{
1403 dpurdie 1012
    #
1013
    #   Extract arguments and options
1014
    #   If last argument is a hesh, then its a hash of options
1015
    #
1016
    my $opt;
1017
    $opt = pop @_
1018
        if (@_ > 0 and UNIVERSAL::isa($_[-1],'HASH'));
267 dpurdie 1019
 
1403 dpurdie 1020
    my ($self, $repo) = @_;
1021
 
1022
    my @path_list = '';
267 dpurdie 1023
    my @list;
1403 dpurdie 1024
    my @mlist;
267 dpurdie 1025
    my $scanned = 0;
1026
    Debug ("SvnListPackages");
1027
    while ( @path_list )
1028
    {
1029
        my $path = shift @path_list;
1403 dpurdie 1030
        if ( $opt->{Progress} )
1031
        {
1032
            Message ("Reading: " . ( $path || 'RepoRoot') );
1033
        }
267 dpurdie 1034
        $scanned++;
1403 dpurdie 1035
        my ( $ref_files, $ref_dirs, $ref_svn, $found ) = $self->SvnScanPath ( 'Listing Packages', join( '/', $repo, $path) );
267 dpurdie 1036
 
1037
        #
1038
        #   If there are Subversion dirs (ttb) in this directory
1039
        #   then this is a package. Add to list
1040
        #
1041
        push @list, $path if ( @$ref_svn );
1042
 
1043
        #
1044
        #   Add subdirs to the list of paths to explore
1045
        #
1046
        foreach  ( @$ref_dirs )
1047
        {
1403 dpurdie 1048
            chop;                                   # Remove trailing '/'
1049
            push @path_list, $path ? join('/', $path , $_) : $_; # Extend the path
267 dpurdie 1050
        }
1051
    }
1052
 
1403 dpurdie 1053
    if ( $opt->{Tag} )
1054
    {
1055
        my $tag = $opt->{Tag};
1056
        foreach my $path ( sort @list )
1057
        {
1058
            Message ("Testing: $path") if ( $opt->{Progress} );
1059
            if ( $self->SvnTestPath ( 'Listing Packages', join('/', $repo, $path, 'tags', $tag) ) )
1060
            {
1061
                push @mlist, $path;
1062
            }
1063
        }
1064
    }
1065
 
1066
    if ( $opt->{Show} )
1067
    {
1068
        Message ("Found Tags:", @mlist );
1069
        Message ("Found Packages:", @list ) if  $opt->{Show} > 2;
1070
        Message ("Tags Found: " . scalar @mlist );
1071
        Message ("Packages Found: " . scalar @list );
1072
        Message ("Dirs Scanned: $scanned");
1073
    }
1074
 
1075
    return \@list, \@mlist;
267 dpurdie 1076
}
1077
 
1078
#-------------------------------------------------------------------------------
1079
# Function        : ListLabels
1080
#
1081
# Description     : List labels within a given package
1082
#
1083
# Inputs          : $self               - Instance data
1084
#                   $path               - path to label source
1085
#
1086
# Returns         : Ref to an array
1087
#
1088
sub ListLabels
1089
{
1090
    my ($self, $path) = @_;
1091
    Debug ("ListLabels");
1092
 
1093
    my ( $ref_files, $ref_dirs, $ref_svn, $found ) = $self->SvnScanPath ( 'Listing Versions', $path );
1094
 
1095
    Error ("List: Path not found: $path") unless ( $found );
1096
 
1097
    #
1098
    #   Dont report files - just directories
1099
    #
1100
    return $ref_dirs;
1101
}
1102
 
1103
 
1104
#-------------------------------------------------------------------------------
1105
# Function        : SvnLocateWsRoot
1106
#
1107
# Description     : Given a WorkSpace, determine the root of the work space
1108
#                   This is not as simple as you might think
1109
#
1110
#                   Algorithm
1111
#                       svn ls ..
1112
#                       Am I in the parent directory
1113
#                       Repeat
1114
#
369 dpurdie 1115
#                   Updates 'WS' and 'WSURL'
1116
#
267 dpurdie 1117
# Inputs          : $self               - Instance data
1118
#                   $test               - True: Don't die on error
1119
#
1120
# Returns         : Root of workspace as an absolute address
1121
#                   Will not return if there is an error
1122
#
1123
sub SvnLocateWsRoot
1124
{
1125
    my ($self, $test) = @_;
1126
    my @path;
1127
    my $path = $self->{WS};
1403 dpurdie 1128
    my $found;
7217 dpurdie 1129
    my $rv;
267 dpurdie 1130
 
1131
    Debug ("SvnLocateWsRoot");
1132
    Error ("SvnLocateWsRoot: No Workspace") unless ( $path  );
7217 dpurdie 1133
    Verbose2 ("SvnLocateWsRoot($test): Start in $path");
267 dpurdie 1134
 
1135
    #
1136
    #   Validate the source path
1137
    #
7217 dpurdie 1138
    $rv = SvnValidateWs ($self, 'SvnLocateWsRoot', $test);
1139
    if ( $test && $rv )
267 dpurdie 1140
    {
7217 dpurdie 1141
        Verbose2("SvnLocateWsRoot: Invalid path: $rv");
267 dpurdie 1142
        return undef;
1143
    }
1144
 
1145
    #
1403 dpurdie 1146
    #   Under Subversion 1.7 the process is a lot easier
267 dpurdie 1147
    #
1403 dpurdie 1148
    if ( exists $self->{'InfoWs'}{'Working Copy Root Path'} )
1149
    {
1150
        #
1151
        #   WS is now known
1152
        #
1153
        $self->{WS} = $self->{'InfoWs'}{'Working Copy Root Path'};
267 dpurdie 1154
 
1403 dpurdie 1155
        #
1156
        #   Calculate WSURL
1157
        #
2049 dpurdie 1158
        $self->{WSURL} = join('/', $self->{PKGROOT}, $self->{DEVBRANCH})
1159
            if ($self->{DEVBRANCH});
1403 dpurdie 1160
        $found = 1;
1161
    }
1162
    else
267 dpurdie 1163
    {
1403 dpurdie 1164
        # Preversion 1.7
1165
        Warning ("Using svn < 1.7. This is not recommended");
267 dpurdie 1166
 
1403 dpurdie 1167
        #
1168
        #   Need to sanitize the users path to ensure that the following
1169
        #   algorithm works. Need:
1170
        #       1) Absolute Path
1171
        #       2) Not ending in '/'
1172
        #
369 dpurdie 1173
 
267 dpurdie 1174
        #
1403 dpurdie 1175
        #   If we have a relative path then prepend the current directory
1176
        #   An absolute path is:
1177
        #           /aaa/aa/aa
1178
        #       or  c:/aaa/aa/aa
267 dpurdie 1179
        #
1403 dpurdie 1180
        $path = getcwd() . '/' . $path
1181
            unless ( $path =~ m~^/|\w:/~  );
267 dpurdie 1182
 
1183
        #
1403 dpurdie 1184
        #   Walk the bits and remove ".." directories
1185
        #       Done by pushing non-.. elements and poping last entry for .. elements.
1186
        #   Have a leading "/" which is good.
267 dpurdie 1187
        #
1403 dpurdie 1188
        #   Create a array of directories in the path
1189
        #   Split on one or more \ or / separators
267 dpurdie 1190
        #
1403 dpurdie 1191
        foreach ( split /[\\\/]+/ , $path )
267 dpurdie 1192
        {
1403 dpurdie 1193
            next if ( $_ eq '.' );
1194
            unless ( $_ eq '..' )
1195
            {
1196
                push @path, $_;
1197
            }
1198
            else
1199
            {
1200
                Error ("SvnLocateWsRoot: Bad Pathname: $path")
1201
                    if ( $#path <= 0 );
1202
                pop @path;
1203
            }
267 dpurdie 1204
        }
1205
 
1206
        #
1403 dpurdie 1207
        #   Need to adjust the WSURL too
1208
        #   Break into parts and pop them off as we go
1209
        #   Add a dummy one to allow for the first iteration
267 dpurdie 1210
        #
1403 dpurdie 1211
        my @wsurl = (split (/[\\\/]+/ , $self->{WSURL}), 'Dummy');
369 dpurdie 1212
 
1403 dpurdie 1213
        Verbose2 ("Clean absolute path elements: @path");
1214
        PATH_LOOP:
1215
        while ( @path )
1216
        {
1217
            #
1218
            #   This directory element. Append / to assist in compare
1219
            #   Determine parent path
1220
            #
1221
            my $name = pop (@path) . '/';
1222
            my $parent = join ('/', @path );
1223
            pop @wsurl;
369 dpurdie 1224
 
1403 dpurdie 1225
            #
1226
            #   Examine the parent directory
1227
            #   Get a list of all elements in the parent
1228
            #   Need to ensure that this directory is one of them
1229
            #
1230
            #   Ignore any errors - assume that they are because the
1231
            #   parent is not a part of the work space. This will terminate the
1232
            #   search.
1233
            #
1234
            $self->SvnCmd ('list', $parent, '--depth', 'immediates' );
1235
            foreach my $entry ( @{$self->{RESULT_LIST}} )
1236
            {
1237
                next PATH_LOOP
1238
                    if ( $entry eq $name );
1239
            }
1240
 
1241
            #
1242
            #   Didn't find 'dir' in directory svn listing of parent
1243
            #   This parent is not a part of the same WorkSpace as 'dir'
1244
            #   We have a winner.
1245
            #
1246
            chop $name;                         #   Chop the '/' previously added
1247
            $self->{WS} = $parent . '/' . $name;
1248
 
1249
            #
1250
            #   Reform the WSURL. Elements have been removed as we tested up the
1251
            #   path
1252
            #
1253
            $self->{WSURL} = join '/', @wsurl;
1254
            $found = 1;
1255
            last;
1256
        }
267 dpurdie 1257
    }
1258
 
1259
    #
1260
    #   Shouldn't get this far
1261
    #
1403 dpurdie 1262
    Error ("SvnLocateWsRoot: Root not found")
1263
        unless ( $found );
1264
 
1265
    #
1266
    #   Refresh Info
1267
    #   Must kill cached copy
1268
    #
1269
    delete $self->{'InfoWs'};
1270
    $self->SvnInfo($self->{WS}, 'InfoWs');
1271
    return $self->{WS};
1272
 
267 dpurdie 1273
}
1274
 
1275
#-------------------------------------------------------------------------------
1276
# Function        : SvnValidateWs
1277
#
1278
# Description     : Validate the path to a working store
1279
#
1280
# Inputs          : $self           - Instance data
1281
#                   $user           - Optional prefix for error messages
1282
#                   $test           - True: Just test, Else Error
1283
#
1284
# Returns         : Will not return if not a workspace
1285
#                   Returns the users path
1329 dpurdie 1286
#                   Populates the hash: $self->{InfoWs}
267 dpurdie 1287
#
1288
sub SvnValidateWs
1289
{
1290
    my ($self, $user, $test) = @_;
1291
    Debug ("SvnValidateWs");
1292
 
1293
    $user = "Invalid Subversion Workspace" unless ( $user );
1329 dpurdie 1294
    my $path = $self->{WS};
267 dpurdie 1295
 
1296
    #
1329 dpurdie 1297
    #   Only validate it once
267 dpurdie 1298
    #
1299
    return $path if ( $self->{WS_VALIDATED} );
1300
 
1301
    #
1302
    #   Validate the source path
1303
    #   Must exist and must be a directory
1304
    #
1305
    if ( ! $path ) {
1306
        @{$self->{ERROR_LIST}} = "$user: No path specified";
1307
 
1308
    } elsif ( ! -e $path ) {
1309
        @{$self->{ERROR_LIST}} = "$user: Path does not exist: $path";
1310
 
1311
    } elsif ( ! -d $path ) {
1312
        @{$self->{ERROR_LIST}} = "$user: Path is not a directory";
1313
    } else {
1314
        #
1315
        #   Determine the source path is an fact a view
1316
        #   The info command can do this. Use depth empty to limit the work done
1317
        #
1329 dpurdie 1318
        $self->SvnInfo($path, 'InfoWs');
267 dpurdie 1319
 
1320
        #
1321
        #   Error. Prepend nice message
1322
        #
1323
        unshift @{$self->{ERROR_LIST}}, "$user: Path is not a WorkSpace: $path"
1324
            if ( @{$self->{ERROR_LIST}} );
1325
    }
1326
 
1327
    #
1328
    #   Figure out what to do
1329
    #
1330
    if ( $test )
1331
    {
1332
        return @{$self->{ERROR_LIST}};
1333
    }
1334
    else
1335
    {
1336
        Error @{$self->{ERROR_LIST}} if @{$self->{ERROR_LIST}};
1337
        $self->{WS_VALIDATED} = 1;
1338
        return $path;
1339
    }
1340
}
1341
 
1342
#-------------------------------------------------------------------------------
1343
# Function        : SvnValidatePackageRoot
1344
#
1345
# Description     : Validate a package root
1346
#
1347
# Inputs          : $self           - Instance data
1348
#
1349
# Returns         : Will only return if valid
1350
#                   Returns a cleaned package root
1351
#
1352
sub SvnValidatePackageRoot
1353
{
379 dpurdie 1354
    my ($self, $warning_only) = @_;
267 dpurdie 1355
    Debug ("SvnValidatePackageRoot");
1356
    my $url = $self->Full || Error ("SvnValidatePackageRoot: No URL");
1357
 
1358
    Error ("Package path contains a reserved word ($self->{TAGTYPE})", "Path: $url")
1359
        if (  $self->{TAGTYPE} );
1360
 
1361
    Error ("Package name contains a Peg ($self->{PEG})", "Path: $url")
1362
        if ( $self->{PEG} );
1363
 
1364
    #
1365
    #   Ensure that the target path does exist
1366
    #   Moreover it needs to be a directory and it should have a
1367
    #   a ttb structure
1368
    #
1369
    my ( $ref_files, $ref_dirs, $ref_svn, $found ) = $self->SvnScanPath ( 'Package Base Test', $url );
1370
 
1371
    #
379 dpurdie 1372
    #   Only looking for package path
1373
    #
1374
    if ( !$found && $warning_only )
1375
    {
1376
        return $url;
1377
    }
1378
 
1379
    #
267 dpurdie 1380
    #   Examine the results to see if we have a valid package base
1381
    #
1382
    Error ("Package Base Test: Not a valid package") unless ( $found );
1383
 
1384
    #
1385
    #   Extra bits found
1386
    #   Its not the root of a package
1387
    #
1388
    if ( @$ref_files )
1389
    {
1390
        Warning ("Package Base Test: Files exists",
1391
               "Unexpected files found:", @$ref_files );
1392
    }
1393
 
1394
    #
1395
    #   Need a truck directory
1396
    #   If we don't have a truck we don't have a package
1397
    #
1398
    my $trunk_found = grep ( /trunk\//, @$ref_svn );
1399
    Error ("Invalid Package Base. Does not contain a 'trunk' directory")
1400
        unless ( $trunk_found );
1401
 
1402
    return $url;
1403
}
1404
 
1405
 
1406
#-------------------------------------------------------------------------------
1407
# Function        : SvnIsaSimpleLabel
1408
#
1409
# Description     : Check a label
1410
#                       Must not contain a PEG
1411
#                       Must not contain invalid characters (@ or /)
1412
#                       Must not contain a :: sequence (will confuse other tools)
1413
#                       Handle special label of TIMESTAMP
2429 dpurdie 1414
#                           Create a .WIP so that it can be deleted
267 dpurdie 1415
#
1416
# Inputs          : $label          - to test
1417
#
1418
# Returns         : Will not return on error
1419
#                   Returns label on success
1420
#
1421
sub SvnIsaSimpleLabel
1422
{
1423
    my ($label) = @_;
1424
    Debug ("SvnIsaSimpleLabel, $label");
1425
 
1426
    Error ("No label provided") unless ( $label );
1427
    Error ("Invalid label. Peg (\@nnn) is not allowed: \"$label\"" ) if ( $label =~ m~@\d+$~ );
1428
    Error ("Invalid label. Package Path is not allowed: \"$label\"" ) if ( $label =~ m~/~ );
383 dpurdie 1429
    Error ("Invalid label. Invalid Start Character: \"$label\"" ) unless ( $label =~ m~^[0-9a-zA-Z]~ );
1430
    Error ("Invalid label. Invalid End Character: \"$label\"" ) unless ( $label =~ m~[0-9a-zA-Z]$~ );
267 dpurdie 1431
    Error ("Invalid label. Invalid Characters: \"$label\"" ) unless ( $label =~ m~^[-.:0-9a-zA-Z_]+$~ );
1432
    Error ("Invalid label. Double :: not allowed: \"$label\"" ) if ( $label =~m~::~ );
1433
 
1434
    #
1435
    #   Allow for a label of TIMESTAMP and have it expand
383 dpurdie 1436
    #   Create a label based on users name and a date-time that can be sorted
267 dpurdie 1437
    #
1438
    if ( $label eq 'TIMESTAMP' )
1439
    {
341 dpurdie 1440
        ::EnvImport ('USER' );
1441
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
2429 dpurdie 1442
        $label = sprintf("%s_%4.4u.%2.2u.%2.2u.%2.2u%2.2u%2.2u.WIP",
341 dpurdie 1443
            $::USER, $year+1900, $mon+1, $mday, $hour, $min, $sec );
267 dpurdie 1444
    }
1445
    return $label;
1446
}
1447
 
1448
#-------------------------------------------------------------------------------
1449
# Function        : NewSession
1450
#
1451
# Description     : Create a new empty SvnSession Class
1452
#
1453
# Inputs          : None
1454
#
1455
# Returns         : Class
1456
#
1457
sub NewSession
1458
{
1459
    Debug ("NewSession");
1460
    my $self  = SvnSession();
1461
 
1462
    #
1463
    #   Document Class Variables
1464
    #
1465
    $self->{URL} = '';                  # Repo URL prefix
1466
    $self->{WS}  = '';                  # Users WorkSpace
1467
    $self->{PROTOCOL} = '';             # Named Access Protocol
1468
    $self->{PKGROOT} = '';              # Package root
1469
 
1470
    #
1471
    #   Create a class
1472
    #   Bless my self
1473
    #
1474
    bless ($self, __PACKAGE__);
1475
    return $self;
1476
}
1477
 
1478
#-------------------------------------------------------------------------------
1479
# Function        : NewSessionByWS
1480
#
1481
# Description     : Establish a new SVN Session based on a Workspace
1482
#                   Given a workspace path determine the SvnServer and other
1483
#                   relevent information.
1484
#
1485
#                   Requires some rules
1486
#                       * The package is rooted within a 'ttb'
1487
#
1488
# Inputs          : $path                   - Path to WorkSpace
1489
#                   $test                   - No Error on no WS
361 dpurdie 1490
#                   $slack                  - Less stringent
267 dpurdie 1491
#
1492
# Returns         : Ref to Session Information
1493
#
1494
sub NewSessionByWS
1495
{
361 dpurdie 1496
    my ($path, $test, $slack) = @_;
267 dpurdie 1497
    Debug ("NewSessionByWS", @_);
1498
 
1499
    #
1500
    #   Create a basic Session
1501
    #   Populate it with information that is known
1502
    #
1503
    my $self = NewSession();
1504
    $self->{WS} = $path;
1505
 
1506
    #
1507
    #   Validate the path provided
1329 dpurdie 1508
    #   In the process populate $self->{InfoWs} with info about the workspace.
267 dpurdie 1509
    #
1510
    if ($self->SvnValidateWs ( undef, 1) )
1511
    {
1512
        return $self if ( $test );
1513
        Error ( @{$self->{ERROR_LIST}} );
1514
    }
1515
 
1516
    #
1517
    #   Extract useful info
1518
    #       URL: svn://auperaws996vm21/test/MixedView/trunk
1519
    #       Repository Root: svn://auperaws996vm21/test
1520
    #
1329 dpurdie 1521
    my $url = $self->{'InfoWs'}{'URL'};
1522
    my $reporoot = $self->{'InfoWs'}{'Repository Root'};
1523
    my $repoVersion = $self->{'InfoWs'}{'Revision'};
1403 dpurdie 1524
    my $devBranch;
267 dpurdie 1525
 
1526
    Error ("JatsSvn Internal error. Can't parse info")
1527
        unless ( $url && $reporoot );
1528
 
1529
    #
1530
    #   Need the length of the path to the repository
1531
    #   but not the name of the repostory itself.
1532
    #
1533
    #   Remove that from the head of the URL to give a
1534
    #   path within the repository, that includes the repos name
1535
    #
1536
    $reporoot = (fileparse( $reporoot ))[1];
1537
    $url = substr ($url, length ($reporoot));
1538
    $self->{WSURL} = $url;
1539
    chop $reporoot;
1540
 
1541
    Verbose2 ("SvnLocatePackageRoot: $reporoot, $url" );
1542
 
1543
    #
1544
    #   Remove anything after a ttb ( truck, tags, branch ) element
4519 dpurdie 1545
    #   This will be the root of the package within the repo
267 dpurdie 1546
    #
1547
    if (  $url =~ m~(.+)/((tags|branches|trunk)(/|$).*)~ )
1548
    {
1549
        $url = $1;
1550
        $self->{WSTYPE} = $3;
1403 dpurdie 1551
        if ( $3 eq 'trunk' ) {
1552
            $devBranch = $3;
1553
        } elsif ( $3 eq 'branches' ) {
2026 dpurdie 1554
            my @bits = split('/', $2);
4519 dpurdie 1555
            $devBranch = join('/', @bits[0 .. 1]);
1403 dpurdie 1556
        }
267 dpurdie 1557
    }
1558
    else
1559
    {
361 dpurdie 1560
        #
1561
        #   If we are being slack (ie deleting the workspace)
1562
        #   Then generate a warning, not an error
1563
        #
1564
        my $fnc = $slack ? \&Warning : \&Error;
1565
        $fnc->("SvnLocatePackageRoot. Non standard repository format",
1566
               "Url must contain 'tags' or 'branches' or 'trunk'",
267 dpurdie 1567
               "Url: $url");
361 dpurdie 1568
        $self->{WSTYPE} = 'trunk';
267 dpurdie 1569
    }
1570
 
1571
    #
1572
    #   Insert known information
1573
    #
1574
    $self->{URL} = $reporoot . '/';
1575
    $self->{PKGROOT} = $url;
369 dpurdie 1576
    $self->{WSREVNO} = $repoVersion;
1403 dpurdie 1577
    $self->{DEVBRANCH} = $devBranch;
267 dpurdie 1578
 
1579
    #
1580
    #   Create useful information
1581
    #
1582
    SplitPackageUrl($self);
1583
    return $self;
1584
}
1585
 
1586
#-------------------------------------------------------------------------------
1587
# Function        : NewSessionByUrl
1588
#
1589
# Description     : Establish a new SVN Session based on a user URL
1590
#
1591
# Inputs          : $uurl                   - Users URL
361 dpurdie 1592
#                   $ttb_test               - Test and warn for TTB structure
267 dpurdie 1593
#                   $session                - Optional: Existing session
1594
#
1595
# Returns         : Ref to Session Information
1596
#
1597
sub NewSessionByUrl
1598
{
361 dpurdie 1599
    my ($uurl, $ttb_test, $self ) = @_;
267 dpurdie 1600
    Debug ("NewSessionByUrl", @_);
1601
    Error ("No Repostory Path specified") unless ( $uurl );
1602
 
1603
    #
1604
    #   Create a basic Session
1605
    #   Populate it with information that is known
1606
    #
1607
    $self = NewSession() unless ( $self );
1608
 
1609
    #
369 dpurdie 1610
    #   Examine the URL and convert a Repository Path into a URL
353 dpurdie 1611
    #   as provided by configuration information within the environment
267 dpurdie 1612
    #
361 dpurdie 1613
    ($self->{URL}, $self->{PKGROOT} ) = SvnPath2Url ($uurl);
1614
 
1615
    #
1616
    #   Create useful information
1617
    #
1618
    SplitPackageUrl($self);
1619
 
1620
    #
1621
    #   Warn of non-standard URLs
1622
    #   These may create problems latter
1623
    #
1624
    if ( $ttb_test )
1625
    {
1626
        Warning("Non standard repository format",
1627
                 "Url should contain 'tags' or 'branches' or 'trunk'",
1628
                 "Url: $self->{PKGROOT}") unless $self->{TAGTYPE};
1629
    }
1630
 
1631
    return $self;
1632
}
1633
 
1634
#-------------------------------------------------------------------------------
1635
# Function        : SvnPath2Url
1636
#
1637
# Description     : Convert a repository path to a Full Url
1638
#                   Also handles Full Url
1639
#
1640
# Inputs          : $rpath             - Repository Path
1641
#                                        May be a full URL
1642
#
1643
# Returns         : List context
1644
#                   Two items that can be joined
1645
#                   URL                - URL
1646
#                   PKG_ROOT           - Package Root
1647
#
1648
#                   Scalar context: Joined URL and Package Root
1649
#                                   Fully formed URL
1650
#
1651
sub SvnPath2Url
1652
{
1653
    my ($rpath) = @_;
1654
    my $processed = 0;
1655
    my $url;
1656
    my $pkgroot;
1657
 
1658
    #
1659
    #   Examine the argument and convert a Repository Path into a URL
1660
    #   as provided by configuration information within the environment
1661
    #
1662
    $rpath =~ m~(.+?)/(.*)~;
1663
    my $fe = $1 || $rpath;
353 dpurdie 1664
    my $rest = $2 || '';
1665
    if ( $SVN_URLS{$fe} )
267 dpurdie 1666
    {
361 dpurdie 1667
        $url = $SVN_URLS{$fe};
1668
        $pkgroot = $rest;
353 dpurdie 1669
        $processed = 1;
341 dpurdie 1670
    }
1671
 
353 dpurdie 1672
    if ( ! $processed )
341 dpurdie 1673
    {
267 dpurdie 1674
        #
353 dpurdie 1675
        #   Examine the URL and determine if we have a FULL Url or
1676
        #   a path within the 'default' server
1677
        #
1678
        foreach my $key ( @SVN_URLS_LIST )
1679
        {
361 dpurdie 1680
            if ( $rpath =~ m~^$SVN_URLS{$key}(.*)~ )
353 dpurdie 1681
            {
361 dpurdie 1682
                $url = $SVN_URLS{$key};
1683
                $pkgroot = $1;
353 dpurdie 1684
                $processed = 1;
1685
                last;
1686
            }
1687
        }
1688
    }
267 dpurdie 1689
 
353 dpurdie 1690
    #
1691
    #   Last attempt
1692
    #   Treat as a raw URL - some operations won't be allowed
1693
    #
1694
    if ( ! $processed )
267 dpurdie 1695
    {
361 dpurdie 1696
        if ( $rpath =~ m~^((file|http|https|svn):///?([^/]+)/)(.+)~ )
353 dpurdie 1697
        {
1698
            #       http://server/
1699
            #       https://server/
1700
            #       svn://server/
1701
            #       file://This/Isa/Bad/Guess
1702
            #
361 dpurdie 1703
            $url = $1;
1704
            $pkgroot = $4;
353 dpurdie 1705
        }
369 dpurdie 1706
        elsif ($SVN_URLS{''} )
353 dpurdie 1707
        {
1329 dpurdie 1708
            if ( exists $ENV{'GBE_ABT'} && $ENV{'GBE_ABT'})
1709
            {
1710
                Error ("Attempt to use default repository within automated build", "Path: " . $rpath);
1711
            }
361 dpurdie 1712
            $url = $SVN_URLS{''};
1713
            $pkgroot = $rpath;
353 dpurdie 1714
        }
1715
        else
1716
        {
1717
            #
1718
            #   User default (site configured) Repo Root
1719
            #
1720
            Error ("No site repository configured for : $fe",
1721
                   "Configure GBE_SVN_URL_" . uc($fe) );
1722
        }
267 dpurdie 1723
    }
1724
 
1725
    #
361 dpurdie 1726
    #   May want two elements, may want one
267 dpurdie 1727
    #
361 dpurdie 1728
    return $url, $pkgroot if ( wantarray );
1729
    return $url . $pkgroot;
267 dpurdie 1730
}
1731
 
369 dpurdie 1732
#-------------------------------------------------------------------------------
1733
# Function        : SvnPaths
1734
#
1735
# Description     : Extract SVN path conversion information
1736
#
1737
# Inputs          : Nothing
1738
#
1739
# Returns         : Two refs
1740
#                   Hash of SVN URLS
1741
#                   Array for search order
1742
#
1743
sub SvnPaths
1744
{
1745
    return \%SVN_URLS, \@SVN_URLS_LIST;
1746
}
361 dpurdie 1747
 
267 dpurdie 1748
#-------------------------------------------------------------------------------
1749
# Function        : SplitPackageUrl
1750
#
1403 dpurdie 1751
# Description     : Split the package URL into a few useful bits
267 dpurdie 1752
#
1753
# Inputs          : $self           - Instance data
1754
#
1755
# Returns         : Nothing
1756
#
1757
sub SplitPackageUrl
1758
{
1759
    my ($self) = @_;
353 dpurdie 1760
    Debug ("SplitPackageUrl", $self->{URL}, $self->{PKGROOT});
267 dpurdie 1761
 
1762
    #
1763
    #   Remove any protocol that may be present
1764
    #       http://server/
341 dpurdie 1765
    #       https://server/
267 dpurdie 1766
    #       svn://server/
1767
    #       file://This/Isa/Bad/Guess
1768
    #
341 dpurdie 1769
    if ( $self->{URL} =~ m~^(file|http|https|svn)://([^/]+)~ )
267 dpurdie 1770
    {
1771
        $self->{PROTOCOL} = $1;
1772
        $self->{SERVER} = $2;
1773
    }
1774
 
1775
    if ( $self->{PKGROOT} =~ m~(.*)(@\d+)$~ )
1776
    {
1777
        $self->{PEG} = $2;
1778
    }
1779
 
1780
    #
1781
    #   Determine TTB type
1782
    #   Need to handle
1783
    #       .../trunk
1784
    #       .../trunk@nnnnn
1785
    #       .../tags/version@nnnnn
1786
    #       .../branches/version@nnnnn
1787
    #
1788
    #
1789
    if (  $self->{PKGROOT} =~ m~/?(.*)/(tags|branches|trunk)(/|$|@)(.*)$~ )
1790
    {
1791
        $self->{PATH}         = $1;
1792
        $self->{TAGTYPE}      = $2;
1793
        $self->{VERSION}      = $4;
1794
    }
1795
    else
1796
    {
1797
        $self->{PATH} = $self->{PKGROOT};
1798
    }
1799
 
1800
    DebugDumpData ('SplitPackageUrl', $self ) if ( IsDebug(2) );
1801
}
1802
 
1803
#-------------------------------------------------------------------------------
1804
# Function        : Full
1805
#                   FullWs
1806
#                   Repo
1807
#                   Peg
1808
#                   Type
1809
#                   WsType
1810
#                   Path
1811
#                   Version
1812
#                   RmRef
385 dpurdie 1813
#                   RmPath
267 dpurdie 1814
#
1815
# Description     : Accessor functions
1816
#
1817
# Inputs          : $self       - Instance data
1818
#                                 self (is $_[0])
1819
#
1820
# Returns         : Data Item
1821
#
369 dpurdie 1822
sub Full        { return $_[0]->{URL} . $_[0]->{PKGROOT} ; }
1823
sub FullWs      { return $_[0]->{URL} . $_[0]->{WSURL} ; }
1824
sub FullWsRev   { return $_[0]->{URL} . $_[0]->{WSURL} . '@' . $_[0]->{WSREVNO} ; }
1403 dpurdie 1825
sub FullPath    { return $_[0]->{URL} . $_[0]->{PATH} ; }
369 dpurdie 1826
sub Peg         { return $_[0]->{PEG} ; }
1403 dpurdie 1827
sub DevBranch   { return $_[0]->{DEVBRANCH} || '' ; }
369 dpurdie 1828
sub Type        { return $_[0]->{TAGTYPE} || '' ; }
1829
sub WsType      { return $_[0]->{WSTYPE}  || '' ; }
1830
sub Path        { return $_[0]->{PATH} ; }
1831
sub Version     { return $_[0]->{VERSION} ; }
1832
sub RmRef       { return $_[0]->{RMREF} ; }
385 dpurdie 1833
sub RmPath      { my $path = $_[0]->{RMREF}; $path =~ s~@.*?$~~ ;return  $path; }
1403 dpurdie 1834
sub SvnTag      { return $_[0]->{SVNTAG} || '' ; }
267 dpurdie 1835
 
1836
#-------------------------------------------------------------------------------
1837
# Function        : Print
1838
#
1839
# Description     : Debug display the URL
1840
#
1841
# Inputs          : $self           - Instance data
1842
#                   $header
1843
#                   $indent
1844
#
1845
# Returns         : Nothing
1846
#
1847
sub Print
1848
{
1849
    my ($self, $header, $indent) = @_;
1850
    print "$header\n" if $header;
1851
    $indent = 4 unless ( defined $indent );
1852
    $indent = ' ' x $indent;
1853
 
1854
 
1403 dpurdie 1855
    print $indent . "PROTOCOL :" . $self->{PROTOCOL} . "\n";
1856
    print $indent . "SERVER   :" . $self->{SERVER} . "\n";
1857
    print $indent . "URL      :" . $self->{URL} . "\n";
1858
    print $indent . "PKGROOT  :" . $self->{PKGROOT} . "\n";
1859
    print $indent . "PATH     :" . $self->{PATH} . "\n";
1860
    print $indent . "TAGTYPE  :" . ($self->{TAGTYPE} || '') . "\n";
1861
    print $indent . "VERSION  :" . ($self->{VERSION} || '') . "\n";
1862
    print $indent . "PEG      :" . ($self->{PEG} || '') . "\n";
1863
    print $indent . "DEVBRANCH:" . ($self->{DEVBRANCH} || '') . "\n";
1864
    print $indent . "SVNTAG   :" . ($self->{SVNTAG} || '') . "\n";
1865
#    print $indent . "FULL    :" . $self->Full . "\n";
1866
 
1867
    print $indent . "Full         :" . $self->Full . "\n";
2049 dpurdie 1868
    print $indent . "FullWs       :" . $self->FullWs    . "\n";
1403 dpurdie 1869
#    print $indent . "FullWsRev    :" . $self->FullWsRev . "\n";
1870
    print $indent . "FullPath     :" . $self->FullPath  . "\n";
1871
    print $indent . "Peg          :" . $self->Peg       . "\n";
1872
    print $indent . "DevBranch    :" . $self->DevBranch . "\n";
1873
    print $indent . "Type         :" . $self->Type      . "\n";
1874
    print $indent . "WsType       :" . $self->WsType    . "\n";
1875
    print $indent . "Path         :" . $self->Path      . "\n";
1876
    print $indent . "Version      :" . $self->Version   . "\n";
1877
    print $indent . "RmRef        :" . ($self->RmRef || '') . "\n";
1878
#    print $indent . "RmPath       :" . ($self->RmPath|| '') . "\n";
267 dpurdie 1879
}
1880
 
1881
#-------------------------------------------------------------------------------
1882
# Function        : BranchName
1883
#
1884
# Description     : Create a full URL to a branch or tag based on the
1885
#                   current entry
1886
#
1887
#                   URL must have a TTB format
1888
#
1889
# Inputs          : $self           - Instance data
1890
#                   $branch         - Name of the branch
1891
#                   $type           - Optional branch type
1892
#
1893
# Returns         : Full URL name to the new branch
1894
#
1895
sub BranchName
1896
{
1897
    my ($self, $branch, $type ) = @_;
1898
    Debug ( "BranchName", $branch );
1899
 
1900
    $type = 'branches' unless ( $type );
1901
    my $root = $self->{PKGROOT};
1902
 
1903
    $root =~ s~/(tags|branches|trunk)(/|$|@).*~~;
1904
 
1905
    return $self->{URL} . $root . '/' . $type . '/' . $branch;
1906
}
1907
 
379 dpurdie 1908
#-------------------------------------------------------------------------------
1909
# Function        : setRepoProperty
1910
#
1911
# Description     : Sets a Repository property
1912
#                   This may well fail unless the Repo is setup to allow such
2429 dpurdie 1913
#                   changes and the user is allowed to make such changes
379 dpurdie 1914
#
1915
# Inputs          : $name
1916
#                   $value
1403 dpurdie 1917
#                   $allowError     - Support for bad repositories
379 dpurdie 1918
#
1403 dpurdie 1919
# Returns         : 0 - Change made
1920
#                   Will not return on error
379 dpurdie 1921
#
1922
sub setRepoProperty
1923
{
1403 dpurdie 1924
    my ($self, $name, $value, $allowError ) = @_;
1925
    my $retval = 0;
2429 dpurdie 1926
    my $rv;
1403 dpurdie 1927
 
379 dpurdie 1928
    Debug ( "setRepoProperty", $name, $value );
1929
    #
1930
    #   Ensure that the Repo version is known
1931
    #   This should be set by a previous operation
1932
    #
1933
    unless ( defined $self->{REVNO} )
1934
    {
1935
        Error ("setRepoProperty. Release Revision Number not known");
1936
    }
1937
 
2429 dpurdie 1938
 
1939
 
379 dpurdie 1940
    #
1941
    #   Execute the command
2429 dpurdie 1942
    #   Appears tp fail random;y - so try a few times
379 dpurdie 1943
    #
4076 dpurdie 1944
    #Debug ( "setRepoProperty", $name, $value, $self->{REVNO});
2429 dpurdie 1945
    for (my $ii = 0; $ii < 3; $ii++ )
1946
    {
1947
    $rv = $self->SvnCmd ( 'propset' , $name, '--revprop', '-r',  $self->{REVNO}, $value, $self->Full,
379 dpurdie 1948
                            {
1949
                                'credentials' => 1,
1950
                                'nosavedata' => 1,
1951
                            }
2429 dpurdie 1952
                       );
1953
        last unless ( $rv );
1954
        Warning("setRepoProperty: Failure attempt: $ii");
1955
DebugDumpData('setRepoProperty Failure', $self );
1956
        sleep (1);
1957
    }
1958
 
1959
    if ($rv)
379 dpurdie 1960
    {
1961
        #
1962
        #   Property NOT set
1963
        #
1403 dpurdie 1964
        if ( $allowError )
1965
        {
1966
            Warning ("setRepoProperty: $name - FAILED");
1967
            $retval = 1;
1968
        }
1969
        else
1970
        {
1971
            Error ("setRepoProperty: $name - FAILED");
1972
        }
379 dpurdie 1973
    }
1403 dpurdie 1974
 
1975
    return $retval;
379 dpurdie 1976
}
1977
 
1403 dpurdie 1978
#-------------------------------------------------------------------------------
1979
# Function        : backTrackSvnLabel
1980
#
1981
# Description     : Examine a Svn Tag and backtrack until we find the branch
1982
#                   that was used to create the label
1983
#
1984
# Inputs          : $self                   - Instance Data
1985
#                   $src_label              - Label to process
1986
#                                             Label within the current instance
1987
#                   A hash of named arguments
1988
#                       data                - Scalar ref. Hash of good stuff returned
1989
#                       printdata           - Print RAW svn data
1990
#                       onlysimple          - Do not do exhaustive scan
1991
#                       savedevbranch       - Save Dev Branch in session
2764 dpurdie 1992
#                                             Used in label clone
1403 dpurdie 1993
#
1994
# Returns         : Branch from which the label was taken
1995
#                   or the label prefixed with 'tags'.
1996
#
1997
sub backTrackSvnLabel
1998
{
1999
    my $self = shift;
2000
    my $src_label = shift;
2001
    my %opt = @_;
2002
    my $branch;
2003
 
2004
    Debug ("backTrackSvnLabel");
2005
    Error ("backTrackSvnLabel: Odd number of args") unless ((@_ % 2) == 0);
2006
 
2007
    #
2008
    #   May need to read and process data twice
2009
    #   First   - stop on copy. May it fast
2010
    #   Second  - all the log.
2011
 
2012
    #
2013
    #   extract data
2014
    #
2015
    foreach my $mode ( '--stop-on-copy', '' )
2016
    {
2017
        #   Init stored data
2018
        #   Used to communicate with callback function(s)
2019
        #
2020
        Information ("backTrackSvnLabel: Performing exhaustive search") unless $mode;
2021
        $self->{btData} = ();
2022
        $self->{btData}{results}{base} = $self->FullPath();
2023
        $self->{btData}{results}{label} = $src_label;
2024
        $self->{btData}{results}{changeSets} = 0;
2025
        $self->{btData}{results}{distance} = 0;
2026
 
2027
        #
2028
        #   Linux does not handle empty arguments in the same
2029
        #   manner as windows. Solution: pass an array
2030
        #
2031
        my @mode;
2032
        push @mode, $mode if ( $mode);
2033
        my $spath = $self->FullPath() . '/' . $src_label;
2034
 
2035
        Verbose2("backTrackSvnLabel. Log from $spath");
2036
        $self->SvnCmd ( 'log', '-v', '--xml', '-q'
2037
                        , @mode
2038
                        , $spath
2039
                        , { 'credentials' => 1,
2040
                            'process' => \&ProcessBackTrack,
2041
                            'printdata' => $opt{printdata},
2042
                            'nosavedata' => 1,
2043
                             }
2044
                            );
2045
 
2046
        last if ( $self->{btData}{good} );
2047
        last if ( $opt{onlysimple} );
2048
    }
2049
 
2050
    #
2051
    #   Did not backtrack to a branch (or trunk)
2052
    #   Return the users label
2053
    #
2054
    unless ( $self->{btData}{good} )
2055
    {
2056
        $branch = $src_label;
2057
    }
2058
    else
2059
    {
2060
        $branch = $self->{btData}{results}{devBranch};
2061
        if ( $opt{savedevbranch} )
2062
        {
2063
            $self->{btData}{results}{devBranch} =~ m~^(.*?)(@|$)~;
2064
            $self->{DEVBRANCH} = $1;
2065
        }
2066
 
2067
    }
2068
 
2069
    #
2070
    #   Return data to the user
2071
    #
2072
    if ( my $refData = $opt{data} )
2073
    {
2074
        Error ('Internal: backTrackSvnLabel. Arg to "data" must be ref to a scalar')
2075
            unless ( ref($refData) eq 'SCALAR' );
2076
        $$refData = $self->{btData}{results};
2077
    }
2078
 
2079
    #
2080
    #   Clean up the data
2081
    #
2082
    delete $self->{btData};
2083
    return $branch;
2084
}
2085
 
2086
#-------------------------------------------------------------------------------
2087
# Function        : ProcessBackTrack
2088
#
2089
# Description     :
2090
#                   Parse
2091
#                       <logentry
2092
#                          revision="24272">
2093
#                       <author>bivey</author>
2094
#                       <date>2005-07-25T15:45:35.000000Z</date>
2095
#                       <paths>
2096
#                       <path
2097
#                          prop-mods="false"
2098
#                          text-mods="false"
2099
#                          kind="dir"
2100
#                          copyfrom-path="/enqdef/branches/Stockholm"
2101
#                          copyfrom-rev="24271"
2102
#                          action="A">/enqdef/tags/enqdef_24.0.1.sls</path>
6177 dpurdie 2103
#                       </path>
1403 dpurdie 2104
#                       <msg>COTS/enqdef: Tagged by Jats Svn Import</msg>
2105
#                       </logentry>
2106
#
2107
#
2108
#                   Uses:   $self->{btData}     - Scratch Data
2109
#
2110
# Inputs          : $self           - Class Data
2111
#                   $line           - Input data to parse
2112
#
2113
# Returns         : 0 - Do not terminate input command
2114
#
2115
sub  ProcessBackTrack
2116
{
2117
    my ($self, $line ) = @_;
2118
    Message ( $line ) if $self->{PRINTDATA};
2119
 
2120
    $line =~ s~\s+$~~;
2121
    next unless ( $line );
2122
#    Debug0('', $line);
2123
 
2124
    my $workSpace =  \%{$self->{btData}};
2125
    if ( $line =~ m~<logentry$~ ) {
3045 dpurdie 2126
        #
2127
        #   Start of a logentry
2128
        #
1403 dpurdie 2129
        $workSpace->{mode} = 'l';
2130
        $workSpace->{rev} = 0;
2131
        $workSpace->{changesSeen} = 0;
2132
 
2133
    } elsif ( $line =~ m~</logentry>$~ ) {
2134
        $workSpace->{mode} = '';
2135
        #
2136
        #   End of a <logenty>
2137
        #   See if we have a result - a dev branch not copied from a tag
2138
        #
2139
        if ( exists $workSpace->{devBranch} )
2140
        {
2141
            $workSpace->{results}{distance}++;
2142
            $workSpace->{devBranch} =~ m~/((tags|branches|trunk)(/|\@).*)~;
2143
            my $devBranch = $1;
2144
 
2145
            push @{$workSpace->{results}{paths}}, $devBranch;
2146
            unless ( $devBranch =~ m ~^tags~ )
2147
            {
2148
                $workSpace->{results}{devBranch} = $devBranch;
2149
                $workSpace->{results}{isaBranch} = 1;
2150
                $workSpace->{good} = 1;
2151
                return 1;
2152
            }
2153
        }
2154
 
2155
    } elsif ( $line =~ m~<path$~ ) {
2156
        $workSpace->{mode} = 'p';
2157
        Error ('Path without Rev') unless ( $workSpace->{rev} );
2158
 
2159
    } elsif ( $line =~ m~</paths>$~ ) {
2160
        $workSpace->{mode} = '';
2161
    }
2162
    return 0 unless ( $workSpace->{mode} );
2163
 
2164
    if ( $workSpace->{mode} eq 'l' )
2165
    {
2166
        #
2167
        #   Processing logentry data
3045 dpurdie 2168
        #       Only need the revision
1403 dpurdie 2169
        #
2170
        $workSpace->{rev} = $1
2171
            if ( $line =~ m~revision=\"(\d+)\"~ );
2172
 
2173
    } elsif ( $workSpace->{mode} eq 'p' ) {
2174
        #
2175
        #   Processing Paths
2176
        #       Entries appear to be in a random order
2177
        #       Not always the same order
2178
        #
2179
        my $end = 0;
3045 dpurdie 2180
        if ( $line =~ s~\s*(.+?)="(.*)">(.*)</path>$~~ )
1403 dpurdie 2181
        {
2182
            #
2183
            #   Last entry has two items
2184
            #       Attribute
2185
            #       Data Item
2186
            #
2187
            $end = 1;
2188
            $workSpace->{path}{$1} = $2;
2189
            $workSpace->{path}{DATA} = $3;
2190
        }
2191
        elsif ($line =~ m~\s*(.*?)="(.*)"~ )
2192
        {
3045 dpurdie 2193
            #
2194
            #   Attribute
2195
            #
1403 dpurdie 2196
            $workSpace->{path}{$1} = $2;
2197
        }
2198
#        else
2199
#        {
2200
#            Warning ("Cannot decode XML log: $line");
2201
#        }
2202
 
2203
        if ( $end )
2204
        {
6177 dpurdie 2205
#DebugDumpData("AtEnd",$workSpace->{path});
1403 dpurdie 2206
            #
2207
            #   If the Repo is created by a pre 1.6 SVN, then kind will be
2208
            #   empty. Have a guess.
2209
            #
2210
            if ( $workSpace->{path}{'kind'} eq '' )
2211
            {
2212
                if ( exists $workSpace->{path}{'copyfrom-path'} ) {
2213
                    $workSpace->{path}{'kind'} = 'dir';
2214
                } else {
2215
                    $workSpace->{path}{'kind'} = 'file';
2216
                }
2217
            }
2218
 
2219
            if ( $workSpace->{path}{'kind'} eq 'dir' &&  exists $workSpace->{path}{'copyfrom-path'} )
2220
            {
2221
                my $srev = $workSpace->{path}{'copyfrom-rev'};
2222
                my $from = $workSpace->{path}{'copyfrom-path'};
3347 dpurdie 2223
                if ( $from =~ m~/trunk$~ || $from =~ m~/branches/[^/]+~ )
1403 dpurdie 2224
                {
2225
                    $workSpace->{devBranch} = $from . '@' . $srev;
2226
                }
2227
            }
2228
 
2229
            elsif ( $workSpace->{path}{'kind'} eq 'file' )
2230
            {
2231
                #
2232
                #   Track files that have been changed between tag and branch
2233
                #   The log is presented as newest first
2234
                #   The files have a tag-name component.
2235
                #       Remove the tag name - so that we can compare files
2236
                #       Save the first instance of changed files
2237
                #           Others will be in older versions
2238
                #           and thus of no interest
2239
                #
6177 dpurdie 2240
                #   Count the change sets that have changes
1403 dpurdie 2241
                #   Having changes in multiple change sets indicates
2242
                #   development on a /tags/ - which is BAD
2243
                #
2244
                $workSpace->{path}{'DATA'} =~ m~(.+)/((tags|branches|trunk)(/|$).*)~;
2245
                my $file =  $2;
2246
                my $full = $file;
2247
                $file =~ s~^tags/(.+?)/~~;
2248
 
2249
                if ( ! exists $workSpace->{files}{$file}  )
2250
                {
6177 dpurdie 2251
                    push @{$workSpace->{results}{files}}, join($;, $full . '@' . $workSpace->{rev}, $workSpace->{path}{'action'});
1403 dpurdie 2252
                }
2253
                $workSpace->{files}{$file}++;
2254
                $workSpace->{firstFile} = $file unless ( defined $workSpace->{firstFile} );
2255
 
2256
                unless ( $workSpace->{changesSeen} )
2257
                {
2258
                    unless( $workSpace->{firstFile} eq $file )
2259
                    {
2260
                        $workSpace->{results}{changeSets}++;
2261
                        $workSpace->{changesSeen}++;
2262
                    }
2263
                }
2264
 
2265
                if ( scalar keys %{$workSpace->{files}} > 1 )
2266
                {
2267
                    $workSpace->{results}{multipleChanges} = 1;
2268
                    Verbose ("backTrackSvnLabel: Changes in multiple versions");
2269
                }
2270
            }
2271
 
2272
            delete $workSpace->{path};
2273
        }
2274
    }
2275
 
2276
    #
2277
    #   Return 0 to keep on going
2278
    return 0;
2279
}
2280
 
7217 dpurdie 2281
#-------------------------------------------------------------------------------
2282
# Function        :  
2283
#
2284
# Description     : Examine the current workspace and exact information about its
2285
#                   parent.
2286
#                   
2287
#                   Does not extract the entire log history - just the last copyfrom
2288
#
2289
# Inputs          : $self
2290
#
2291
# Returns         : Nothing
2292
#                   Will add {InfoWsExtra} to the session handle
2293
#
2294
sub getWsExtraInfo
2295
{
2296
    my $self = shift;
2297
 
2298
    #
2299
    #   Determine the source of the merge
2300
    #   Create a hash entry to store working data
2301
    # 
2302
    $self->{btData} = {};
2303
    $self->SvnCmd ( 'log', '-v', '--xml', '--stop-on-copy', '--limit', '1', '-r0:HEAD', $self->{InfoWs}{Path}
2304
                    , { 'process' => \&ProcessWsExtraInfo,
2305
                         }
2306
                        );
2307
 
2308
    # Grab the first entry of the log array - should only be one
2309
    #
2310
    $self->{InfoWsExtra} = $self->{btData}{Data}[0];
2311
    delete $self->{btData};
2312
}
2313
 
2314
#-------------------------------------------------------------------------------
2315
# Function        : ProcessWsExtraInfo
2316
#
2317
# Description     :
2318
#                   Parse
2319
#                       <logentry
2320
#                          revision="24272">
2321
#                       <author>bivey</author>
2322
#                       <date>2005-07-25T15:45:35.000000Z</date>
2323
#                       <paths>
2324
#                       <path
2325
#                          prop-mods="false"
2326
#                          text-mods="false"
2327
#                          kind="dir"
2328
#                          copyfrom-path="/enqdef/branches/Stockholm"
2329
#                          copyfrom-rev="24271"
2330
#                          action="A">/enqdef/tags/enqdef_24.0.1.sls</path>
2331
#                       </paths>
2332
#                       <msg>COTS/enqdef: Tagged by Jats Svn Import</msg>
2333
#                       </logentry>
2334
#
2335
# Inputs          : 
2336
#
2337
# Returns         : 
2338
#
2339
sub  ProcessWsExtraInfo
2340
{
2341
    my ($self, $line ) = @_;
2342
    my $data = $self->{btData};
2343
    $data->{Mode} = '' unless ( defined $data->{Mode} );
2344
    return unless ( $line );
2345
#print "----- ($data->{Mode}) $line\n";
2346
 
2347
    if ( $line =~ m~^<logentry~ ) {
2348
        $data->{Item} = ();
2349
        $data->{Mode} = 'A';
2350
 
2351
    } elsif ( ($line =~ s~\s*(.+?)="(.*)">(.*)</path>$~~) && ($data->{Mode} eq 'A') ) {
2352
        #
2353
        #   Last entry has two items
2354
        #       Attribute
2355
        #       Data Item
2356
        #
2357
        $data->{Item}->{$1} = $2;
2358
        $data->{Item}->{target} = $3;
2359
 
2360
    } elsif ( ($line =~ m~\s*(.*?)="(.*)"~) && ($data->{Mode} eq 'A') ) {
2361
        #
2362
        #   Attribute
2363
        #
2364
        $data->{Item}->{$1} = $2;
2365
 
2366
    } elsif ( $line =~ m~</logentry~ ) {
2367
        $data->{Mode} = '';
2368
        if ( exists $data->{Item}->{'copyfrom-path'} )
2369
        {
2370
            #DebugDumpData("Data", $data->{Item});
2371
            push @{$data->{Data}}, $data->{Item};
2372
        }
2373
    }
2374
 
2375
    #
2376
    #   Return 0 to keep on going
2377
    return 0;
2378
}
2379
 
267 dpurdie 2380
#------------------------------------------------------------------------------
2381
1;