-
Notifications
You must be signed in to change notification settings - Fork 16
/
protocolfile.cpp
974 lines (773 loc) · 27.1 KB
/
protocolfile.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
#include "protocolfile.h"
#include "protocolparser.h"
#include <fstream>
#include <filesystem>
#include <iostream>
std::string ProtocolFile::tempprefix = "temporarydeleteme_";
/*!
* Create the file object
* \param moduleName is the name of the file, not counting any extension
* \param supported are the Protocol-wide options.
* \param temp should be true for this file to be a temp file
*/
ProtocolFile::ProtocolFile(const std::string& moduleName, ProtocolSupport supported, bool temp) :
support(supported),
module(moduleName),
dirty(false),
appending(false),
temporary(temp)
{
}
/*!
* Create the file object. After this constructor you must call setModuleNameAndPath()
* or a file will not be created
* \param supported are the Protocol-wide options.
*/
ProtocolFile::ProtocolFile(ProtocolSupport supported) :
support(supported),
dirty(false),
appending(false),
temporary(true),
hasNontrivialContent(false)
{
}
void ProtocolFile::setModuleNameAndPath(std::string name, std::string filepath)
{
setModuleNameAndPath(std::string(), name, filepath, support.language);
}
void ProtocolFile::setModuleNameAndPath(std::string name, std::string filepath, ProtocolSupport::LanguageType languageoverride)
{
setModuleNameAndPath(std::string(), name, filepath, languageoverride);
}
void ProtocolFile::setModuleNameAndPath(std::string prefix, std::string name, std::string filepath)
{
setModuleNameAndPath(prefix, name, filepath, support.language);
}
void ProtocolFile::setModuleNameAndPath(std::string prefix, std::string name, std::string filepath, ProtocolSupport::LanguageType languageoverride)
{
// Remove any contents we currently have
clear();
support.language = languageoverride;
// Clean it all up
separateModuleNameAndPath(name, filepath);
// Extract the extension
extractExtension(name);
// Remember the module name
module = prefix + name;
// And the path
path = filepath;
// This will see if the file already exists and will setup the initial output
prepareToAppend();
}
/*!
* Get the extension information for this name, and remove it from the name.
* \param name has its extension (if any) recorded and removed
*/
void ProtocolFile::extractExtension(std::string& name)
{
extractExtension(name, extension);
}
/*!
* Get the extension information for this name, and remove it from the name.
* \param name has its extension (if any) removed
* \param extension receives the extension
*/
void ProtocolFile::extractExtension(std::string& name, std::string& extension)
{
// Note that "." as the first character is not an extension, it indicates a hidden file
std::size_t index = name.rfind(".");
if((index >= 1) && (index < name.size()))
{
// The extension, including the "."
extension = name.substr(index);
// The name without the extension
name = name.erase(index);
}
else
extension.clear();
}// ProtocolFile::extractExtension
/*!
* Given a module name and path adjust the name and path so that all the path
* information is in the path, the base name is in the name
* \param name contains the name with may include some path information. The
* path and extension will be removed
* \param filepath contains the path information, which will be augmented
* with any path information from the name, unless the name contains
* absolute path information, in which case the filepath will be
* replaced with the name path
*/
void ProtocolFile::separateModuleNameAndPath(std::string& name, std::string& filepath)
{
// Handle the case where the file includes "./" to reference the current working
// directory. We just remove this as its not needed.
if((name.find("./") == 0) || (name.find(".\\") == 0))
name.erase(0, 2);
// We use this to get any path data from the name
std::filesystem::path namepath(name);
// Remove the path from the name and add it to the file path
if(namepath.has_parent_path())
{
// Only add the directory separator if the filepath is not empty,
// cause if it is empty this will refer to the root of the file system
if(!filepath.empty())
filepath += std::filesystem::path::preferred_separator;
filepath += namepath.parent_path().string();
name = namepath.filename().string();
}
// Make sure the path uses native separators and ends with a separator (unless its empty)
filepath = sanitizePath(filepath);
}// ProtocolFile::separateModuleNameAndPath
/*!
* Clear the contents of the file. This will also mark the file as clean
*/
void ProtocolFile::clear()
{
contents.clear();
dirty = false;
appending = false;
}
/*!
* Append to the contents of the file, not including any prologue/epilogue. This will
* mark the file as dirty and containing non-trivial content, which will cause it to
* be flushed to disk on destruction.
* \param text is the information to append
*/
void ProtocolFile::write(const std::string& text)
{
hasNontrivialContent = true;
writeInternal(text);
}
/*!
* Append to the contents of the file, not including any prologue/epilogue. This will
* mark the file as dirty, but will not set non-trival content to true. The file may
* be destroyed on exit if there is no non-trivial content.
* \param text is the information to append
*/
void ProtocolFile::writeInternal(const std::string& text)
{
contents += text;
dirty = true;
}
/*!
* Append to the contents of the file, not including any prologue/epilogue.
* This will mark the file as dirty, which will cause it to be flushed to disk
* on destruction. The append will only take place if `text` does not already
* appear in the file contents.
* \param text is the information to append
*/
void ProtocolFile::writeOnce(const std::string& text)
{
if(contents.find(text) >= contents.size())
{
write(text);
}
}
/*!
* Output multiple include directives. The include directives are all done
* using quotes, not global brackes
* \param list is the list of module names that need to be included
*/
void ProtocolFile::writeIncludeDirectives(const std::vector<std::string>& list)
{
for(std::size_t i = 0; i < list.size(); i++)
writeIncludeDirective(list.at(i));
}
/*!
* Output an include directive, which looks like "#include filename.h\n". You
* can pass the entire include directive or just the module name. The include
* directive will not be output if this file already contains this directive.
* \param include is the module name to include
* \param comment is a trailing comment for the include directive, can be empty
* \param global should be true to use brackets ("<>") instead of quotes.
* \param autoextensions should be true to automatically append ".h" or ".hpp" to the
* include name if it is not already included
*/
void ProtocolFile::writeIncludeDirective(const std::string& include, const std::string& comment, bool global, bool autoextension)
{
if(include.empty())
return;
std::string directive = trimm(include);
// Technically things other than .h* could be included, but not by ProtoGen
if(!contains(directive, ".h") && autoextension)
{
if(support.language == ProtocolSupport::cpp_language)
directive += ".hpp";
else
directive += ".h";
}
// Don't include ourselves
if(directive == fileName(true))
return;
// Build the include directive with quotes or brackets based on the global status
if (global == false)
directive = "#include \"" + directive + "\"";
else
directive = "#include <" + directive + ">";
// See if this include directive is already present, in which case we don't need to add it again
if(contains(contents, directive, true))
return;
// Add the comment if there is one
if(comment.empty())
directive += "\n";
else
directive += "\t// " + comment + "\n";
// We try to group all the #includes together
std::size_t index = contents.rfind("#include");
if(index < contents.size())
{
// Find the end of the line
index = contents.find("\n", index);
if(index != std::string::npos)
{
contents.insert(index+1, directive);
dirty = true;
return;
}
}
// If we get here there were no #includes in the file, this is the first
// one; which we put at the current end of the file
makeLineSeparator();
// Note that an include directive is not non-trivial.
writeInternal(directive);
}// ProtocolFile::writeIncludeDirective
/*!
* Make sure the file data end such that there is exactly one blank line
* between the current contents and anything that is added after this function
*/
void ProtocolFile::makeLineSeparator(void)
{
makeLineSeparator(contents);
}
/*!
* Make sure the string data end such that there is exactly one blank line
* between the current contents and anything that is added after this function
* \param contents is the string whose ending is adjusted
*/
void ProtocolFile::makeLineSeparator(std::string& contents)
{
// Make sure that there are exactly two line terminators at the end of the string
int last = ((int)contents.size()) - 1;
int lastChar = last;
if(last < 0)
return;
// Scroll backwards until we have cleared the linefeeds and lastChar is pointing at the last non-linefeed character
while(lastChar >= 0)
{
if(contents.at(lastChar) == '\n')
lastChar--;
else
break;
}
// Three cases:
// 1) Too many linefeeds, chop some off
// 2) Just the right amount of line feeds, change nothing
// 3) Too few linefeeds, add some
if(last > lastChar + 2)
contents.erase(lastChar + 3);
else
{
while(last < lastChar + 2)
{
contents += "\n";
last++;
}
}
}
/*!
* Make a nice, native, relative path with a trailing directory separator
* \param path is the path to sanitize
* \return the sanitized path
*/
std::string ProtocolFile::sanitizePath(const std::string& path)
{
std::error_code ec;
// Empty paths are the simplest
if(path.empty())
return path;
// Absolute and relative versions of path
std::string absolute = std::filesystem::absolute(path, ec).string();
std::string relative = std::filesystem::relative(path, ec).string();
// Error checking, the path creation could fail, especially for relative paths that don't exist
if(absolute.empty())
absolute = path;
if(relative.empty())
relative = path;
// Make sure it has a trailing separator
if(!absolute.empty())
absolute += std::filesystem::path::preferred_separator;
// "." is the current working directory, same as an empty path
if(relative == ".")
relative.clear();
else if(!relative.empty())
relative += std::filesystem::path::preferred_separator;
// Return the shorter of the two paths
if(relative.size() > absolute.size())
return absolute;
else
return relative;
}
/*!
* delete a specific file. The file will be deleted even if it is read-only.
* \param fileName identifies the file relative to the current working directory
*/
void ProtocolFile::deleteFile(const std::string& fileName)
{
std::error_code ec;
makeFileWritable(fileName);
std::filesystem::remove(fileName, ec);
}
/*!
* Rename a file from oldName to newName. If the file newName already exists
* it will be deleted.
* \param oldName is the old name of the file
* \param newName is the new name of the file
*/
void ProtocolFile::renameFile(const std::string& oldName, const std::string& newName)
{
std::error_code ec;
// Make sure the new file does not exist
deleteFile(newName);
// Now make the old name become the new name
makeFileWritable(oldName);
std::filesystem::rename(oldName, newName, ec);
}// ProtocolFile::renameFile
/*!
* Make a specific file writable.
* \param fileName identifies the file relative to the current working directory
*/
void ProtocolFile::makeFileWritable(const std::string& fileName)
{
std::error_code ec;
// Make sure the file has owner read and write permissiosn
std::filesystem::permissions(fileName, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, std::filesystem::perm_options::add, ec);
}
/*!
* Copy a temporary file to the real file and delete the temporary file
* \param path is the path to the files
* \param fileName is the real file name, which does not include the temporary prefix
*/
void ProtocolFile::copyTemporaryFile(const std::string& path, const std::string& fileName)
{
bool equal = false;
std::string tempFileName = path + tempprefix + fileName;
std::string permFileName = path + fileName;
// Open the temporary file
std::fstream tempfile(tempFileName, std::ios_base::in);
// Its possible we already copied and deleted the file, so this isn't an error
if(!tempfile.is_open())
return;
// Open the permanent file
std::fstream permfile(permFileName, std::ios_base::in);
// Check if the files are the same
if(permfile.is_open())
{
// Real all file bytes into a string, notice parentheses to deal with "most vexing parse problem"
std::string tempdata((std::istreambuf_iterator<char>(tempfile)), std::istreambuf_iterator<char>());
std::string permdata((std::istreambuf_iterator<char>(permfile)), std::istreambuf_iterator<char>());
if(tempdata == permdata)
equal = true;
permfile.close();
}
// Done with the file contents
tempfile.close();
if(equal)
{
// If the two file contents are the same, delete the temporary
// file, leave the original file unchanged
deleteFile(tempFileName);
}
else
{
// else if the file contents are different, delete the original
// file and rename the temp file to be the original file
renameFile(tempFileName, permFileName);
}
}// ProtocolFile::copyTemporaryFile
/*!
* delete both the .c and .h file. The files will be deleted even if they are read-only.
* \param moduleName gives the file name without extension.
*/
void ProtocolFile::deleteModule(const std::string& moduleName)
{
deleteFile(moduleName + ".cpp");
deleteFile(moduleName + ".c");
deleteFile(moduleName + ".hpp");
deleteFile(moduleName + ".h");
}
/*!
* Destroy the protocol file making sure to dump the contents to disk if needed
*/
ProtocolFile::~ProtocolFile()
{
ProtocolFile::flush();
}
/*!
* \return the the correct on disk name. This name will include the temporary
* prefix if needed
*/
std::string ProtocolFile::fileNameAndPathOnDisk(void) const
{
if(temporary)
return path + tempprefix+fileName(true);
else
return path + fileName(true);
}
/*!
* Write the file to disc, including any prologue/epilogue
* \return true if the file is written, else there is a problem opening\overwriting the file
*/
bool ProtocolFile::flush(void)
{
// Nothing to write
if(!dirty || contents.empty())
return false;
// Got to have a name
if(module.empty())
{
std::cerr << "Empty module name when writing protocol file" << std::endl;
return false;
}
std::error_code ec;
// Make sure the path exists
if(!path.empty())
std::filesystem::create_directories(path, ec);
// Open the file for write
std::fstream file(fileNameAndPathOnDisk(), std::ios_base::out);
if(!file.is_open())
{
std::cerr << "error: failed to open " << ProtocolFile::fileName(true) << std::endl;
return false;
}
// The actual interesting contents
file << contents;
// And the file
file.close();
// Empty our data
clear();
return true;
}// ProtocolFile::flush
/*!
* Write a comment for the entire file in the \file block. This will do nothing
* if the file comment has already been set.
* \param comment is the file comment, which will be reflowed to 80 characters.
*/
void ProtocolHeaderFile::setFileComment(const std::string& comment)
{
std::string match;
std::string filecomment;
// This is the comment block as it is without a file comment
match += "/*!\n";
match += " * \\file\n";
match += " */\n";
// Construct the file comment
filecomment += "/*!\n";
filecomment += " * \\file\n";
filecomment += ProtocolParser::reflowComment(comment, " * ", 80) + "\n";
filecomment += " */\n";
replaceinplace(contents, match, filecomment);
}// ProtocolHeaderFile::setFileComment
/*!
* Add the #define __STDC_CONSTANT_MACROS before stdnint.h is included. If
* stdint.h is not yet included then add the define to the end of the file.
* If the #define is already present, do nothing.
*/
void ProtocolHeaderFile::defineStdC_Constant_Macros(void)
{
std::string match;
std::string filecomment;
// Only do the definition once
if(contains(contents, "#define __STDC_CONSTANT_MACROS"))
return;
// We need to insert "#define __STDC_CONSTANT_MACROS" before the include to stdint.h
match += "#include <stdint.h>";
if(contains(contents, match))
replaceinplace(contents, match, "#define __STDC_CONSTANT_MACROS\n#include <stdint.h>");
else
{
makeLineSeparator();
writeInternal("#define __STDC_CONSTANT_MACROS\n");
}
makeLineSeparator();
}// ProtocolHeaderFile::defineStdC_Constant_Macros
/*!
* Get the extension information for this name, and remove it from the name.
* \param name has its extension (if any) logged and removed
*/
void ProtocolHeaderFile::extractExtension(std::string& name)
{
ProtocolFile::extractExtension(name);
// A header file extension must start with ".h" (.h, .hpp, .hxx, etc.)
if(!contains(extension, ".h"))
{
if(support.language == ProtocolSupport::cpp_language)
extension = ".hpp";
else
extension = ".h";
}
}// ProtocolHeaderFile::extractExtension
//! Destructor that performs the actual file write
ProtocolHeaderFile::~ProtocolHeaderFile()
{
ProtocolHeaderFile::flush();
}
/*!
* Write the file to disc, including any prologue/epilogue
* \return true if the file is written, else there is a problem opening\overwriting the file
*/
bool ProtocolHeaderFile::flush(void)
{
// Nothing to write
if(!dirty || contents.empty())
return false;
// Got to have a name
if(module.empty())
{
std::cerr << "Empty module name when writing protocol header file" << std::endl;
return false;
}
std::error_code ec;
// Make sure the path exists
if(!path.empty())
std::filesystem::create_directories(path, ec);
// Open the file for write
std::fstream file(fileNameAndPathOnDisk(), std::ios_base::out);
if(!file.is_open())
{
std::cerr << "Failed to open " << fileName(true) << std::endl;
return false;
}
// The actual interesting contents
file << contents;
// close the file out
file << getClosingStatement();
// And the file
file.close();
// Empty our data
clear();
return true;
}// ProtocolHeaderFile::flush
/*!
* \return the text that is appended to close a header file
*/
std::string ProtocolHeaderFile::getClosingStatement(void)
{
std::string close;
if(support.language == ProtocolSupport::c_language)
{
// close the __cplusplus
close += "#ifdef __cplusplus\n";
close += "}\n";
close += "#endif\n";
}
// close the opening #ifdef
close += "#endif // _" + toUpper(module) + replace(toUpper(extension), ".", "_") + "\n";
return close;
}
/*!
* Setup a file for a possible append. The append will happen if the file
* already exists, in which case it is read out, and the closing statement
* removed so append can be performed
*/
void ProtocolHeaderFile::prepareToAppend(void)
{
std::error_code ec;
if(std::filesystem::exists(fileNameAndPathOnDisk(), ec))
{
std::fstream file(fileNameAndPathOnDisk(), std::ios_base::in);
if(!file.is_open())
{
std::cerr << "Failed to open " << fileName(true) << " for append" << std::endl;
return;
}
// Read the entire file, and store as existing text string data
contents = std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
// Close the file, we don't need it anymore
file.close();
// Remove the trailing closing statement from the file so we can append further stuff
size_t index = contents.rfind(getClosingStatement());
if(index < contents.size())
contents.erase(index);
// we are appending
appending = true;
}// If the file already exists
else
{
// If this file does not yet exist, then put the stuff on top that is always included
// Tag for what generated the file
write("// " + fileName(true) + " was generated by ProtoGen version " + ProtocolParser::genVersion + "\n\n");
if (!support.licenseText.empty())
{
write(support.licenseText);
makeLineSeparator();
}
// The opening #ifdef
std::string define = "_" + toUpper(module) + replace(toUpper(extension), ".", "_");
write("#ifndef " + define + "\n");
write("#define " + define + "\n");
if(support.language == ProtocolSupport::c_language)
{
write("\n// Language target is C, C++ compilers: don't mangle us\n");
write("#ifdef __cplusplus\n");
write("extern \"C\" {\n");
write("#endif\n\n");
}
else if(support.language == ProtocolSupport::cpp_language)
{
write("\n// Language target is C++\n\n");
}
// Comment block at the top of the header file needed so doxygen will document the file
write("/*!\n");
write(" * \\file\n");
write(" */\n");
write("\n");
if((support.language == ProtocolSupport::c_language) || (support.language == ProtocolSupport::cpp_language))
writeIncludeDirective("stdint.h", "", true);
if(support.supportbool && (support.language == ProtocolSupport::c_language))
writeIncludeDirective("stdbool.h", "", true);
makeLineSeparator();
}
}// ProtocolHeaderFile::prepareToAppend
/*!
* Get the extension information for this name, and remove it from the name.
* \param name has its extension (if any) logged and removed
*/
void ProtocolSourceFile::extractExtension(std::string& name)
{
ProtocolFile::extractExtension(name);
if(support.language == ProtocolSupport::cpp_language)
{
// We cannot allow the .c extension for c++
if(extension.empty() || endsWith(extension, ".c"))
extension = ".cpp";
}
else
{
// A source file extension must start with ".c" (.c, .cpp, .cxx, etc.)
if(!contains(extension, ".c"))
extension = ".c";
}
}// ProtocolSourceFile::extractExtension
//! Destructor that performs the actual file write
ProtocolSourceFile::~ProtocolSourceFile()
{
ProtocolSourceFile::flush();
}
/*!
* Return the file path, or an empty string if this file has no non-trivial content
* \return the file path, or an empty string
*/
std::string ProtocolSourceFile::filePath(bool eveniftrivial) const
{
if(hasNontrivialContent || eveniftrivial)
return ProtocolFile::filePath(eveniftrivial);
else
return std::string();
}
/*!
* Return the file name, or an empty string if this file has no non-trivial content
* \return the file, or an empty string
*/
std::string ProtocolSourceFile::fileName(bool eveniftrivial) const
{
if(hasNontrivialContent || eveniftrivial)
return ProtocolFile::fileName(eveniftrivial);
else
return std::string();
}
/*!
* Write the file to disc, including any prologue/epilogue
* \return true if the file is written, else there is a problem opening\overwriting the file
*/
bool ProtocolSourceFile::flush(void)
{
// Nothing to write
if(!dirty || contents.empty())
return false;
// Got to have a name
if(module.empty())
{
std::cerr << "Empty module name when writing protocol source file" << std::endl;
return false;
}
if(hasNontrivialContent)
{
std::error_code ec;
// Make sure the path exists
if(!path.empty())
std::filesystem::create_directories(path, ec);
// Open the file for write
std::fstream file(fileNameAndPathOnDisk(), std::ios_base::out);
if(!file.is_open())
{
std::cerr << "Failed to open " << ProtocolSourceFile::fileName(true) << std::endl;
return false;
}
// The actual interesting contents
file << contents;
// close the file out
file << getClosingStatement();
// And the file
file.close();
}
else
{
// Source files must have non-trivial content to be allowed to exist
deleteFile(fileNameAndPathOnDisk());
}
// Empty our data
clear();
return true;
}// ProtocolSourceFile::flush
/*!
* \return the text that is appended to close a source file
*/
std::string ProtocolSourceFile::getClosingStatement(void)
{
std::string close;
// Mark the end of the file (so we can find it later if we append)
close += "// end of " + ProtocolSourceFile::fileName(true) + "\n";
return close;
}
/*!
* Setup a file for a possible append. The append will happen if the file
* already exists, in which case it is read out, and the closing statement
* removed so append can be performed
*/
void ProtocolSourceFile::prepareToAppend(void)
{
std::error_code ec;
if(std::filesystem::exists(fileNameAndPathOnDisk(), ec))
{
std::fstream file(fileNameAndPathOnDisk(), std::ios_base::in);
if(!file.is_open())
{
std::cerr << "Failed to open " << fileName(true) << " for append" << std::endl;
return;
}
// Read the entire file, and store as existing text string data
contents = std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
// Close the file, we don't need it anymore
file.close();
// Remove the trailing closing statement from the file so we can append further stuff
size_t index = contents.rfind(getClosingStatement());
if(index < contents.size())
contents.erase(index);
// we are appending
appending = true;
// We must assume we have non-trival content
hasNontrivialContent = true;
}// If the file already exists
else
{
// If this file does not yet exist, then put the stuff on top that is always included
// Tag for what generated the file
writeInternal("// " + fileName(true) + " was generated by ProtoGen version " + ProtocolParser::genVersion + "\n\n");
if (!support.licenseText.empty())
{
writeInternal(support.licenseText);
makeLineSeparator();
}
// The source file includes the header
writeIncludeDirective(module);
}
}// ProtocolSourceFile::prepareToAppend