-
Notifications
You must be signed in to change notification settings - Fork 15.6k
/
command_line_interface.cc
2616 lines (2325 loc) · 91.7 KB
/
command_line_interface.cc
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
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/compiler/command_line_interface.h>
#include <cstdint>
#include <google/protobuf/stubs/platform_macros.h>
#include <stdio.h>
#include <sys/types.h>
#ifdef major
#undef major
#endif
#ifdef minor
#undef minor
#endif
#include <fcntl.h>
#include <sys/stat.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <ctype.h>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <limits.h> //For PATH_MAX
#include <memory>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#elif defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/compiler/subprocess.h>
#include <google/protobuf/compiler/zip_writer.h>
#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/io/io_win32.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace compiler {
#ifndef O_BINARY
#ifdef _O_BINARY
#define O_BINARY _O_BINARY
#else
#define O_BINARY 0 // If this isn't defined, the platform doesn't need it.
#endif
#endif
namespace {
#if defined(_WIN32)
// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
// them like we do below.
using google::protobuf::io::win32::access;
using google::protobuf::io::win32::close;
using google::protobuf::io::win32::mkdir;
using google::protobuf::io::win32::open;
using google::protobuf::io::win32::setmode;
using google::protobuf::io::win32::write;
#endif
static const char* kDefaultDirectDependenciesViolationMsg =
"File is imported but not declared in --direct_dependencies: %s";
// Returns true if the text looks like a Windows-style absolute path, starting
// with a drive letter. Example: "C:\foo". TODO(kenton): Share this with
// copy in importer.cc?
static bool IsWindowsAbsolutePath(const std::string& text) {
#if defined(_WIN32) || defined(__CYGWIN__)
return text.size() >= 3 && text[1] == ':' && isalpha(text[0]) &&
(text[2] == '/' || text[2] == '\\') && text.find_last_of(':') == 1;
#else
return false;
#endif
}
void SetFdToTextMode(int fd) {
#ifdef _WIN32
if (setmode(fd, _O_TEXT) == -1) {
// This should never happen, I think.
GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_TEXT): " << strerror(errno);
}
#endif
// (Text and binary are the same on non-Windows platforms.)
}
void SetFdToBinaryMode(int fd) {
#ifdef _WIN32
if (setmode(fd, _O_BINARY) == -1) {
// This should never happen, I think.
GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_BINARY): " << strerror(errno);
}
#endif
// (Text and binary are the same on non-Windows platforms.)
}
void AddTrailingSlash(std::string* path) {
if (!path->empty() && path->at(path->size() - 1) != '/') {
path->push_back('/');
}
}
bool VerifyDirectoryExists(const std::string& path) {
if (path.empty()) return true;
if (access(path.c_str(), F_OK) == -1) {
std::cerr << path << ": " << strerror(errno) << std::endl;
return false;
} else {
return true;
}
}
// Try to create the parent directory of the given file, creating the parent's
// parent if necessary, and so on. The full file name is actually
// (prefix + filename), but we assume |prefix| already exists and only create
// directories listed in |filename|.
bool TryCreateParentDirectory(const std::string& prefix,
const std::string& filename) {
// Recursively create parent directories to the output file.
// On Windows, both '/' and '\' are valid path separators.
std::vector<std::string> parts =
Split(filename, "/\\", true);
std::string path_so_far = prefix;
for (int i = 0; i < parts.size() - 1; i++) {
path_so_far += parts[i];
if (mkdir(path_so_far.c_str(), 0777) != 0) {
if (errno != EEXIST) {
std::cerr << filename << ": while trying to create directory "
<< path_so_far << ": " << strerror(errno) << std::endl;
return false;
}
}
path_so_far += '/';
}
return true;
}
// Get the absolute path of this protoc binary.
bool GetProtocAbsolutePath(std::string* path) {
#ifdef _WIN32
char buffer[MAX_PATH];
int len = GetModuleFileNameA(NULL, buffer, MAX_PATH);
#elif defined(__APPLE__)
char buffer[PATH_MAX];
int len = 0;
char dirtybuffer[PATH_MAX];
uint32_t size = sizeof(dirtybuffer);
if (_NSGetExecutablePath(dirtybuffer, &size) == 0) {
realpath(dirtybuffer, buffer);
len = strlen(buffer);
}
#elif defined(__FreeBSD__)
char buffer[PATH_MAX];
size_t len = PATH_MAX;
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
if (sysctl(mib, 4, &buffer, &len, NULL, 0) != 0) {
len = 0;
}
#else
char buffer[PATH_MAX];
int len = readlink("/proc/self/exe", buffer, PATH_MAX);
#endif
if (len > 0) {
path->assign(buffer, len);
return true;
} else {
return false;
}
}
// Whether a path is where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
bool IsInstalledProtoPath(const std::string& path) {
// Checking the descriptor.proto file should be good enough.
std::string file_path = path + "/google/protobuf/descriptor.proto";
return access(file_path.c_str(), F_OK) != -1;
}
// Add the paths where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
void AddDefaultProtoPaths(
std::vector<std::pair<std::string, std::string>>* paths) {
// TODO(xiaofeng): The code currently only checks relative paths of where
// the protoc binary is installed. We probably should make it handle more
// cases than that.
std::string path;
if (!GetProtocAbsolutePath(&path)) {
return;
}
// Strip the binary name.
size_t pos = path.find_last_of("/\\");
if (pos == std::string::npos || pos == 0) {
return;
}
path = path.substr(0, pos);
// Check the binary's directory.
if (IsInstalledProtoPath(path)) {
paths->push_back(std::pair<std::string, std::string>("", path));
return;
}
// Check if there is an include subdirectory.
if (IsInstalledProtoPath(path + "/include")) {
paths->push_back(
std::pair<std::string, std::string>("", path + "/include"));
return;
}
// Check if the upper level directory has an "include" subdirectory.
pos = path.find_last_of("/\\");
if (pos == std::string::npos || pos == 0) {
return;
}
path = path.substr(0, pos);
if (IsInstalledProtoPath(path + "/include")) {
paths->push_back(
std::pair<std::string, std::string>("", path + "/include"));
return;
}
}
std::string PluginName(const std::string& plugin_prefix,
const std::string& directive) {
// Assuming the directive starts with "--" and ends with "_out" or "_opt",
// strip the "--" and "_out/_opt" and add the plugin prefix.
return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6);
}
} // namespace
// A MultiFileErrorCollector that prints errors to stderr.
class CommandLineInterface::ErrorPrinter
: public MultiFileErrorCollector,
public io::ErrorCollector,
public DescriptorPool::ErrorCollector {
public:
ErrorPrinter(ErrorFormat format, DiskSourceTree* tree = NULL)
: format_(format),
tree_(tree),
found_errors_(false),
found_warnings_(false) {}
~ErrorPrinter() {}
// implements MultiFileErrorCollector ------------------------------
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
found_errors_ = true;
AddErrorOrWarning(filename, line, column, message, "error", std::cerr);
}
void AddWarning(const std::string& filename, int line, int column,
const std::string& message) {
found_warnings_ = true;
AddErrorOrWarning(filename, line, column, message, "warning", std::clog);
}
// implements io::ErrorCollector -----------------------------------
void AddError(int line, int column, const std::string& message) {
AddError("input", line, column, message);
}
void AddWarning(int line, int column, const std::string& message) {
AddErrorOrWarning("input", line, column, message, "warning", std::clog);
}
// implements DescriptorPool::ErrorCollector-------------------------
void AddError(const std::string& filename, const std::string& element_name,
const Message* descriptor, ErrorLocation location,
const std::string& message) {
AddErrorOrWarning(filename, -1, -1, message, "error", std::cerr);
}
void AddWarning(const std::string& filename, const std::string& element_name,
const Message* descriptor, ErrorLocation location,
const std::string& message) {
AddErrorOrWarning(filename, -1, -1, message, "warning", std::clog);
}
bool FoundErrors() const { return found_errors_; }
bool FoundWarnings() const { return found_warnings_; }
private:
void AddErrorOrWarning(const std::string& filename, int line, int column,
const std::string& message, const std::string& type,
std::ostream& out) {
// Print full path when running under MSVS
std::string dfile;
if (format_ == CommandLineInterface::ERROR_FORMAT_MSVS && tree_ != NULL &&
tree_->VirtualFileToDiskFile(filename, &dfile)) {
out << dfile;
} else {
out << filename;
}
// Users typically expect 1-based line/column numbers, so we add 1
// to each here.
if (line != -1) {
// Allow for both GCC- and Visual-Studio-compatible output.
switch (format_) {
case CommandLineInterface::ERROR_FORMAT_GCC:
out << ":" << (line + 1) << ":" << (column + 1);
break;
case CommandLineInterface::ERROR_FORMAT_MSVS:
out << "(" << (line + 1) << ") : " << type
<< " in column=" << (column + 1);
break;
}
}
if (type == "warning") {
out << ": warning: " << message << std::endl;
} else {
out << ": " << message << std::endl;
}
}
const ErrorFormat format_;
DiskSourceTree* tree_;
bool found_errors_;
bool found_warnings_;
};
// -------------------------------------------------------------------
// A GeneratorContext implementation that buffers files in memory, then dumps
// them all to disk on demand.
class CommandLineInterface::GeneratorContextImpl : public GeneratorContext {
public:
GeneratorContextImpl(const std::vector<const FileDescriptor*>& parsed_files);
// Write all files in the directory to disk at the given output location,
// which must end in a '/'.
bool WriteAllToDisk(const std::string& prefix);
// Write the contents of this directory to a ZIP-format archive with the
// given name.
bool WriteAllToZip(const std::string& filename);
// Add a boilerplate META-INF/MANIFEST.MF file as required by the Java JAR
// format, unless one has already been written.
void AddJarManifest();
// Get name of all output files.
void GetOutputFilenames(std::vector<std::string>* output_filenames);
// implements GeneratorContext --------------------------------------
io::ZeroCopyOutputStream* Open(const std::string& filename);
io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename);
io::ZeroCopyOutputStream* OpenForInsert(const std::string& filename,
const std::string& insertion_point);
io::ZeroCopyOutputStream* OpenForInsertWithGeneratedCodeInfo(
const std::string& filename, const std::string& insertion_point,
const google::protobuf::GeneratedCodeInfo& info);
void ListParsedFiles(std::vector<const FileDescriptor*>* output) {
*output = parsed_files_;
}
private:
friend class MemoryOutputStream;
// The files_ field maps from path keys to file content values. It's a map
// instead of an unordered_map so that files are written in order (good when
// writing zips).
std::map<std::string, std::string> files_;
const std::vector<const FileDescriptor*>& parsed_files_;
bool had_error_;
};
class CommandLineInterface::MemoryOutputStream
: public io::ZeroCopyOutputStream {
public:
MemoryOutputStream(GeneratorContextImpl* directory,
const std::string& filename, bool append_mode);
MemoryOutputStream(GeneratorContextImpl* directory,
const std::string& filename,
const std::string& insertion_point);
MemoryOutputStream(GeneratorContextImpl* directory,
const std::string& filename,
const std::string& insertion_point,
const google::protobuf::GeneratedCodeInfo& info);
virtual ~MemoryOutputStream();
// implements ZeroCopyOutputStream ---------------------------------
bool Next(void** data, int* size) override {
return inner_->Next(data, size);
}
void BackUp(int count) override { inner_->BackUp(count); }
int64_t ByteCount() const override { return inner_->ByteCount(); }
private:
// Checks to see if "filename_.pb.meta" exists in directory_; if so, fixes the
// offsets in that GeneratedCodeInfo record to reflect bytes inserted in
// filename_ at original offset insertion_offset with length insertion_length.
// Also adds in the data from info_to_insert_ with updated offsets governed by
// insertion_offset and indent_length. We assume that insertions will not
// occur within any given annotated span of text. insertion_content must end
// with an endline.
void UpdateMetadata(const std::string& insertion_content,
size_t insertion_offset, size_t insertion_length,
size_t indent_length);
// Inserts info_to_insert_ into target_info, assuming that the relevant
// insertion was made at insertion_offset in file_content with the given
// indent_length. insertion_content must end with an endline.
void InsertShiftedInfo(const std::string& insertion_content,
size_t insertion_offset, size_t indent_length,
google::protobuf::GeneratedCodeInfo& target_info);
// Where to insert the string when it's done.
GeneratorContextImpl* directory_;
std::string filename_;
std::string insertion_point_;
// The string we're building.
std::string data_;
// Whether we should append the output stream to the existing file.
bool append_mode_;
// StringOutputStream writing to data_.
std::unique_ptr<io::StringOutputStream> inner_;
// The GeneratedCodeInfo to insert at the insertion point.
google::protobuf::GeneratedCodeInfo info_to_insert_;
};
// -------------------------------------------------------------------
CommandLineInterface::GeneratorContextImpl::GeneratorContextImpl(
const std::vector<const FileDescriptor*>& parsed_files)
: parsed_files_(parsed_files), had_error_(false) {}
bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk(
const std::string& prefix) {
if (had_error_) {
return false;
}
if (!VerifyDirectoryExists(prefix)) {
return false;
}
for (const auto& pair : files_) {
const std::string& relative_filename = pair.first;
const char* data = pair.second.data();
int size = pair.second.size();
if (!TryCreateParentDirectory(prefix, relative_filename)) {
return false;
}
std::string filename = prefix + relative_filename;
// Create the output file.
int file_descriptor;
do {
file_descriptor =
open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
} while (file_descriptor < 0 && errno == EINTR);
if (file_descriptor < 0) {
int error = errno;
std::cerr << filename << ": " << strerror(error);
return false;
}
// Write the file.
while (size > 0) {
int write_result;
do {
write_result = write(file_descriptor, data, size);
} while (write_result < 0 && errno == EINTR);
if (write_result <= 0) {
// Write error.
// FIXME(kenton): According to the man page, if write() returns zero,
// there was no error; write() simply did not write anything. It's
// unclear under what circumstances this might happen, but presumably
// errno won't be set in this case. I am confused as to how such an
// event should be handled. For now I'm treating it as an error,
// since retrying seems like it could lead to an infinite loop. I
// suspect this never actually happens anyway.
if (write_result < 0) {
int error = errno;
std::cerr << filename << ": write: " << strerror(error);
} else {
std::cerr << filename << ": write() returned zero?" << std::endl;
}
return false;
}
data += write_result;
size -= write_result;
}
if (close(file_descriptor) != 0) {
int error = errno;
std::cerr << filename << ": close: " << strerror(error);
return false;
}
}
return true;
}
bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip(
const std::string& filename) {
if (had_error_) {
return false;
}
// Create the output file.
int file_descriptor;
do {
file_descriptor =
open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
} while (file_descriptor < 0 && errno == EINTR);
if (file_descriptor < 0) {
int error = errno;
std::cerr << filename << ": " << strerror(error);
return false;
}
// Create the ZipWriter
io::FileOutputStream stream(file_descriptor);
ZipWriter zip_writer(&stream);
for (const auto& pair : files_) {
zip_writer.Write(pair.first, pair.second);
}
zip_writer.WriteDirectory();
if (stream.GetErrno() != 0) {
std::cerr << filename << ": " << strerror(stream.GetErrno()) << std::endl;
return false;
}
if (!stream.Close()) {
std::cerr << filename << ": " << strerror(stream.GetErrno()) << std::endl;
return false;
}
return true;
}
void CommandLineInterface::GeneratorContextImpl::AddJarManifest() {
auto pair = files_.insert({"META-INF/MANIFEST.MF", ""});
if (pair.second) {
pair.first->second =
"Manifest-Version: 1.0\n"
"Created-By: 1.6.0 (protoc)\n"
"\n";
}
}
void CommandLineInterface::GeneratorContextImpl::GetOutputFilenames(
std::vector<std::string>* output_filenames) {
for (const auto& pair : files_) {
output_filenames->push_back(pair.first);
}
}
io::ZeroCopyOutputStream* CommandLineInterface::GeneratorContextImpl::Open(
const std::string& filename) {
return new MemoryOutputStream(this, filename, false);
}
io::ZeroCopyOutputStream*
CommandLineInterface::GeneratorContextImpl::OpenForAppend(
const std::string& filename) {
return new MemoryOutputStream(this, filename, true);
}
io::ZeroCopyOutputStream*
CommandLineInterface::GeneratorContextImpl::OpenForInsert(
const std::string& filename, const std::string& insertion_point) {
return new MemoryOutputStream(this, filename, insertion_point);
}
io::ZeroCopyOutputStream*
CommandLineInterface::GeneratorContextImpl::OpenForInsertWithGeneratedCodeInfo(
const std::string& filename, const std::string& insertion_point,
const google::protobuf::GeneratedCodeInfo& info) {
return new MemoryOutputStream(this, filename, insertion_point, info);
}
// -------------------------------------------------------------------
CommandLineInterface::MemoryOutputStream::MemoryOutputStream(
GeneratorContextImpl* directory, const std::string& filename,
bool append_mode)
: directory_(directory),
filename_(filename),
append_mode_(append_mode),
inner_(new io::StringOutputStream(&data_)) {}
CommandLineInterface::MemoryOutputStream::MemoryOutputStream(
GeneratorContextImpl* directory, const std::string& filename,
const std::string& insertion_point)
: directory_(directory),
filename_(filename),
insertion_point_(insertion_point),
inner_(new io::StringOutputStream(&data_)) {}
CommandLineInterface::MemoryOutputStream::MemoryOutputStream(
GeneratorContextImpl* directory, const std::string& filename,
const std::string& insertion_point, const google::protobuf::GeneratedCodeInfo& info)
: directory_(directory),
filename_(filename),
insertion_point_(insertion_point),
inner_(new io::StringOutputStream(&data_)),
info_to_insert_(info) {}
void CommandLineInterface::MemoryOutputStream::InsertShiftedInfo(
const std::string& insertion_content, size_t insertion_offset,
size_t indent_length, google::protobuf::GeneratedCodeInfo& target_info) {
// Keep track of how much extra data was added for indents before the
// current annotation being inserted. `pos` and `source_annotation.begin()`
// are offsets in `insertion_content`. `insertion_offset` is updated so that
// it can be added to an annotation's `begin` field to reflect that
// annotation's updated location after `insertion_content` was inserted into
// the target file.
size_t pos = 0;
insertion_offset += indent_length;
for (const auto& source_annotation : info_to_insert_.annotation()) {
GeneratedCodeInfo::Annotation* annotation = target_info.add_annotation();
int inner_indent = 0;
// insertion_content is guaranteed to end in an endline. This last endline
// has no effect on indentation.
for (; pos < source_annotation.end() && pos < insertion_content.size() - 1;
++pos) {
if (insertion_content[pos] == '\n') {
if (pos >= source_annotation.begin()) {
// The beginning of the annotation is at insertion_offset, but the end
// can still move further in the target file.
inner_indent += indent_length;
} else {
insertion_offset += indent_length;
}
}
}
*annotation = source_annotation;
annotation->set_begin(annotation->begin() + insertion_offset);
insertion_offset += inner_indent;
annotation->set_end(annotation->end() + insertion_offset);
}
}
void CommandLineInterface::MemoryOutputStream::UpdateMetadata(
const std::string& insertion_content, size_t insertion_offset,
size_t insertion_length, size_t indent_length) {
auto it = directory_->files_.find(filename_ + ".pb.meta");
if (it == directory_->files_.end() && info_to_insert_.annotation().empty()) {
// No metadata was recorded for this file.
return;
}
GeneratedCodeInfo metadata;
bool is_text_format = false;
std::string* encoded_data = nullptr;
if (it != directory_->files_.end()) {
encoded_data = &it->second;
// Try to decode a GeneratedCodeInfo proto from the .pb.meta file. It may be
// in wire or text format. Keep the same format when the data is written out
// later.
if (!metadata.ParseFromString(*encoded_data)) {
if (!TextFormat::ParseFromString(*encoded_data, &metadata)) {
// The metadata is invalid.
std::cerr
<< filename_
<< ".pb.meta: Could not parse metadata as wire or text format."
<< std::endl;
return;
}
// Generators that use the public plugin interface emit text-format
// metadata (because in the public plugin protocol, file content must be
// UTF8-encoded strings).
is_text_format = true;
}
} else {
// Create a new file to store the new metadata in info_to_insert_.
encoded_data =
&directory_->files_.insert({filename_ + ".pb.meta", ""}).first->second;
}
GeneratedCodeInfo new_metadata;
bool crossed_offset = false;
size_t to_add = 0;
for (const auto& source_annotation : metadata.annotation()) {
// The first time an annotation at or after the insertion point is found,
// insert the new metadata from info_to_insert_. Shift all annotations
// after the new metadata by the length of the text that was inserted
// (including any additional indent length).
if (source_annotation.begin() >= insertion_offset && !crossed_offset) {
crossed_offset = true;
InsertShiftedInfo(insertion_content, insertion_offset, indent_length,
new_metadata);
to_add += insertion_length;
}
GeneratedCodeInfo::Annotation* annotation = new_metadata.add_annotation();
*annotation = source_annotation;
annotation->set_begin(annotation->begin() + to_add);
annotation->set_end(annotation->end() + to_add);
}
// If there were never any annotations at or after the insertion point,
// make sure to still insert the new metadata from info_to_insert_.
if (!crossed_offset) {
InsertShiftedInfo(insertion_content, insertion_offset, indent_length,
new_metadata);
}
if (is_text_format) {
TextFormat::PrintToString(new_metadata, encoded_data);
} else {
new_metadata.SerializeToString(encoded_data);
}
}
CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// Make sure all data has been written.
inner_.reset();
// Insert into the directory.
auto pair = directory_->files_.insert({filename_, ""});
auto it = pair.first;
bool already_present = !pair.second;
if (insertion_point_.empty()) {
// This was just a regular Open().
if (already_present) {
if (append_mode_) {
it->second.append(data_);
} else {
std::cerr << filename_ << ": Tried to write the same file twice."
<< std::endl;
directory_->had_error_ = true;
}
return;
}
it->second.swap(data_);
} else {
// This was an OpenForInsert().
// If the data doesn't end with a clean line break, add one.
if (!data_.empty() && data_[data_.size() - 1] != '\n') {
data_.push_back('\n');
}
// Find the file we are going to insert into.
if (!already_present) {
std::cerr << filename_
<< ": Tried to insert into file that doesn't exist."
<< std::endl;
directory_->had_error_ = true;
return;
}
std::string* target = &it->second;
// Find the insertion point.
std::string magic_string =
strings::Substitute("@@protoc_insertion_point($0)", insertion_point_);
std::string::size_type pos = target->find(magic_string);
if (pos == std::string::npos) {
std::cerr << filename_ << ": insertion point \"" << insertion_point_
<< "\" not found." << std::endl;
directory_->had_error_ = true;
return;
}
if ((pos > 3) && (target->substr(pos - 3, 2) == "/*")) {
// Support for inline "/* @@protoc_insertion_point() */"
pos = pos - 3;
} else {
// Seek backwards to the beginning of the line, which is where we will
// insert the data. Note that this has the effect of pushing the
// insertion point down, so the data is inserted before it. This is
// intentional because it means that multiple insertions at the same point
// will end up in the expected order in the final output.
pos = target->find_last_of('\n', pos);
if (pos == std::string::npos) {
// Insertion point is on the first line.
pos = 0;
} else {
// Advance to character after '\n'.
++pos;
}
}
// Extract indent.
std::string indent_(*target, pos,
target->find_first_not_of(" \t", pos) - pos);
if (indent_.empty()) {
// No indent. This makes things easier.
target->insert(pos, data_);
UpdateMetadata(data_, pos, data_.size(), 0);
} else {
// Calculate how much space we need.
int indent_size = 0;
for (int i = 0; i < data_.size(); i++) {
if (data_[i] == '\n') indent_size += indent_.size();
}
// Make a hole for it.
target->insert(pos, data_.size() + indent_size, '\0');
// Now copy in the data.
std::string::size_type data_pos = 0;
char* target_ptr = ::google::protobuf::string_as_array(target) + pos;
while (data_pos < data_.size()) {
// Copy indent.
memcpy(target_ptr, indent_.data(), indent_.size());
target_ptr += indent_.size();
// Copy line from data_.
// We already guaranteed that data_ ends with a newline (above), so this
// search can't fail.
std::string::size_type line_length =
data_.find_first_of('\n', data_pos) + 1 - data_pos;
memcpy(target_ptr, data_.data() + data_pos, line_length);
target_ptr += line_length;
data_pos += line_length;
}
UpdateMetadata(data_, pos, data_.size() + indent_size, indent_.size());
GOOGLE_CHECK_EQ(target_ptr,
::google::protobuf::string_as_array(target) + pos + data_.size() + indent_size);
}
}
}
// ===================================================================
#if defined(_WIN32) && !defined(__CYGWIN__)
const char* const CommandLineInterface::kPathSeparator = ";";
#else
const char* const CommandLineInterface::kPathSeparator = ":";
#endif
CommandLineInterface::CommandLineInterface()
: direct_dependencies_violation_msg_(
kDefaultDirectDependenciesViolationMsg) {}
CommandLineInterface::~CommandLineInterface() {}
void CommandLineInterface::RegisterGenerator(const std::string& flag_name,
CodeGenerator* generator,
const std::string& help_text) {
GeneratorInfo info;
info.flag_name = flag_name;
info.generator = generator;
info.help_text = help_text;
generators_by_flag_name_[flag_name] = info;
}
void CommandLineInterface::RegisterGenerator(
const std::string& flag_name, const std::string& option_flag_name,
CodeGenerator* generator, const std::string& help_text) {
GeneratorInfo info;
info.flag_name = flag_name;
info.option_flag_name = option_flag_name;
info.generator = generator;
info.help_text = help_text;
generators_by_flag_name_[flag_name] = info;
generators_by_option_name_[option_flag_name] = info;
}
void CommandLineInterface::AllowPlugins(const std::string& exe_name_prefix) {
plugin_prefix_ = exe_name_prefix;
}
namespace {
bool ContainsProto3Optional(const Descriptor* desc) {
for (int i = 0; i < desc->field_count(); i++) {
if (desc->field(i)->has_optional_keyword()) {
return true;
}
}
for (int i = 0; i < desc->nested_type_count(); i++) {
if (ContainsProto3Optional(desc->nested_type(i))) {
return true;
}
}
return false;
}
bool ContainsProto3Optional(const FileDescriptor* file) {
if (file->syntax() == FileDescriptor::SYNTAX_PROTO3) {
for (int i = 0; i < file->message_type_count(); i++) {
if (ContainsProto3Optional(file->message_type(i))) {
return true;
}
}
}
return false;
}
} // namespace
namespace {
std::unique_ptr<SimpleDescriptorDatabase>
PopulateSingleSimpleDescriptorDatabase(const std::string& descriptor_set_name);
}
int CommandLineInterface::Run(int argc, const char* const argv[]) {
Clear();
switch (ParseArguments(argc, argv)) {
case PARSE_ARGUMENT_DONE_AND_EXIT:
return 0;
case PARSE_ARGUMENT_FAIL:
return 1;
case PARSE_ARGUMENT_DONE_AND_CONTINUE:
break;
}
std::vector<const FileDescriptor*> parsed_files;
std::unique_ptr<DiskSourceTree> disk_source_tree;
std::unique_ptr<ErrorPrinter> error_collector;
std::unique_ptr<DescriptorPool> descriptor_pool;
// The SimpleDescriptorDatabases here are the constituents of the
// MergedDescriptorDatabase descriptor_set_in_database, so this vector is for
// managing their lifetimes. Its scope should match descriptor_set_in_database
std::vector<std::unique_ptr<SimpleDescriptorDatabase>>
databases_per_descriptor_set;
std::unique_ptr<MergedDescriptorDatabase> descriptor_set_in_database;
std::unique_ptr<SourceTreeDescriptorDatabase> source_tree_database;
// Any --descriptor_set_in FileDescriptorSet objects will be used as a
// fallback to input_files on command line, so create that db first.
if (!descriptor_set_in_names_.empty()) {
for (const std::string& name : descriptor_set_in_names_) {
std::unique_ptr<SimpleDescriptorDatabase> database_for_descriptor_set =
PopulateSingleSimpleDescriptorDatabase(name);
if (!database_for_descriptor_set) {
return EXIT_FAILURE;
}
databases_per_descriptor_set.push_back(
std::move(database_for_descriptor_set));
}