cmSystemTools.cxx 62 KB
Newer Older
1
2
3
4
5
6
7
8
/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile$
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Will Schroeder's avatar
Will Schroeder committed
9
10
  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
11

Will Schroeder's avatar
Will Schroeder committed
12
13
14
     This software is distributed WITHOUT ANY WARRANTY; without even 
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
     PURPOSE.  See the above copyright notices for more information.
15
16

=========================================================================*/
17
#include "cmSystemTools.h"   
18
#include "errno.h"
Andy Cedilnik's avatar
Andy Cedilnik committed
19
#include <stdio.h>
20
#include <sys/stat.h>
21
#include "cmRegularExpression.h"
Ken Martin's avatar
Ken Martin committed
22
#include <ctype.h>
Ken Martin's avatar
Ken Martin committed
23
#include "cmDirectory.h"
24
#include "cmMakefile.h"
25

26
27
28
29
30
// support for realpath call
#ifndef _WIN32
#include <limits.h>
#include <stdlib.h>
#include <sys/param.h>
31
#include <sys/wait.h>
32
33
#endif

34
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__))
35
#include <string.h>
36
#include <windows.h>
37
#include <direct.h>
Bill Hoffman's avatar
Bill Hoffman committed
38
#define _unlink unlink
39
40
41
42
inline int Mkdir(const char* dir)
{
  return _mkdir(dir);
}
43
44
45
46
47
48
inline const char* Getcwd(char* buf, unsigned int len)
{
  return _getcwd(buf, len);
}
inline int Chdir(const char* dir)
{
49
50
51
  #if defined(__BORLANDC__)
  return chdir(dir);
  #else
52
  return _chdir(dir);
53
  #endif
54
}
55
56
57
58
59
60
#else
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
inline int Mkdir(const char* dir)
{
Bill Lorensen's avatar
Bill Lorensen committed
61
  return mkdir(dir, 00777);
62
}
63
64
65
66
67
68
69
70
inline const char* Getcwd(char* buf, unsigned int len)
{
  return getcwd(buf, len);
}
inline int Chdir(const char* dir)
{
  return chdir(dir);
}
71
72
#endif

73
bool cmSystemTools::s_DisableRunCommandOutput = false;
Bill Hoffman's avatar
Bill Hoffman committed
74
bool cmSystemTools::s_ErrorOccured = false;
75
bool cmSystemTools::s_DisableMessages = false;
Bill Hoffman's avatar
Bill Hoffman committed
76

77
78
79
80
81
82
83
84
85
86
87
88
89
std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";
void cmSystemTools::SetWindows9xComspecSubstitute(const char* str)
{
  if ( str )
    {
    cmSystemTools::s_Windows9xComspecSubstitute = str;
    }
}
const char* cmSystemTools::GetWindows9xComspecSubstitute()
{
  return cmSystemTools::s_Windows9xComspecSubstitute.c_str();
}

90
91
void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&, void*);
void* cmSystemTools::s_ErrorCallbackClientData = 0;
92

93
94
95
96
// adds the elements of the env variable path to the arg passed in
void cmSystemTools::GetPath(std::vector<std::string>& path)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
97
  const char* pathSep = ";";
98
#else
99
  const char* pathSep = ":";
100
101
#endif
  std::string pathEnv = getenv("PATH");
102
103
104
  // A hack to make the below algorithm work.  
  if(pathEnv[pathEnv.length()-1] != ':')
    {
105
    pathEnv += pathSep;
106
    }
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
  std::string::size_type start =0;
  bool done = false;
  while(!done)
    {
    std::string::size_type endpos = pathEnv.find(pathSep, start);
    if(endpos != std::string::npos)
      {
      path.push_back(pathEnv.substr(start, endpos-start));
      start = endpos+1;
      }
    else
      {
      done = true;
      }
    }
122
123
124
125
126
  for(std::vector<std::string>::iterator i = path.begin();
      i != path.end(); ++i)
    {
    cmSystemTools::ConvertToUnixSlashes(*i);
    }
127
}
128

129
130
131

const char* cmSystemTools::GetExecutableExtension()
{
132
#if defined(_WIN32) || defined(__CYGWIN__)
133
134
135
136
137
138
139
  return ".exe";
#else
  return "";
#endif  
}


