-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathastyle_main.cpp
2875 lines (2620 loc) · 92 KB
/
astyle_main.cpp
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* astyle_main.cpp
*
* Copyright (C) 2006-2011 by Jim Pattee <jimp03@email.com>
* Copyright (C) 1998-2002 by Tal Davidson
* <http://www.gnu.org/licenses/lgpl-3.0.html>
*
* This file is a part of Artistic Style - an indentation and
* reformatting tool for C, C++, C# and Java source files.
* <http://astyle.sourceforge.net>
*
* Artistic Style is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artistic Style is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artistic Style. If not, see <http://www.gnu.org/licenses/>.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
#include "astyle_main.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <errno.h>
// includes for recursive getFileNames() function
#ifdef _WIN32
#undef UNICODE // use ASCII windows functions
#include <windows.h>
#else
#include <dirent.h>
#include <sys/stat.h>
#ifdef __VMS
#include <unixlib.h>
#include <rms.h>
#include <ssdef.h>
#include <stsdef.h>
#include <lib$routines.h>
#include <starlet.h>
#endif /* __VMS */
#endif
#ifdef __DMC__
#include <locale.h>
#endif
// turn off MinGW automatic file globbing
// this CANNOT be in the astyle namespace
#ifndef ASTYLE_LIB
int _CRT_glob = 0;
#endif
namespace astyle
{
#ifdef _WIN32
char g_fileSeparator = '\\';
bool g_isCaseSensitive = false;
#else
char g_fileSeparator = '/';
bool g_isCaseSensitive = true;
#endif
// console build variables
#ifndef ASTYLE_LIB
ostream* _err = &cerr; // direct error messages to cerr
ASConsole* g_console = NULL; // class to encapsulate console variables
#endif
#ifdef ASTYLE_JNI
// java library build variables
JNIEnv* g_env;
jobject g_obj;
jmethodID g_mid;
#endif
const char* g_version = "2.02.1";
//-----------------------------------------------------------------------------
// ASStreamIterator class
// typename will be istringstream for GUI and istream otherwise
//-----------------------------------------------------------------------------
template<typename T>
ASStreamIterator<T>::ASStreamIterator(T* in)
{
inStream = in;
buffer.reserve(200);
eolWindows = 0;
eolLinux = 0;
eolMacOld = 0;
outputEOL[0] = '\0';
peekStart = 0;
prevLineDeleted = false;
checkForEmptyLine = false;
}
template<typename T>
ASStreamIterator<T>::~ASStreamIterator()
{
}
/**
* read the input stream, delete any end of line characters,
* and build a string that contains the input line.
*
* @return string containing the next input line minus any end of line characters
*/
template<typename T>
string ASStreamIterator<T>::nextLine(bool emptyLineWasDeleted)
{
// verify that the current position is correct
assert (peekStart == 0);
// a deleted line may be replaced if break-blocks is requested
// this sets up the compare to check for a replaced empty line
if (prevLineDeleted) {
prevLineDeleted = false;
checkForEmptyLine = true;
}
if (!emptyLineWasDeleted)
prevBuffer = buffer;
else
prevLineDeleted = true;
// read the next record
buffer.clear();
char ch;
inStream->get(ch);
while (!inStream->eof() && ch != '\n' && ch != '\r') {
buffer.append(1, ch);
inStream->get(ch);
}
if (inStream->eof()) {
return buffer;
}
int peekCh = inStream->peek();
// find input end-of-line characters
if (!inStream->eof()) {
if (ch == '\r') { // CR+LF is windows otherwise Mac OS 9
if (peekCh == '\n') {
inStream->get();
eolWindows++;
} else
eolMacOld++;
} else { // LF is Linux, allow for improbable LF/CR
if (peekCh == '\r') {
inStream->get();
eolWindows++;
} else
eolLinux++;
}
} else {
inStream->clear();
}
// set output end of line characters
if (eolWindows >= eolLinux) {
if (eolWindows >= eolMacOld)
strcpy(outputEOL, "\r\n"); // Windows (CR+LF)
else
strcpy(outputEOL, "\r"); // MacOld (CR)
} else if (eolLinux >= eolMacOld)
strcpy(outputEOL, "\n"); // Linux (LF)
else
strcpy(outputEOL, "\r"); // MacOld (CR)
return buffer;
}
// save the current position and get the next line
// this can be called for multiple reads
// when finished peeking you MUST call peekReset()
// call this function from ASFormatter ONLY
template<typename T>
string ASStreamIterator<T>::peekNextLine()
{
assert (hasMoreLines());
string nextLine_;
char ch;
if (peekStart == 0)
peekStart = inStream->tellg();
// read the next record
inStream->get(ch);
while (!inStream->eof() && ch != '\n' && ch != '\r') {
nextLine_.append(1, ch);
inStream->get(ch);
}
if (inStream->eof()) {
return nextLine_;
}
int peekCh = inStream->peek();
// remove end-of-line characters
if (!inStream->eof()) {
if ((peekCh == '\n' || peekCh == '\r') && peekCh != ch) ///////////// changed //////////
inStream->get();
}
return nextLine_;
}
// reset current position and EOF for peekNextLine()
template<typename T>
void ASStreamIterator<T>::peekReset()
{
assert(peekStart != 0);
inStream->clear();
inStream->seekg(peekStart);
peekStart = 0;
}
// save the last input line after input has reached EOF
template<typename T>
void ASStreamIterator<T>::saveLastInputLine()
{
assert(inStream->eof());
prevBuffer = buffer;
}
// check for a change in line ends
template<typename T>
bool ASStreamIterator<T>::getLineEndChange(int lineEndFormat) const
{
assert(lineEndFormat == LINEEND_DEFAULT
|| lineEndFormat == LINEEND_WINDOWS
|| lineEndFormat == LINEEND_LINUX
|| lineEndFormat == LINEEND_MACOLD);
bool lineEndChange = false;
if (lineEndFormat == LINEEND_WINDOWS)
lineEndChange = (eolLinux + eolMacOld != 0);
else if (lineEndFormat == LINEEND_LINUX)
lineEndChange = (eolWindows + eolMacOld != 0);
else if (lineEndFormat == LINEEND_MACOLD)
lineEndChange = (eolWindows + eolLinux != 0);
else {
if (eolWindows > 0)
lineEndChange = (eolLinux + eolMacOld != 0);
else if (eolLinux > 0)
lineEndChange = (eolWindows + eolMacOld != 0);
else if (eolMacOld > 0)
lineEndChange = (eolWindows + eolLinux != 0);
}
return lineEndChange;
}
#ifndef ASTYLE_LIB
//-----------------------------------------------------------------------------
// ASConsole class
// main function will be included only in the console build
//-----------------------------------------------------------------------------
// rewrite a stringstream converting the line ends
void ASConsole::convertLineEnds(ostringstream& out, int lineEnd)
{
assert(lineEnd == LINEEND_WINDOWS || lineEnd == LINEEND_LINUX || lineEnd == LINEEND_MACOLD);
const string& inStr = out.str(); // avoids strange looking syntax
string outStr; // the converted ouput
int inLength = inStr.length();
for (int pos = 0; pos < inLength; pos++) {
if (inStr[pos] == '\r') {
if (inStr[pos+ 1] == '\n') {
// CRLF
if (lineEnd == LINEEND_CR) {
outStr += inStr[pos]; // Delete the LF
pos++;
continue;
} else if (lineEnd == LINEEND_LF) {
outStr += inStr[pos+1]; // Delete the CR
pos++;
continue;
} else {
outStr += inStr[pos]; // Do not change
outStr += inStr[pos+1];
pos++;
continue;
}
} else {
// CR
if (lineEnd == LINEEND_CRLF) {
outStr += inStr[pos]; // Insert the CR
outStr += '\n'; // Insert the LF
continue;
} else if (lineEnd == LINEEND_LF) {
outStr += '\n'; // Insert the LF
continue;
} else {
outStr += inStr[pos]; // Do not change
continue;
}
}
} else if (inStr[pos] == '\n') {
// LF
if (lineEnd == LINEEND_CRLF) {
outStr += '\r'; // Insert the CR
outStr += inStr[pos]; // Insert the LF
continue;
} else if (lineEnd == LINEEND_CR) {
outStr += '\r'; // Insert the CR
continue;
} else {
outStr += inStr[pos]; // Do not change
continue;
}
} else {
outStr += inStr[pos]; // Write the current char
}
}
// replace the stream
out.str(outStr);
}
void ASConsole::correctMixedLineEnds(ostringstream& out)
{
LineEndFormat lineEndFormat = LINEEND_DEFAULT;
if (strcmp(outputEOL, "\r\n") == 0)
lineEndFormat = LINEEND_WINDOWS;
if (strcmp(outputEOL, "\n") == 0)
lineEndFormat = LINEEND_LINUX;
if (strcmp(outputEOL, "\r") == 0)
lineEndFormat = LINEEND_MACOLD;
convertLineEnds(out, lineEndFormat);
}
// check files for 16 or 32 bit encoding
// the file must have a Byte Order Mark (BOM)
// NOTE: some string functions don't work with NULLs (e.g. length())
FileEncoding ASConsole::detectEncoding(const char* data, size_t dataSize) const
{
FileEncoding encoding = ENCODING_8BIT;
if (dataSize >= 4 && memcmp(data, "\x00\x00\xFE\xFF", 4) == 0)
encoding = UTF_32BE;
else if (dataSize >= 4 && memcmp(data, "\xFF\xFE\x00\x00", 4) == 0)
encoding = UTF_32LE;
else if (dataSize >= 2 && memcmp(data, "\xFE\xFF", 2) == 0)
encoding = UTF_16BE;
else if (dataSize >= 2 && memcmp(data, "\xFF\xFE", 2) == 0)
encoding = UTF_16LE;
return encoding;
}
// error exit without a message
void ASConsole::error() const
{
(*_err) << _("\nArtistic Style has terminated") << endl;
exit(EXIT_FAILURE);
}
// error exit with a message
void ASConsole::error(const char* why, const char* what) const
{
(*_err) << why << ' ' << what << endl;
error();
}
/**
* If no files have been given, use cin for input and cout for output.
*
* This is used to format text for text editors like TextWrangler (Mac).
* Do NOT display any console messages when this function is used.
*/
void ASConsole::formatCinToCout() const
{
verifyCinPeek();
ASStreamIterator<istream> streamIterator(&cin); // create iterator for cin
formatter.init(&streamIterator);
while (formatter.hasMoreLines()) {
cout << formatter.nextLine();
if (formatter.hasMoreLines())
cout << streamIterator.getOutputEOL();
else {
// this can happen if the file if missing a closing bracket and break-blocks is requested
if (formatter.getIsLineReady()) {
cout << streamIterator.getOutputEOL();
cout << formatter.nextLine();
}
}
}
cout.flush();
}
/**
* Verify that tellg() works with cin.
* This will fail if cin is piped to AStyle "cat txt.cpp | ./astyled".
* But is OK for redirection "./astyled < txt.cpp".
*/
void ASConsole::verifyCinPeek() const
{
int currPos = static_cast<int>(cin.tellg());
if (currPos == -1) {
(*_err) << _("Cannot process the input stream") << endl;
error();
}
}
/**
* Open input file, format it, and close the output.
*
* @param fileName_ The path and name of the file to be processed.
*/
void ASConsole::formatFile(const string& fileName_)
{
stringstream in;
ostringstream out;
FileEncoding encoding = readFile(fileName_, in);
// Unless a specific language mode has been set, set the language mode
// according to the file's suffix.
if (!formatter.getModeManuallySet()) {
if (stringEndsWith(fileName_, string(".java")))
formatter.setJavaStyle();
else if (stringEndsWith(fileName_, string(".cs")))
formatter.setSharpStyle();
else
formatter.setCStyle();
}
// set line end format
string nextLine; // next output line
filesAreIdentical = true; // input and output files are identical
LineEndFormat lineEndFormat = formatter.getLineEndFormat();
initializeOutputEOL(lineEndFormat);
// do this AFTER setting the file mode
ASStreamIterator<stringstream> streamIterator(&in);
formatter.init(&streamIterator);
// format the file
while (formatter.hasMoreLines()) {
nextLine = formatter.nextLine();
out << nextLine;
linesOut++;
if (formatter.hasMoreLines()) {
setOutputEOL(lineEndFormat, streamIterator.getOutputEOL());
out << outputEOL;
} else {
streamIterator.saveLastInputLine(); // to compare the last input line
// this can happen if the file if missing a closing bracket and break-blocks is requested
if (formatter.getIsLineReady()) {
setOutputEOL(lineEndFormat, streamIterator.getOutputEOL());
out << outputEOL;
nextLine = formatter.nextLine();
out << nextLine;
linesOut++;
streamIterator.saveLastInputLine();
}
}
if (filesAreIdentical) {
if (streamIterator.checkForEmptyLine) {
if (nextLine.find_first_not_of(" \t") != string::npos)
filesAreIdentical = false;
} else if (!streamIterator.compareToInputBuffer(nextLine))
filesAreIdentical = false;
streamIterator.checkForEmptyLine = false;
}
}
// correct for mixed line ends
if (lineEndsMixed) {
correctMixedLineEnds(out);
filesAreIdentical = false;
}
// remove targetDirectory from filename if required by print
string displayName;
if (hasWildcard)
displayName = fileName_.substr(targetDirectory.length() + 1);
else
displayName = fileName_;
// if file has changed, write the new file
if (!filesAreIdentical || streamIterator.getLineEndChange(lineEndFormat)) {
writeFile(fileName_, encoding, out);
printMsg(_("Formatted %s\n"), displayName);
filesFormatted++;
} else {
if (!isFormattedOnly)
printMsg(_("Unchanged %s\n"), displayName);
filesUnchanged++;
}
assert(formatter.getChecksumDiff() == 0);
}
// build a vector of argv options
// the program path argv[0] is excluded
vector<string> ASConsole::getArgvOptions(int argc, char** argv) const
{
vector<string> argvOptions;
for (int i = 1; i < argc; i++) {
argvOptions.push_back(string(argv[i]));
}
return argvOptions;
}
// for unit testing
vector<bool> ASConsole::getExcludeHitsVector()
{
return excludeHitsVector;
}
// for unit testing
vector<string> ASConsole::getExcludeVector()
{
return excludeVector;
}
// for unit testing
vector<string> ASConsole::getFileName()
{
return fileName;
}
// for unit testing
vector<string> ASConsole::getFileNameVector()
{
return fileNameVector;
}
// for unit testing
vector<string> ASConsole::getFileOptionsVector()
{
return fileOptionsVector;
}
int ASConsole::getFilesUnchanged()
{
return filesUnchanged;
}
int ASConsole::getFilesFormatted()
{
return filesFormatted;
}
bool ASConsole::getIgnoreExcludeErrors()
{
return ignoreExcludeErrors;
}
bool ASConsole::getIgnoreExcludeErrorsDisplay()
{
return ignoreExcludeErrorsDisplay;
}
bool ASConsole::getIsFormattedOnly()
{
return isFormattedOnly;
}
string ASConsole::getLanguageID() const
{
return localizer.getLanguageID();
}
bool ASConsole::getIsQuiet()
{
return isQuiet;
}
bool ASConsole::getIsRecursive()
{
return isRecursive;
}
bool ASConsole::getIsVerbose()
{
return isVerbose;
}
bool ASConsole::getLineEndsMixed()
{
return lineEndsMixed;
}
bool ASConsole::getNoBackup()
{
return noBackup;
}
string ASConsole::getOptionsFileName()
{
return optionsFileName;
}
bool ASConsole::getOptionsFileRequired()
{
return optionsFileRequired;
}
// for unit testing
vector<string> ASConsole::getOptionsVector()
{
return optionsVector;
}
string ASConsole::getOrigSuffix()
{
return origSuffix;
}
string ASConsole::getParam(const string& arg, const char* op)
{
return arg.substr(strlen(op));
}
bool ASConsole::getPreserveDate()
{
return preserveDate;
}
// initialize output end of line
void ASConsole::initializeOutputEOL(LineEndFormat lineEndFormat)
{
assert(lineEndFormat == LINEEND_DEFAULT
|| lineEndFormat == LINEEND_WINDOWS
|| lineEndFormat == LINEEND_LINUX
|| lineEndFormat == LINEEND_MACOLD);
outputEOL[0] = '\0'; // current line end
prevEOL[0] = '\0'; // previous line end
lineEndsMixed = false; // output has mixed line ends, LINEEND_DEFAULT only
if (lineEndFormat == LINEEND_WINDOWS)
strcpy(outputEOL, "\r\n");
else if (lineEndFormat == LINEEND_LINUX)
strcpy(outputEOL, "\n");
else if (lineEndFormat == LINEEND_MACOLD)
strcpy(outputEOL, "\r");
else
outputEOL[0] = '\0';
}
FileEncoding ASConsole::readFile(const string& fileName_, stringstream& in) const
{
const int blockSize = 131072; // 128 KB
ifstream fin(fileName_.c_str(), ios::binary);
if (!fin)
error("Cannot open input file", fileName_.c_str());
char data[blockSize];
fin.read(data, sizeof(data));
if (fin.bad())
error("Cannot read input file", fileName_.c_str());
size_t dataSize = static_cast<size_t>(fin.gcount());
FileEncoding encoding = detectEncoding(data, dataSize);
if (encoding == UTF_32BE || encoding == UTF_32LE)
error(_("Cannot process UTF-32 encoding"), fileName_.c_str());
bool firstBlock = true;
while (dataSize) {
if (encoding == UTF_16LE || encoding == UTF_16BE) {
// convert utf-16 to utf-8
size_t utf8Size = Utf8Length(data, dataSize, encoding);
char* utf8Out = new char[utf8Size];
size_t utf8Len = Utf16ToUtf8(data, dataSize, encoding, firstBlock, utf8Out);
assert(utf8Len == utf8Size);
in << string(utf8Out, utf8Len);
delete []utf8Out;
} else
in << string(data, dataSize);
fin.read(data, sizeof(data));
if (fin.bad())
error("Cannot read input file", fileName_.c_str());
dataSize = static_cast<size_t>(fin.gcount());
firstBlock = false;
}
fin.close();
return encoding;
}
void ASConsole::setIgnoreExcludeErrors(bool state)
{
ignoreExcludeErrors = state;
}
void ASConsole::setIgnoreExcludeErrorsAndDisplay(bool state)
{
ignoreExcludeErrors = state;
ignoreExcludeErrorsDisplay = state;
}
void ASConsole::setIsFormattedOnly(bool state)
{
isFormattedOnly = state;
}
void ASConsole::setIsQuiet(bool state)
{
isQuiet = state;
}
void ASConsole::setIsRecursive(bool state)
{
isRecursive = state;
}
void ASConsole::setIsVerbose(bool state)
{
isVerbose = state;
}
void ASConsole::setNoBackup(bool state)
{
noBackup = state;
}
void ASConsole::setOptionsFileName(string name)
{
optionsFileName = name;
}
void ASConsole::setOptionsFileRequired(bool state)
{
optionsFileRequired = state;
}
void ASConsole::setOrigSuffix(string suffix)
{
origSuffix = suffix;
}
void ASConsole::setPreserveDate(bool state)
{
preserveDate = state;
}
// set outputEOL variable
void ASConsole::setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL)
{
if (lineEndFormat == LINEEND_DEFAULT) {
strcpy(outputEOL, currentEOL);
if (strlen(prevEOL) == 0)
strcpy(prevEOL, outputEOL);
if (strcmp(prevEOL, outputEOL) != 0) {
lineEndsMixed = true;
filesAreIdentical = false;
strcpy(prevEOL, outputEOL);
}
} else {
strcpy(prevEOL, currentEOL);
if (strcmp(prevEOL, outputEOL) != 0)
filesAreIdentical = false;
}
}
#ifdef _WIN32 // Windows specific
/**
* WINDOWS function to display the last system error.
*/
void ASConsole::displayLastError()
{
LPSTR msgBuf;
DWORD lastError = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
lastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPSTR) &msgBuf,
0,
NULL
);
// Display the string.
(*_err) << "Error (" << lastError << ") " << msgBuf << endl;
// Free the buffer.
LocalFree(msgBuf);
}
/**
* WINDOWS function to get the current directory.
* NOTE: getenv("CD") does not work for Windows Vista.
* The Windows function GetCurrentDirectory is used instead.
*
* @return The path of the current directory
*/
string ASConsole::getCurrentDirectory(const string& fileName_) const
{
char currdir[MAX_PATH];
currdir[0] = '\0';
if (!GetCurrentDirectory(sizeof(currdir), currdir))
error("Cannot find file", fileName_.c_str());
return string(currdir);
}
/**
* WINDOWS function to resolve wildcards and recurse into sub directories.
* The fileName vector is filled with the path and names of files to process.
*
* @param directory The path of the directory to be processed.
* @param wildcard The wildcard to be processed (e.g. *.cpp).
*/
void ASConsole::getFileNames(const string& directory, const string& wildcard)
{
vector<string> subDirectory; // sub directories of directory
WIN32_FIND_DATA findFileData; // for FindFirstFile and FindNextFile
// Find the first file in the directory
// Find will get at least "." and "..".
string firstFile = directory + "\\*";
HANDLE hFind = FindFirstFile(firstFile.c_str(), &findFileData);
if (hFind == INVALID_HANDLE_VALUE) {
// Error (3) The system cannot find the path specified.
// Error (123) The filename, directory name, or volume label syntax is incorrect.
// ::FindClose(hFind); before exiting
displayLastError();
error(_("Cannot open directory"), directory.c_str());
}
// save files and sub directories
do {
// skip hidden or read only
if (findFileData.cFileName[0] == '.'
|| (findFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
|| (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
continue;
// is this a sub directory
if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (!isRecursive)
continue;
// if a sub directory and recursive, save sub directory
string subDirectoryPath = directory + g_fileSeparator + findFileData.cFileName;
if (isPathExclued(subDirectoryPath))
printMsg(_("Exclude %s\n"), subDirectoryPath.substr(mainDirectoryLength));
else
subDirectory.push_back(subDirectoryPath);
continue;
}
// save the file name
string filePathName = directory + g_fileSeparator + findFileData.cFileName;
// check exclude before wildcmp to avoid "unmatched exclude" error
bool isExcluded = isPathExclued(filePathName);
// save file name if wildcard match
if (wildcmp(wildcard.c_str(), findFileData.cFileName)) {
if (isExcluded)
printMsg(_("Exclude %s\n"), filePathName.substr(mainDirectoryLength));
else
fileName.push_back(filePathName);
}
} while (FindNextFile(hFind, &findFileData) != 0);
// check for processing error
::FindClose(hFind);
DWORD dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
error("Error processing directory", directory.c_str());
// recurse into sub directories
// if not doing recursive subDirectory is empty
for (unsigned i = 0; i < subDirectory.size(); i++)
getFileNames(subDirectory[i], wildcard);
return;
}
/**
* WINDOWS function to format a number according to the current locale.
* This formats positive integers only, no float.
*
* @param num The number to be formatted.
* @param lcid The LCID of the locale to be used for testing.
* @return The formatted number.
*/
string ASConsole::getNumberFormat(int num, size_t lcid) const
{
// Compilers that don't support C++ locales should still support this assert.
// The C locale should be set but not the C++.
// This function is not necessary if the C++ locale is set.
assert(locale().name() == "C");
// convert num to a string
stringstream alphaNum;
alphaNum << num;
string number = alphaNum.str();
if (useAscii)
return number;
// format the number using the Windows API
if (lcid == 0)
lcid = LOCALE_USER_DEFAULT;
int outSize = ::GetNumberFormat(lcid, 0, number.c_str(), NULL, NULL, 0);
char* outBuf = new(nothrow) char[outSize];
if (outBuf == NULL)
return number;
::GetNumberFormat(lcid, 0, number.c_str(), NULL, outBuf, outSize);
// remove the decimal
string formattedNum(outBuf);
int decSize = ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, NULL, 0);
char* decBuf = new(nothrow) char[decSize];
if (decBuf == NULL)
return number;
::GetLocaleInfo(lcid, LOCALE_SDECIMAL, decBuf, decSize);
size_t i = formattedNum.rfind(decBuf);
if (i != string::npos)
formattedNum.erase(i);
if (!formattedNum.length())
formattedNum = "0";
delete [] outBuf;
delete [] decBuf;
return formattedNum;
}
#else // not _WIN32
/**
* LINUX function to get the current directory.
* This is done if the fileName does not contain a path.
* It is probably from an editor sending a single file.
*
* @param fileName_ The filename is used only for the error message.
* @return The path of the current directory
*/
string ASConsole::getCurrentDirectory(const string& fileName_) const
{
char* currdir = getenv("PWD");
if (currdir == NULL)
error("Cannot find file", fileName_.c_str());
return string(currdir);
}
/**
* LINUX function to resolve wildcards and recurse into sub directories.
* The fileName vector is filled with the path and names of files to process.
*
* @param directory The path of the directory to be processed.
* @param wildcard The wildcard to be processed (e.g. *.cpp).
*/
void ASConsole::getFileNames(const string& directory, const string& wildcard)
{
struct dirent* entry; // entry from readdir()
struct stat statbuf; // entry from stat()
vector<string> subDirectory; // sub directories of this directory
// errno is defined in <errno.h> and is set for errors in opendir, readdir, or stat
errno = 0;
DIR* dp = opendir(directory.c_str());
if (dp == NULL)
error(_("Cannot open directory"), directory.c_str());
// save the first fileName entry for this recursion
const unsigned firstEntry = fileName.size();
// save files and sub directories
while ((entry = readdir(dp)) != NULL) {
// get file status
string entryFilepath = directory + g_fileSeparator + entry->d_name;
if (stat(entryFilepath.c_str(), &statbuf) != 0) {
if (errno == EOVERFLOW) { // file over 2 GB is OK
errno = 0;
continue;
}
perror("errno message");
error("Error getting file status in directory", directory.c_str());
}
// skip hidden or read only
if (entry->d_name[0] == '.' || !(statbuf.st_mode & S_IWUSR))
continue;
// if a sub directory and recursive, save sub directory
if (S_ISDIR(statbuf.st_mode) && isRecursive) {
if (isPathExclued(entryFilepath))
printMsg(_("Exclude %s\n"), entryFilepath.substr(mainDirectoryLength));
else
subDirectory.push_back(entryFilepath);
continue;
}
// if a file, save file name
if (S_ISREG(statbuf.st_mode)) {
// check exclude before wildcmp to avoid "unmatched exclude" error
bool isExcluded = isPathExclued(entryFilepath);
// save file name if wildcard match
if (wildcmp(wildcard.c_str(), entry->d_name)) {
if (isExcluded)