summaryrefslogtreecommitdiff
path: root/clone_build_tree.pl
blob: 8a64a44cf215d1d54540b6b03ca85aa4be459c63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#!/usr/bin/env perl
eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}'
    & eval 'exec perl -w -S $0 $argv:q'
    if 0;

# ******************************************************************
#      Author: Chad Elliott
#        Date: 4/8/2004
# Description: Clone a build tree into an alternate location.
#              This script is a rewrite of create_ace_build.pl and
#              does not restrict the user to place the build
#              in any particular location or that it be used with
#              ACE_wrappers.  Some of the functions were borrowed
#              from create_ace_build.pl, but were modified quite a
#              bit.
# ******************************************************************

# ******************************************************************
# Pragma Section
# ******************************************************************

use strict;
use Cwd;
use FileHandle;
use File::Copy;
use File::Find;
use File::Path;
use File::stat;
use File::Basename;

# ******************************************************************
# Data Section
# ******************************************************************

my $exclude;
my @foundFiles;
my $verbose = 0;
my $lbuildf = 0;
my $lnonbuildf = 0;
my $version = '1.16';

eval 'symlink("", "");';
my $hasSymlink = ($@ eq '');

# ******************************************************************
# Subroutine Section
# ******************************************************************

sub findCallback {
  my $matches = !(/^CVS\z/s && ($File::Find::prune = 1)            ||
                  /^\.svn\z/s && ($File::Find::prune = 1)          ||
                  /^\.git\z/s && ($File::Find::prune = 1)          ||
                  defined $exclude &&
                  /^$exclude\z/s && ($File::Find::prune = 1)       ||
                  /^\.cvsignore\z/s && ($File::Find::prune = 1)    ||
                  /^\..*obj\z/s && ($File::Find::prune = 1)        ||
                  /^Templates\.DB\z/s && ($File::Find::prune = 1)  ||
                  /^Debug\z/s && ($File::Find::prune = 1)          ||
                  /^Release\z/s && ($File::Find::prune = 1)        ||
                  /^Static_Debug\z/s && ($File::Find::prune = 1)   ||
                  /^Static_Release\z/s && ($File::Find::prune = 1)
                 );

  if ($matches) {
    if(!$lnonbuildf) {
      $matches &&= (! -l $_                  &&
                    ! ( -f $_ && /^core\z/s) &&
                    ! /^.*\.rej\z/s          &&
                    ! /^.*\.state\z/s        &&
                    ! /^.*\.so\z/s           &&
                    ! /^.*\.[oa]\z/s         &&
                    ! /^.*\.dll\z/s          &&
                    ! /^.*\.lib\z/s          &&
                    ! /^.*\.obj\z/s          &&
                    ! /^.*~\z/s              &&
                    ! /^\.\z/s               &&
                    ! /^\.#.*\z/s            &&
                    ! /^.*\.ncb\z/s          &&
                    ! /^.*\.opt\z/s          &&
                    ! /^.*\.bak\z/s          &&
                    ! /^.*\.suo\z/s          &&
                    ! /^.*\.ilk\z/s          &&
                    ! /^.*\.pdb\z/s          &&
                    ! /^.*\.pch\z/s          &&
                    ! /^.*\.log\z/s          &&
                    ! ( -f $_ && /^.*\.d\z/s )
                   );
    }

    if ($matches) {
      if (!$lbuildf) {
        $matches = (! /^.*\.dsp\z/s        &&
                    ! /^.*\.dsw\z/s        &&
                    ! /^.*\.vcproj\z/s     &&
                    ! /^.*\.sln\z/s        &&
                    ! /^Makefile.*\z/s     &&
                    ! /^GNUmakefile.*\z/s  &&
                    ! /^.*\.am\z/s         &&
                    ! /^\.depend\..*\z/s   &&
                    ! /^.*\.vcn\z/s        &&
                    ! /^.*\.vcp\z/s        &&
                    ! /^.*\.vcw\z/s        &&
                    ! /^.*\.vpj\z/s        &&
                    ! /^.*\.vpw\z/s        &&
                    ! /^.*\.cbx\z/s        &&
                    ! /^.*\.bpgr\z/s       &&
                    ! /^.*\.bmak\z/s       &&
                    ! /^.*\.bmake\z/s      &&
                    ! /^.*\.mak\z/s        &&
                    ! /^.*\.nmake\z/s      &&
                    ! /^.*\.bld\z/s        &&
                    ! /^.*\.icc\z/s        &&
                    ! /^.*\.icp\z/s        &&
                    ! /^.*\.classpath\z/s  &&
                    ! /^.*\.project\z/s    &&
                    ! /^.*\.wrproject\z/s  &&
                    ! /^.*\.wrmakefile\z/s &&
                    ! /^.*\.vxtest\z/s
                  );
      }

      if ($matches) {
        ## Remove the beginning dot slash as we save the file
        push(@foundFiles, $File::Find::name);
        $foundFiles[$#foundFiles] =~ s/^\.[\\\/]+//;
      }
    }
  }
}


sub getFileList {
  File::Find::find({wanted => \&findCallback}, '.');
  return \@foundFiles;
}


sub backupAndMoveModified {
  my($realpath, $linkpath) = @_;
  my $mltime   = -M $linkpath;
  my $mrtime   = -M $realpath;
  my $status   = 1;

  ## -M returns the number of days since modification.  Therefore,
  ## a smaller time means that it has been modified more recently.
  ## This is different than what stat() returns.

  ## If the hard linked file is newer than the original file, that means
  ## the link has been broken by something and needs to be "fixed".  We
  ## will back up the original file and move the modified file into it's
  ## place.
  if ($mltime < $mrtime) {
    $status = 0;

    ## Move the real file to a backup
    unlink("$realpath.bak");
    if (rename($realpath, "$realpath.bak")) {
      ## Move the linked file to the real file name
      if (move($linkpath, $realpath)) {
        $status = 1;
      }
      else {
        ## The move failed, so we will attempt to put
        ## the original file back.
        unlink($realpath);
        rename("$realpath.bak", $realpath);
      }
    }
  }
  elsif ($mltime != $mrtime || -s $linkpath != -s $realpath) {
    ## The two files are different in some way, we need to make a backup
    ## so that we don't cause a loss of data/work.
    $status = 0;
  }

  if (!$status) {
    ## We were not able to properly deal with this file.  We will
    ## attempt to preserve the modified file.
    unlink("$linkpath.bak");
    rename($linkpath, "$linkpath.bak");
  }
}


sub hardlink {
  my($realpath, $linkpath) = @_;

  if ($^O eq 'MSWin32' && ! -e $realpath) {
    ## If the real file "doesn't exist", then we need to
    ## look up the short file name.
    my $short = Win32::GetShortPathName($realpath);

    ## If we were able to find the short file name, then we need to
    ## try again.
    if (defined $short) {
      $realpath = $short;
    }
    else {
      ## This should never happen, but there appears to be a bug
      ## with the underlying Win32 APIs on Windows Server 2003.
      ## Long paths will cause an error which perl will ignore.
      ## Unicode versions of the APIs seem to work fine.
      ## To experiment try Win32 _fullpath() and CreateHardLink with
      ## long paths.
      print "WARNING: Skipping $realpath.\n";
      return 1;
    }
  }

  return link($realpath, $linkpath);
}


sub symlinkFiles {
  my($files, $fullbuild, $dmode, $startdir, $absolute) = @_;
  my $sdlength = length($startdir) + 1;
  my $partial  = ($absolute ? undef :
                              substr($fullbuild, $sdlength,
                                     length($fullbuild) - $sdlength));

  foreach my $file (@$files) {
    my $fullpath = "$fullbuild/$file";
    if (-e $fullpath) {
      ## We need to make sure that we're not attempting to mix hardlinks
      ## and softlinks.
      if (! -d $fullpath && ! -l $fullpath) {
        my $stat = stat($fullpath);
        if ($stat->nlink() > 1) {
          print STDERR "ERROR: Attempting to mix softlinks ",
                       "with a hardlink build.\n",
                       "$fullpath has ", $stat->nlink(), " links.\n";
          return 1;
        }
      }
    }
    else {
      if (-d $file) {
        if ($verbose) {
          print "Creating $fullpath\n";
        }
        if (!mkpath($fullpath, 0, $dmode)) {
          print STDERR "ERROR: Unable to create $fullpath\n";
          return 1;
        }
      }
      else {
        if ($absolute) {
          if ($verbose) {
            print "symlink $startdir/$file $fullpath\n";
          }
          if (!symlink("$startdir/$file", $fullpath)) {
            print STDERR "ERROR: Unable to symlink $fullpath\n";
            return 1;
          }
        }
        else {
          my $buildfile = "$partial/$file";
          my $slashcount = ($buildfile =~ tr/\///);
          my $real = ($slashcount == 0 ? './' : ('../' x $slashcount)) .
                     $file;

          print "symlink $real $fullpath\n" if ($verbose);
          if (!symlink($real, $fullpath)) {
            print STDERR "ERROR: Unable to symlink $fullpath\n";
            return 1;
          }
        }
      }
    }
  }

  ## Remove links that point to non-existent files.  The subroutine is
  ## now anonymous to avoid the "will not stay shared" warning for %dirs.
  my %dirs;
  File::Find::find({wanted => sub {
                                if (-l $_ && ! -e $_) {
                                  unlink($_);
                                  $dirs{$File::Find::dir} = 1;
                                  if ($verbose) {
                                    print "Removing $File::Find::dir/$_\n";
                                  }
                                }
                              }
                   }, $fullbuild);
  foreach my $key (keys %dirs) {
    rmdir($key);
  }
  return 0;
}


sub hardlinkFiles {
  my($files, $fullbuild, $dmode, $startdir) = @_;
  my @hardlinks;

  foreach my $file (@$files) {
    my $fullpath = "$fullbuild/$file";
    if (-d $file) {
      if (! -e $fullpath) {
        if ($verbose) {
          print "Creating $fullpath\n";
        }
        if (!mkpath($fullpath, 0, $dmode)) {
          print STDERR "ERROR: Unable to create $fullpath\n";
          return 1;
        }
      }
    }
    else {
      if (-e $fullpath) {
        ## We need to make sure that we're not attempting to mix hardlinks
        ## and softlinks.
        if (-l $fullpath) {
          print STDERR "ERROR: Attempting to mix hardlinks ",
                       "with a softlink build.\n",
                       "$fullpath is a softlink.\n";
          return 1;
        }
        backupAndMoveModified($file, $fullpath);
      }
      if (! -e $fullpath) {
        if ($verbose) {
          print "hardlink $file $fullpath\n";
        }
        if (!hardlink($file, $fullpath)) {
          print STDERR "ERROR: Unable to link $fullpath\n";
          return 1;
        }
      }

      ## If we successfully linked the file or it already exists,
      ## we need to keep track of it.
      push(@hardlinks, $file);
    }
  }

  ## Remove links that point to non-existent files
  my $lfh = new FileHandle();
  my $txt = "$fullbuild/clone_build_tree.links";
  if (open($lfh, $txt)) {
    my %dirs;
    while(<$lfh>) {
      my $line = $_;
      $line =~ s/\s+$//;
      if (! -e $line) {
        my $full = "$fullbuild/$line";
        unlink($full);
        $dirs{dirname($full)} = 1;
        print "Removing $full\n" if ($verbose);
      }
    }
    close($lfh);
    foreach my $key (keys %dirs) {
      rmdir($key);
    }
  }

  ## Rewrite the link file.
  unlink($txt);
  if (open($lfh, ">$txt")) {
    foreach my $file (@hardlinks) {
      print $lfh "$file\n";
    }
    close($lfh);
  }

  return 0;
}


sub linkFiles {
  my($absolute, $dmode, $hardlink, $builddir, $builds) = @_;
  my $status    = 0;
  my $starttime = time();
  my $startdir  = getcwd();

  ## Ensure that the build directory exists and is writable
  mkpath($builddir, 0, $dmode);
  if (! -d $builddir || ! -w $builddir) {
    print STDERR "ERROR: Unable to create or write to $builddir\n";
    return 1;
  }

  ## Search for the clonable files
  print "Searching $startdir for files...\n";
  my $files = getFileList();
  my $findtime = time() - $starttime;
  print 'Found ', scalar(@$files), ' files and directories in ',
        $findtime, ' second', ($findtime == 1 ? '' : 's'), ".\n";

  foreach my $build (@$builds) {
    my $fullbuild = "$builddir/$build";

    ## Create all of the links for this build
    if (-d $fullbuild) {
      print "Updating $fullbuild\n";
    }
    else {
      print "Creating $fullbuild\n";
      mkpath($fullbuild, 0, $dmode);
    }

    if ($hardlink) {
      $status += hardlinkFiles($files, $fullbuild, $dmode, $startdir);
    }
    else {
      $status += symlinkFiles($files, $fullbuild,
                              $dmode, $startdir, $absolute);
    }
    print "Finished in $fullbuild\n";
  }

  print 'Total time: ', time() - $starttime, " seconds.\n" if ($status == 0);

  return $status;
}


sub usageAndExit {
  my $msg = shift;

  print STDERR "$msg\n" if (defined $msg);

  my $base = basename($0);
  my $spc  = ' ' x (length($base) + 8);

  print STDERR "$base v$version\n\n",
               "Create a tree identical in layout to the current directory\n",
               "with the use of ", ($hasSymlink ? "symbolic links or " : ''),
               "hard links.\n\n",
               "Usage: $base [-b <builddir>] [-d <dmode>] [-f] [-n]",
               ($hasSymlink ? "[-a] [-l] " : ''),
               "[-v]\n",
               $spc, "[build names...]\n\n",
               ($hasSymlink ?
               "-a  Use absolute paths when creating soft links.\n" .
               "-l  Use hard links instead of soft links.\n" : ''),
               "-b  Set the build directory. It defaults to the ",
               "<current directory>/build.\n",
               "-d  Set the directory permissions mode.\n",
               "-f  Link build files (Makefile, .dsw, .sln, .etc).\n",
               "-n  Link non-build files normally avoided (.o,.so, etc.).\n",
               "-s  Set the start directory. It defaults to the ",
               "<current directory>.\n",
               "-v  Enable verbose mode.\n";

  exit(0);
}


# ******************************************************************
# Main Section
# ******************************************************************

my $dmode    = 0777;
my $absolute = 0;
my $hardlink = !$hasSymlink;
my $builddir;
my @builds;
my $startdir;

for(my $i = 0; $i <= $#ARGV; ++$i) {
  if ($ARGV[$i] eq '-a') {
    $absolute = 1;
  }
  elsif ($ARGV[$i] eq '-b') {
    ++$i;
    if (defined $ARGV[$i]) {
      $builddir = $ARGV[$i];

      ## Convert backslashes to slashes
      $builddir =~ s/\\/\//g;

      ## Remove trailing slashes
      $builddir =~ s/\/+$//;

      ## Remove duplicate slashes
      while($builddir =~ s/\/\//\//g) {
      }
    }
    else {
      usageAndExit('-b requires an argument');
    }
  }
  elsif ($ARGV[$i] eq '-d') {
    ++$i;
    if (defined $ARGV[$i]) {
      $dmode = $ARGV[$i];
    }
    else {
      usageAndExit('-d requires an argument');
    }
  }
  elsif ($ARGV[$i] eq '-f') {
    $lbuildf = 1;
  }
  elsif ($ARGV[$i] eq '-l') {
    $hardlink = 1;
  }
  elsif ($ARGV[$i] eq '-n') {
    $lnonbuildf = 1;
  }
  elsif ($ARGV[$i] eq '-v') {
    $verbose = 1;
  }
  elsif ($ARGV[$i] eq '-s') {
    ++$i;
    if (defined $ARGV[$i]) {
      $startdir = $ARGV[$i];
    }
    else {
      usageAndExit('-s requires an argument');
    }
  }
  elsif ($ARGV[$i] =~ /^-/) {
    usageAndExit('Unknown option: ' . $ARGV[$i]);
  }
  else {
    push(@builds, $ARGV[$i]);
  }
}

if (defined $startdir && !chdir($startdir)) {
  print "ERROR: Unable to change directory to $startdir\n";
  exit(1);
}

$builddir = getcwd() . '/build' if (!defined $builddir);

if (index($builddir, getcwd()) == 0) {
  $exclude = substr($builddir, length(getcwd()) + 1);
  $exclude =~ s/([\+\-\\\$\[\]\(\)\.])/\\$1/g;
  $exclude =~ s/.*?([^\/]+)$/$1/;
}
else {
  $absolute = 1;
}

if (!defined $builds[0]) {
  my $cwd = getcwd();
  if (chdir($builddir)) {
    @builds = glob('*');
    chdir($cwd);
  }
  else {
    usageAndExit('There are no builds to update.');
  }
}

exit(linkFiles($absolute, $dmode, $hardlink, $builddir, \@builds));