140
141
bool cmSystemTools::MakeDirectory(const char* path)
{
142
143
144
145
  if(cmSystemTools::FileExists(path))
    {
    return true;
    }
146
  std::string dir = path;
147
148
149
150
  if(dir.size() == 0)
    {
    return false;
    }
151
152
153
  cmSystemTools::ConvertToUnixSlashes(dir);

  std::string::size_type pos = dir.find(':');
154
155
156
157
  if(pos == std::string::npos)
    {
    pos = 0;
    }
158
  std::string topdir;
159
160
  while((pos = dir.find('/', pos)) != std::string::npos)
    {
161
    topdir = dir.substr(0, pos);
162
    Mkdir(topdir.c_str());
163
164
    pos++;
    }
165
  if(dir[dir.size()-1] == '/')
166
167
168
169
170
171
172
173
    {
    topdir = dir.substr(0, dir.size());
    }
  else
    {
    topdir = dir;
    }
  if(Mkdir(topdir.c_str()) != 0)
174
    {
175
176
    // There is a bug in the Borland Run time library which makes MKDIR
    // return EACCES when it should return EEXISTS
177
178
    // if it is some other error besides directory exists
    // then return false
179
180
181
182
183
    if( (errno != EEXIST) 
#ifdef __BORLANDC__
        && (errno != EACCES) 
#endif      
      )
184
      {
185
      cmSystemTools::Error("Faild to create directory:", path);
186
187
188
189
190
191
      return false;
      }
    }
  return true;
}

192
193
194

// replace replace with with as many times as it shows up in source.
// write the result into source.
195
196
197
198
void cmSystemTools::ReplaceString(std::string& source,
                                   const char* replace,
                                   const char* with)
{
Bill Hoffman's avatar
Bill Hoffman committed
199
  std::string::size_type lengthReplace = strlen(replace);
200
  std::string::size_type lengthWith = strlen(with);
201
  std::string rest;
Bill Hoffman's avatar
Bill Hoffman committed
202
  std::string::size_type start = source.find(replace);
203
204
  while(start != std::string::npos)
    {
205
206
    rest = source.substr(start+lengthReplace);
    source = source.substr(0, start);
207
    source += with;
208
    source += rest;
209
    start = source.find(replace, start + lengthWith );
210
211
    }
}
212

213
// Read a registry value.
214
215
216
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will return the data of the "default" value of the key
217
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
218
//      =>  will return the data of the "Root" value of the key
219

Brad King's avatar
Brad King committed
220
#if defined(_WIN32) && !defined(__CYGWIN__)
221
bool cmSystemTools::ReadRegistryValue(const char *key, std::string &value)
222
{
223

224
  std::string primary = key;
225
226
227
  std::string second;
  std::string valuename;
 
228
229
230
231
232
  size_t start = primary.find("\\");
  if (start == std::string::npos)
    {
    return false;
    }
233

234
  size_t valuenamepos = primary.find(";");
235
236
237
238
  if (valuenamepos != std::string::npos)
    {
    valuename = primary.substr(valuenamepos+1);
    }
239

240
241
  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
  
  HKEY primaryKey;
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
266
267
268
269
270
  if(RegOpenKeyEx(primaryKey, 
                  second.c_str(), 
		  0, 
                  KEY_READ, 
                  &hKey) != ERROR_SUCCESS)
271
272
273
274
275
276
277
    {
    return false;
    }
  else
    {
    DWORD dwType, dwSize;
    dwSize = 1023;
278
    char data[1024];
279
280
281
282
283
284
    if(RegQueryValueEx(hKey, 
                       (LPTSTR)valuename.c_str(), 
                       NULL, 
                       &dwType, 
                       (BYTE *)data, 
                       &dwSize) == ERROR_SUCCESS)
285
286
287
      {
      if (dwType == REG_SZ)
        {
288
        value = data;
289
290
291
292
        return true;
        }
      }
    }
293
294
  return false;
}
Brad King's avatar
Brad King committed
295
296
297
298
299
300
#else
bool cmSystemTools::ReadRegistryValue(const char *, std::string &)
{
  return false;
}
#endif
301
302
303
304
305
306
307
308
309


// Write a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will set the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will set the data of the "Root" value of the key

Brad King's avatar
Brad King committed
310
#if defined(_WIN32) && !defined(__CYGWIN__)
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
bool cmSystemTools::WriteRegistryValue(const char *key, const char *value)
{
  std::string primary = key;
  std::string second;
  std::string valuename;
 
  size_t start = primary.find("\\");
  if (start == std::string::npos)
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
  if (valuenamepos != std::string::npos)
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
  HKEY primaryKey;
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  DWORD dwDummy;
  if(RegCreateKeyEx(primaryKey, 
                    second.c_str(), 
                    0, 
                    "",
                    REG_OPTION_NON_VOLATILE,
                    KEY_WRITE,
                    NULL,
                    &hKey,
                    &dwDummy) != ERROR_SUCCESS)
    {
    return false;
    }
368
369
370
371
372
373
374

  if(RegSetValueEx(hKey, 
                   (LPTSTR)valuename.c_str(), 
                   0, 
                   REG_SZ, 
                   (CONST BYTE *)value, 
                   (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
375
    {
376
    return true;
377
    }
378
379
  return false;
}
Brad King's avatar
Brad King committed
380
381
382
383
384
385
#else
bool cmSystemTools::WriteRegistryValue(const char *, const char *)
{
  return false;
}
#endif
386
387
388
389
390
391
392
393

// Delete a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will delete the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will delete  the data of the "Root" value of the key

Brad King's avatar
Brad King committed
394
#if defined(_WIN32) && !defined(__CYGWIN__)
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
bool cmSystemTools::DeleteRegistryValue(const char *key)
{
  std::string primary = key;
  std::string second;
  std::string valuename;
 
  size_t start = primary.find("\\");
  if (start == std::string::npos)
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
  if (valuenamepos != std::string::npos)
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
  HKEY primaryKey;
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  if(RegOpenKeyEx(primaryKey, 
                  second.c_str(), 
		  0, 
                  KEY_WRITE, 
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
    if(RegDeleteValue(hKey, 
                      (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
      {
      return true;
      }
    }
  return false;
}
Brad King's avatar
Brad King committed
457
458
459
460
461
462
#else
bool cmSystemTools::DeleteRegistryValue(const char *)
{
  return false;
}
#endif
463
464
465

// replace replace with with as many times as it shows up in source.
// write the result into source.
Brad King's avatar
Brad King committed
466
#if defined(_WIN32) && !defined(__CYGWIN__)
467
468
void cmSystemTools::ExpandRegistryValues(std::string& source)
{
469
470
471
472
473
474
475
  // Regular expression to match anything inside [...] that begins in HKEY.
  // Note that there is a special rule for regular expressions to match a
  // close square-bracket inside a list delimited by square brackets.
  // The "[^]]" part of this expression will match any character except
  // a close square-bracket.  The ']' character must be the first in the
  // list of characters inside the [^...] block of the expression.
  cmRegularExpression regEntry("\\[(HKEY[^]]*)\\]");
476
477
478
479
480
481
482
  
  // check for black line or comment
  while (regEntry.find(source))
    {
    // the arguments are the second match
    std::string key = regEntry.match(1);
    std::string val;
483
    if (ReadRegistryValue(key.c_str(), val))
484
485
486
487
488
489
490
491
492
493
494
495
496
      {
      std::string reg = "[";
      reg += key + "]";
      cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
      }
    else
      {
      std::string reg = "[";
      reg += key + "]";
      cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
      }
    }
}
Brad King's avatar
Brad King committed
497
498
499
500
501
#else
void cmSystemTools::ExpandRegistryValues(std::string&)
{
}
#endif  
502

503

Ken Martin's avatar
Ken Martin committed
504
505
506
507
508
509
510
511
512
513
514
515
516
std::string cmSystemTools::EscapeQuotes(const char* str)
{
  std::string result = "";
  for(const char* ch = str; *ch != '\0'; ++ch)
    {
    if(*ch == '"')
      {
      result += '\\';
      }
    result += *ch;
    }
  return result;
}
517

518
519
bool cmSystemTools::SameFile(const char* file1, const char* file2)
{
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
551
552
553
554
555
556
557
558
559
560
#ifdef _WIN32
  HANDLE hFile1, hFile2;

  hFile1 = CreateFile( file1, 
                      GENERIC_READ, 
                      FILE_SHARE_READ ,
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS,
                      NULL
    );
  hFile2 = CreateFile( file2, 
                      GENERIC_READ, 
                      FILE_SHARE_READ, 
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS,
                      NULL
    );
  if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
    {
    if(hFile1 != INVALID_HANDLE_VALUE)
      {
      CloseHandle(hFile1);
      }
    if(hFile2 != INVALID_HANDLE_VALUE)
      {
      CloseHandle(hFile2);
      }
    return false;
    }

   BY_HANDLE_FILE_INFORMATION fiBuf1;
   BY_HANDLE_FILE_INFORMATION fiBuf2;
   GetFileInformationByHandle( hFile1, &fiBuf1 );
   GetFileInformationByHandle( hFile2, &fiBuf2 );
   CloseHandle(hFile1);
   CloseHandle(hFile2);
   return (fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
           fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
#else
561
562
563
564
565
  struct stat fileStat1, fileStat2;
  if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
    {
    // see if the files are the same file
    // check the device inode and size
566
567
    if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 && 
       memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
568
569
570
571
572
573
574
       fileStat2.st_size == fileStat1.st_size 
      ) 
      {
      return true;
      }
    }
  return false;
575
#endif
576
577
578
}


579
580
581
582
583
// return true if the file exists
bool cmSystemTools::FileExists(const char* filename)
{
  struct stat fs;
  if (stat(filename, &fs) != 0) 
584
    {
585
    return false;
586
    }
587
  else
588
    {
589
    return true;
590
    }
591
592
593
}


594
595
// Return a capitalized string (i.e the first letter is uppercased, all other
// are lowercased)
596
std::string cmSystemTools::Capitalized(const std::string& s)
597
598
599
600
601
602
603
604
605
{
  std::string n;
  n.resize(s.size());
  n[0] = toupper(s[0]);
  for (size_t i = 1; i < s.size(); i++)
    {
    n[i] = tolower(s[i]);
    }
  return n;
606
}
607
608


Bill Lorensen's avatar
Bill Lorensen committed
609
610
611
612
613
614
615
616
617
618
619
620
// Return a lower case string 
std::string cmSystemTools::LowerCase(const std::string& s)
{
  std::string n;
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
    n[i] = tolower(s[i]);
    }
  return n;
}

Bill Hoffman's avatar
Bill Hoffman committed
621
622
623
624
625
626
627
628
629
630
631
632
// Return a lower case string 
std::string cmSystemTools::UpperCase(const std::string& s)
{
  std::string n;
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
    n[i] = toupper(s[i]);
    }
  return n;
}

Bill Lorensen's avatar
Bill Lorensen committed
633

Bill Hoffman's avatar
Bill Hoffman committed
634
// convert windows slashes to unix slashes 
635
void cmSystemTools::ConvertToUnixSlashes(std::string& path)
636
{
637
638
  std::string::size_type pos = 0;
  while((pos = path.find('\\', pos)) != std::string::npos)
639
640
    {
    path[pos] = '/';
641
    pos++;
642
643
    }
  // remove any trailing slash
644
  if(path.size() && path[path.size()-1] == '/')
645
646
647
    {
    path = path.substr(0, path.size()-1);
    }
Ken Martin's avatar
Ken Martin committed
648
649
650
651
652
653
654
655
656
657

  // if there is a tilda ~ then replace it with HOME
  if(path.find("~") == 0)
    {
    if (getenv("HOME"))
      {
      path = std::string(getenv("HOME")) + path.substr(1);
      }
    }
  
658
659
660
661
662
663
  // if there is a /tmp_mnt in a path get rid of it!
  // stupid sgi's 
  if(path.find("/tmp_mnt") == 0)
    {
    path = path.substr(8);
    }
664
}
665

666
667
668

// change // to /, and escape any spaces in the path
std::string cmSystemTools::ConvertToUnixOutputPath(const char* path)
669
{
670
671
  std::string ret = path;
  
672
673
  // remove // except at the beginning might be a cygwin drive
  std::string::size_type pos = 1;
674
  while((pos = ret.find("//", pos)) != std::string::npos)
675
    {
676
    ret.erase(pos, 1);
677
    }
678
679
  // now escape spaces if there is a space in the path
  if(ret.find(" ") != std::string::npos)
680
    {
681
    std::string result = "";
682
    char lastch = 1;
683
684
    for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
      {
685
686
	// if it is already escaped then don't try to escape it again
      if(*ch == ' ' && lastch != '\\')
687
688
689
690
        {
        result += '\\';
        }
      result += *ch;
691
      lastch = *ch;
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
      }
    ret = result;
    }
  return ret;
}



std::string cmSystemTools::EscapeSpaces(const char* str)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  std::string result;
  
  // if there are spaces
  std::string temp = str;
  if (temp.find(" ") != std::string::npos && 
      temp.find("\"")==std::string::npos)
    {
    result = "\"";
    result += str;
    result += "\"";
    return result;
    }
  return str;
#else
  std::string result = "";
  for(const char* ch = str; *ch != '\0'; ++ch)
    {
    if(*ch == ' ')
      {
      result += '\\';
      }
    result += *ch;
725
    }
726
727
  return result;
#endif
728
729
}

730
std::string cmSystemTools::ConvertToOutputPath(const char* path)
731
{
732
733
734
735
736
737
738
739
740
741
742
743
#if defined(_WIN32) && !defined(__CYGWIN__)
  return cmSystemTools::ConvertToWindowsOutputPath(path);
#else
  return cmSystemTools::ConvertToUnixOutputPath(path);
#endif
}


// remove double slashes not at the start
std::string cmSystemTools::ConvertToWindowsOutputPath(const char* path)
{  
  std::string ret = path;
744
  std::string::size_type pos = 0;
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
  // first convert all of the slashes
  while((pos = ret.find('/', pos)) != std::string::npos)
    {
    ret[pos] = '\\';
    pos++;
    }
  // check for really small paths
  if(ret.size() < 2)
    {
    return ret;
    }
  // now clean up a bit and remove double slashes
  // Only if it is not the first position in the path which is a network
  // path on windows
  pos = 1; // start at position 1
  while((pos = ret.find("\\\\", pos)) != std::string::npos)
    {
    ret.erase(pos, 1);
    }
  // now double quote the path if it has spaces in it
  // and is not already double quoted
  if(ret.find(" ") != std::string::npos
     && ret[0] != '\"')
768
    {
769
770
771
    std::string result;
    result = "\"" + ret + "\"";
    ret = result;
772
    }
773
  return ret;
774
775
}

Bill Hoffman's avatar
Bill Hoffman committed
776
777
778
779
780
781
782
783
784
785
786
787
788
inline void RemoveComments(char* ptr)
{
  while(*ptr)
    {
    if(*ptr == '#')
      {
      *ptr = 0;
      break;
      }
    ++ptr;
    }
}

789
790
bool cmSystemTools::ParseFunction(std::ifstream& fin,
                                  std::string& name,
791
                                  std::vector<std::string>& arguments,
792
793
                                  const char* filename,
				  bool& parseError)
794
{
795
  parseError = false;
796
797
798
799
800
801
802
803
804
805
  name = "";
  arguments = std::vector<std::string>();
  const int BUFFER_SIZE = 4096;
  char inbuffer[BUFFER_SIZE];
  if(!fin)
    {
    return false;
    }
  if(fin.getline(inbuffer, BUFFER_SIZE ) )
    {
Bill Hoffman's avatar
Bill Hoffman committed
806
    RemoveComments(inbuffer);
807
    cmRegularExpression blankLine("^[ \t\r]*$");
Bill Hoffman's avatar
Bill Hoffman committed
808
//    cmRegularExpression comment("^[ \t]*#.*$");
809
    cmRegularExpression oneLiner("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)\\)[ \t\r]*$");
810
    cmRegularExpression multiLine("^[ \t]*([A-Za-z_0-9]*)[ \t]*\\((.*)$");
811
    cmRegularExpression lastLine("^(.*)\\)[ \t\r]*$");
812

Bill Hoffman's avatar
Bill Hoffman committed
813
814
    // check for blank line or comment
    if(blankLine.find(inbuffer) )
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
      {
      return false;
      }
    // look for a oneline fun(arg arg2) 
    else if(oneLiner.find(inbuffer))
      {
      // the arguments are the second match
      std::string args = oneLiner.match(2);
      name = oneLiner.match(1);
      // break up the arguments
      cmSystemTools::GetArguments(args, arguments);
      return true;
      }
    // look for a start of a multiline with no trailing ")"  fun(arg arg2 
    else if(multiLine.find(inbuffer))
      {
      name = multiLine.match(1);
      std::string args = multiLine.match(2);
      cmSystemTools::GetArguments(args, arguments);
      // Read lines until the closing paren is hit
      bool done = false;
      while(!done)
        {
        // read lines until the end paren is found
        if(fin.getline(inbuffer, BUFFER_SIZE ) )
          {
Bill Hoffman's avatar
Bill Hoffman committed
841
          RemoveComments(inbuffer);
842
          // Check for comment lines and ignore them.
Bill Hoffman's avatar
Bill Hoffman committed
843
          if(blankLine.find(inbuffer))
844
845
            { continue; }
          // Is this the last line?
846
847
848
849
850
851
852
853
854
855
856
857
          if(lastLine.find(inbuffer))
            {
            done = true;
            std::string args = lastLine.match(1);
            cmSystemTools::GetArguments(args, arguments);
            }
          else
            {
            std::string line = inbuffer;
            cmSystemTools::GetArguments(line, arguments);
            }
          }
858
859
	else
	  {
860
	  parseError = true;
861
862
	  cmSystemTools::Error("Parse error in read function missing end )\nIn File: ",
			       filename, "\nCurrent line:", inbuffer);
863
864
	  return false;
	  }
865
866
867
868
869
        }
      return true;
      }
    else
      {
870
      parseError = true;
871
872
      cmSystemTools::Error("Parse error in read function\nIn file:", 
                           filename, "\nCurrent line:", inbuffer);
873
874
875
876
877
878
879
880
881
      return false;
      }
    }
  return false;

}

void cmSystemTools::GetArguments(std::string& line,
                                 std::vector<std::string>& arguments)
882
{
883
  // Match a normal argument (not quoted, no spaces).
884
  cmRegularExpression normalArgument("[ \t]*(([^ \t\r\\]|[\\].)+)[ \t\r]*");
885
  // Match a quoted argument (surrounded by double quotes, spaces allowed).
886
  cmRegularExpression quotedArgument("[ \t]*(\"([^\"\\]|[\\].)*\")[ \t\r]*");
887
888
889

  bool done = false;
  while(!done)
890
    {
891
    std::string arg;
Brad King's avatar
Brad King committed
892
    std::string::size_type endpos=0;
893
894
    bool foundQuoted = quotedArgument.find(line.c_str());
    bool foundNormal = normalArgument.find(line.c_str());
895

896
897
898
    if(foundQuoted && foundNormal)
      {
      // Both matches were found.  Take the earlier one.
899
      // Favor double-quoted version if there is a tie.
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
      if(normalArgument.start(1) < quotedArgument.start(1))
        {
        arg = normalArgument.match(1);
        endpos = normalArgument.end(1);
        }
      else
        {
        arg = quotedArgument.match(1);
        endpos = quotedArgument.end(1);
        // Strip off the double quotes on the ends.
        arg = arg.substr(1, arg.length()-2);
        }
      }    
    else if (foundQuoted)
      {
      arg = quotedArgument.match(1);
      endpos = quotedArgument.end(1);
      // Strip off the double quotes on the ends.
      arg = arg.substr(1, arg.length()-2);
      }
    else if(foundNormal)
921
      {
922
923
      arg = normalArgument.match(1);
      endpos = normalArgument.end(1);
924
      }
925
    else
926
      {
927
      done = true;
928
      }
929
    if(!done)
930
      {
931
      arguments.push_back(cmSystemTools::RemoveEscapes(arg.c_str()));
932
      line = line.substr(endpos, line.length() - endpos);
933
934
935
936
      }
    }
}

937
938
939
940
941
942

std::string cmSystemTools::RemoveEscapes(const char* s)
{
  std::string result = "";
  for(const char* ch = s; *ch; ++ch)
    {
943
    if(*ch == '\\' && *(ch+1) != ';')
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
      {
      ++ch;
      switch (*ch)
        {
        case '\\': result.insert(result.end(), '\\'); break;
        case '"': result.insert(result.end(), '"'); break;
        case ' ': result.insert(result.end(), ' '); break;
        case 't': result.insert(result.end(), '\t'); break;
        case 'n': result.insert(result.end(), '\n'); break;
        case 'r': result.insert(result.end(), '\r'); break;
        case '0': result.insert(result.end(), '\0'); break;
        case '\0':
          {
          cmSystemTools::Error("Trailing backslash in argument:\n", s);
          return result;
          }
        default:
          {
          std::string chStr(1, *ch);
          cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
                               "\nin argument ", s);
          }
        }
      }
    else
      {
      result.insert(result.end(), *ch);
      }
    }
  return result;
}

976
977
void cmSystemTools::Error(const char* m1, const char* m2,
                          const char* m3, const char* m4)
978
979
980
981
982
983
984
985
986
987
{
  std::string message = "CMake Error: ";
  if(m1)
    {
    message += m1;
    }
  if(m2)
    {
    message += m2;
    }
988
989
990
991
992
993
994
995
  if(m3)
    {
    message += m3;
    }
  if(m4)
    {
    message += m4;
    }
Bill Hoffman's avatar
Bill Hoffman committed
996
  cmSystemTools::s_ErrorOccured = true;
Ken Martin's avatar
Ken Martin committed
997
998
999
  cmSystemTools::Message(message.c_str(),"Error");
}

1000

For faster browsing, not all history is shown. View entire blame