-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInteractiveTutorial.cpp
More file actions
1191 lines (1007 loc) · 41.9 KB
/
InteractiveTutorial.cpp
File metadata and controls
1191 lines (1007 loc) · 41.9 KB
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
/* runcpp2
Defines: ["ssLOG_USE_SOURCE=1"]
Dependencies:
- Name: ssLogger
Platforms: [DefaultPlatform]
Source:
Git:
URL: "https://github.com/Neko-Box-Coder/ssLogger.git"
LibraryType: Header
IncludePaths: ["Include"]
Defines:
- "_CRT_SECURE_NO_WARNINGS=1"
- Name: "System2.cpp"
Platforms: [DefaultPlatform]
Source:
Git:
URL: "https://github.com/Neko-Box-Coder/System2.cpp.git"
LibraryType: Header
IncludePaths: [".", "./External/System2"]
- Name: "filesystem"
Platforms: [DefaultPlatform]
Source:
Git:
URL: "https://github.com/gulrak/filesystem.git"
Branch: "v1.5.14"
LibraryType: Header
IncludePaths: ["./include"]
*/
#include "ssLogger/ssLogInit.hpp"
#include "ssLogger/ssLog.hpp"
#include "System2.hpp"
#include "ghc/filesystem.hpp"
#include <fstream>
#include <thread>
#include <chrono>
std::string runcpp2ExecutablePath = "";
std::string downloadBranch = "heads/master";
bool integrationTest = false;
#define DELAYED_OUTPUT(str) \
do \
{ \
if(!integrationTest) \
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); \
ssLOG_BASE(str); \
} while(0)
std::string GetInput(bool allowEmpty = false)
{
if(integrationTest)
{
if(!allowEmpty)
ssLOG_ERROR("GetInput() called with allowEmpty set to false for testing");
DELAYED_OUTPUT("");
return "";
}
std::string input;
bool triggered = false;
do
{
if(triggered && !allowEmpty)
DELAYED_OUTPUT("Empty input is not allowed.");
if(!std::getline(std::cin, input))
{
ssLOG_ERROR("IO Error when trying to get cin");
return "";
}
triggered = true;
}
while(!allowEmpty && input.empty());
return input;
}
bool GetYN_WithDefault(bool defaultY)
{
if(integrationTest)
{
DELAYED_OUTPUT("y");
return defaultY;
}
while(true)
{
std::string input = GetInput(true);
if(input == "y")
return true;
else if(input == "n")
return false;
else if(input.empty())
return defaultY;
else
DELAYED_OUTPUT("Input must either be y or n");
}
}
bool GetYN()
{
while(true)
{
std::string input = GetInput();
if(input == "y")
return true;
else if(input == "n")
return false;
else
DELAYED_OUTPUT("Input must either be y or n");
}
}
bool InitializeRuncpp2ExecutablePath()
{
if(!runcpp2ExecutablePath.empty())
return true;
while(true)
{
System2CommandInfo commandInfo = {0};
SYSTEM2_RESULT result = System2CppRun("runcpp2 --version", commandInfo);
if(result != SYSTEM2_RESULT_SUCCESS)
return false;
int returnCode = 0;
result = System2CppGetCommandReturnValueSync(commandInfo, returnCode, false);
if(result != SYSTEM2_RESULT_SUCCESS)
return false;
if(returnCode == 0)
{
runcpp2ExecutablePath = "runcpp2";
DELAYED_OUTPUT("Successfully found runcpp2 executable");
return true;
}
DELAYED_OUTPUT("It seems that runcpp2 is not added to your PATH environment variable.");
DELAYED_OUTPUT( "You can either specify the path to runcpp2 executable "
"or add it to your PATH environment variable.");
DELAYED_OUTPUT("Do you want to specify the path to runcpp2 executable? [y/n]:");
bool ans = GetYN();
if(ans)
{
DELAYED_OUTPUT("Please enter the path to the runcpp2 executable:");
std::string path = GetInput();
if(!ghc::filesystem::exists(path))
{
DELAYED_OUTPUT("The path you entered does not exist.");
return false;
}
runcpp2ExecutablePath = path;
return true;
}
else
{
DELAYED_OUTPUT("Please add runcpp2 to your PATH environment variable now");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
}
}
return true;
}
bool RunCommand(const std::string& command,
bool expectingZeroReturnValue = true,
bool convertSlashes = true)
{
(void)convertSlashes;
std::string updatedCommand = command;
#ifdef _WIN32
if(convertSlashes)
{
std::string::size_type pos = 0;
while((pos = updatedCommand.find('/', pos)) != std::string::npos)
{
updatedCommand.replace(pos, 1, "\\");
pos++;
}
}
#endif
DELAYED_OUTPUT( "-----------------------\n"
"Output:\n"
"-----------------------");
System2CommandInfo commandInfo = {0};
SYSTEM2_RESULT result = System2CppRun(updatedCommand, commandInfo);
if(result != SYSTEM2_RESULT_SUCCESS)
{
ssLOG_ERROR("Failed to run the command: " << updatedCommand);
ssLOG_ERROR("SYSTEM2_RESULT: " << result);
return false;
}
int returnCode = 0;
result = System2CppGetCommandReturnValueSync(commandInfo, returnCode, false);
if(result != SYSTEM2_RESULT_SUCCESS)
{
ssLOG_ERROR("Command failed: " << updatedCommand);
ssLOG_ERROR("Failed to get the return value of the command: " << result);
return false;
}
if(expectingZeroReturnValue && returnCode != 0)
{
ssLOG_ERROR("Command failed: " << updatedCommand);
ssLOG_ERROR("The command returned a non-zero return value: " << returnCode);
return false;
}
DELAYED_OUTPUT("");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
return true;
}
bool RunCommandWithPrompt( const std::string& command,
bool expectingZeroReturnValue = true,
bool convertSlashes = true)
{
//DELAYED_OUTPUT("> " << command << " # Press enter to continue...");
std::cout << "> " << command << " # Press enter to continue...";
GetInput(true);
DELAYED_OUTPUT("");
return RunCommand(command, expectingZeroReturnValue, convertSlashes);
}
std::string ReadFile(const std::string& path)
{
std::ifstream file(path, std::ios::binary);
if(!file)
return "";
file.seekg(0, std::ios::end);
std::string content;
content.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(&content[0], content.size());
return content;
}
bool WriteFile(const std::string& path, const std::string& content)
{
std::ofstream file(path, std::ios::binary | std::ios::trunc);
if(!file)
return false;
file << content;
return true;
}
bool Chapter1_Runcpp2Executable()
{
DELAYED_OUTPUT( "===========================================\n"
"Chapter 1/3: Using runcpp2 executable\n"
"===========================================\n");
DELAYED_OUTPUT("Let's start by creating a \"tutorial\" directory.");
DELAYED_OUTPUT( "If you want to be in a different directory, "
"stop the script now (ctrl+c) and run it in the directory you want.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
std::error_code ec;
if(!ghc::filesystem::exists("tutorial", ec))
{
if(!ghc::filesystem::create_directory("tutorial", ec))
{
ssLOG_ERROR("Failed to create tutorial directory: " << ec.message());
return false;
}
DELAYED_OUTPUT("Created directory \"tutorial\"");
}
DELAYED_OUTPUT( "From now on, all the files related to this interactive tutorial will be placed "
"in the \"tutorial\" directory");
DELAYED_OUTPUT("You can open your IDE/Editor of choice in the \"tutorial\" directory.");
DELAYED_OUTPUT( "It is recommended to have both this tutorial and your IDE/Editor visible at the "
"same time.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
if(!ghc::filesystem::exists("tutorial/main.cpp", ec))
{
DELAYED_OUTPUT("First let me create a very simple C++ file (\"tutorial/main.cpp\").");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
std::string cppCode = R"(#include <iostream>
int main(int, char**)
{
std::cout << "Hello World" << std::endl;
return 0;
})";
std::ofstream file("tutorial/main.cpp", std::ios::binary);
file << cppCode;
file.close();
}
DELAYED_OUTPUT("A simple hello world file is created (\"tutorial/main.cpp\").");
DELAYED_OUTPUT("Now, let's run it.");
if(!RunCommandWithPrompt(runcpp2ExecutablePath + " tutorial/main.cpp"))
return false;
DELAYED_OUTPUT("Seems simple enough.\n");
DELAYED_OUTPUT("Let's build the script instead of running it.");
DELAYED_OUTPUT("Unless specified, input file is treated as `Executable`\n");
DELAYED_OUTPUT( "We can get the binary files of the script by "
"using the `--build` (or `-b`) option.");
DELAYED_OUTPUT( "And we can specify the output directory for the binary files with `--output` "
"(or `-o`)");
DELAYED_OUTPUT( "We also need to pass the `--executable` (or `-e`) option to "
"explicitly get an executable file. \n"
"See https://neko-box-coder.github.io/runcpp2/latest/guides/"
"building_project_sources/ for more details.\n");
DELAYED_OUTPUT("Let's try it");
if(!RunCommandWithPrompt( runcpp2ExecutablePath +
" --build --output ./tutorial --executable "
"tutorial/main.cpp"))
{
return false;
}
DELAYED_OUTPUT("Let's see what we have in the \"tutorial\" directory.");
#ifdef _WIN32
if(!RunCommandWithPrompt("dir tutorial"))
return false;
#else
if(!RunCommandWithPrompt("ls -lah tutorial"))
return false;
#endif
#ifdef _WIN32
DELAYED_OUTPUT("You should be able to see `main.exe` in the directory.");
#else
DELAYED_OUTPUT("You should be able to see `main` in the directory.");
#endif
DELAYED_OUTPUT("Let's run the executable file to make sure it works.");
if(!RunCommandWithPrompt("./tutorial/main"))
return false;
DELAYED_OUTPUT( "Sometimes you want to remove the cache of the script before running it again.\n"
"You can do that by using the `--rebuild` (or `-rb`) option.");
if(!RunCommandWithPrompt(runcpp2ExecutablePath + " --rebuild ./tutorial/main.cpp"))
return false;
DELAYED_OUTPUT("You can also see the build/run process by changing the log level to `info`.");
DELAYED_OUTPUT("Let's rebuild the cache again and see the build process.");
if(!RunCommandWithPrompt( runcpp2ExecutablePath +
" --rebuild --log-level info ./tutorial/main.cpp"))
{
return false;
}
DELAYED_OUTPUT( "runcpp2 also can give realtime error feedback by using "
"the `--watch` (or `-w`) option.");
DELAYED_OUTPUT("I would love to show it here but it will block this tutorial.");
DELAYED_OUTPUT("Feel free to try it yourself. "
"Make a change, or an error, then run `runcpp2 --watch tutorial/main.cpp`");
DELAYED_OUTPUT("Once you are done, you can revert the changes and continue the tutorial.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "You can find the path to your config file and all the builds "
"with the `--show-config-path` (or `-sc`) option.");
if(!RunCommandWithPrompt(runcpp2ExecutablePath + " --show-config-path"))
return false;
DELAYED_OUTPUT("Feel free to make any changes to the config file.\n");
DELAYED_OUTPUT( "Finally, you can specify your script to be built in the current directory "
"with the `--local` (or `-l`) option. \n"
"This will create and build in the `.runcpp2` directory");
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " --local main.cpp"))
return false;
#ifdef _WIN32
if(!RunCommandWithPrompt("dir tutorial"))
return false;
#else
if(!RunCommandWithPrompt("ls -lah tutorial"))
return false;
#endif
DELAYED_OUTPUT("You can find the details of the rest of the options by running `runcpp2 --help`");
DELAYED_OUTPUT( "Or you can read it at https://neko-box-coder.github.io/runcpp2/latest/"
"program_manual/\n");
DELAYED_OUTPUT("This concludes the 1st chapter of the tutorial.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
return true;
}
bool Chapter2_BuildConfig()
{
DELAYED_OUTPUT( "===========================================\n"
"Chapter 2/3: Build Config\n"
"===========================================\n");
std::error_code ec;
if(!ghc::filesystem::exists("tutorial", ec))
{
ssLOG_ERROR("Missing tutorial directory");
return false;
}
if(!ghc::filesystem::exists("tutorial/main.cpp", ec))
{
ssLOG_ERROR("Missing tutorial/main.cpp");
return false;
}
DELAYED_OUTPUT( "You can specify your build config either as an inline YAML comment or as a "
"separate YAML file.");
DELAYED_OUTPUT( "To set build config with an inline comment, you need to first start your "
"comment with either `/*runcpp2` or `//runcpp2`");
DELAYED_OUTPUT("Space between `//` / `/*` and `runcpp2` is allowed as well.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT("First, let me add a define (WORLD=42) as build config to tutorial/main.cpp");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
std::string fileContent = ReadFile("tutorial/main.cpp");
if(fileContent.empty())
{
ssLOG_ERROR("Failed to read tutorial/main.cpp");
return false;
}
const std::string definesString = R"(/*runcpp2
Defines:
DefaultPlatform:
DefaultProfile: ["WORLD=42"]
*/)";
if(!WriteFile("tutorial/main.cpp", definesString + "\n" + fileContent))
{
ssLOG_ERROR("Failed to write tutorial/main.cpp");
return false;
}
DELAYED_OUTPUT("I have just added the define to the script as an inline YAML comment.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "Now let me add `std::cout << WORLD << std::endl;` to output the value "
"of WORLD.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
size_t returnPos = fileContent.find("return 0;");
if(returnPos == std::string::npos)
{
ssLOG_ERROR("Failed to find return 0; in tutorial/main.cpp");
return false;
}
fileContent.replace(returnPos,
std::string("return 0;").size(),
"std::cout << WORLD << std::endl;\n return 0;");
if(!WriteFile("tutorial/main.cpp", definesString + "\n" + fileContent))
{
ssLOG_ERROR("Failed to write tutorial/main.cpp");
return false;
}
}
DELAYED_OUTPUT("I have just added the output line");
DELAYED_OUTPUT("Now let's run the script");
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " main.cpp"))
return false;
DELAYED_OUTPUT( "You should see the output `42`. \n"
"You can specify different settings for different platforms and profiles.");
DELAYED_OUTPUT( "A platform is basically the Host OS (**NOT** the target OS), "
"so the OS you are running this script on.");
DELAYED_OUTPUT("A profile is a single configuration of compiler/linker toolchain.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "`DefaultPlatform` is the default host platform if no explicit platform "
"is specified.");
DELAYED_OUTPUT("`DefaultProfile` is the default profile if no explicit profile is specified.");
DELAYED_OUTPUT( "So the define I just added will apply to any platform and profile, "
"unless there's a explicit platform/profile specified.");
DELAYED_OUTPUT( "You can have settings that apply to specific platforms (e.g. Linux) and "
"profiles (e.g. msvc).");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "If you remember what I said earlier, you can also specify the build config "
"as a separate YAML file.");
DELAYED_OUTPUT( "I will continue the rest of the chapter with that since it is quite "
"cumbersome to edit tutorial/main.cpp everytime.");
DELAYED_OUTPUT("Let me first remove the inline comment in tutorial/main.cpp.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
std::string fileContent = ReadFile("tutorial/main.cpp");
if(fileContent.empty())
{
ssLOG_ERROR("Failed to read tutorial/main.cpp");
return false;
}
size_t startPos = fileContent.find("/*runcpp2");
size_t endPos = fileContent.find("*/", startPos);
if(startPos != std::string::npos && endPos != std::string::npos)
{
fileContent.erase(startPos, (endPos + 2 + 1 /* newline */) - startPos);
}
if(!WriteFile("tutorial/main.cpp", fileContent))
{
ssLOG_ERROR("Failed to write tutorial/main.cpp");
return false;
}
}
DELAYED_OUTPUT("I have just removed the inline comment in tutorial/main.cpp");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "To have a dedicated build config file, you just need to create a YAML file "
"with the same name as your script file but with a `.yaml` extension.");
DELAYED_OUTPUT("Let me create tutorial/main.yaml");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
const std::string yamlContent = R"(Defines:
DefaultPlatform:
DefaultProfile: ["WORLD=42"])";
if(!WriteFile("tutorial/main.yaml", yamlContent))
{
ssLOG_ERROR("Failed to write tutorial/main.yaml");
return false;
}
}
DELAYED_OUTPUT("Now let me run the script again, nothing should have changed.");
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " main.cpp"))
return false;
DELAYED_OUTPUT("");
DELAYED_OUTPUT("A common build config is to specify other source files.");
DELAYED_OUTPUT("This can be done by adding the paths to the `SourceFiles` field.");
DELAYED_OUTPUT("The script file is implicitly added to this field so you don't need to specify it.");
DELAYED_OUTPUT("Let me add a second C++ file (\"tutorial/Hello.cpp\").");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
std::string fileContent = R"(#include "Hello.hpp"
#include <iostream>
void CallHello()
{
std::cout << "Hello from another C++ file" << std::endl;
}
)";
WriteFile("tutorial/Hello.cpp", fileContent);
}
DELAYED_OUTPUT("Let me also add a header file for the second C++ file (\"tutorial/Hello.hpp\").");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
std::string fileContent = R"(#ifndef HELLO_HPP
#define HELLO_HPP
void CallHello();
#endif // HELLO_HPP)";
WriteFile("tutorial/Hello.hpp", fileContent);
}
DELAYED_OUTPUT("Now let me add the second C++ file to `SourceFiles` in the tutorial/main.yaml file.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
const std::string yamlContent = R"(Defines:
DefaultPlatform:
DefaultProfile: ["WORLD=42"]
SourceFiles:
DefaultPlatform:
DefaultProfile: ["./Hello.cpp"]
)";
WriteFile("tutorial/main.yaml", yamlContent);
}
DELAYED_OUTPUT("The paths to the files are always __relative to the script file__.");
DELAYED_OUTPUT("You can also add include paths for the script to the `IncludePaths` field");
DELAYED_OUTPUT("Although unnecessary in this case, let me add \"./\" to the include paths.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
const std::string yamlContent = R"(Defines:
DefaultPlatform:
DefaultProfile: ["WORLD=42"]
SourceFiles:
DefaultPlatform:
DefaultProfile: ["./Hello.cpp"]
IncludePaths:
DefaultPlatform:
DefaultProfile: ["./"]
)";
WriteFile("tutorial/main.yaml", yamlContent);
}
DELAYED_OUTPUT("Turns out, I still need to edit tutorial/main.cpp to call the function.");
DELAYED_OUTPUT("Let me do that now.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
std::string fileContent = ReadFile("tutorial/main.cpp");
if(fileContent.empty())
{
ssLOG_ERROR("Failed to read tutorial/main.cpp");
return false;
}
size_t returnPos = fileContent.find("return 0;");
if(returnPos == std::string::npos)
{
ssLOG_ERROR("Failed to find return 0; in tutorial/main.cpp");
return false;
}
fileContent.replace(returnPos,
std::string("return 0;").size(),
"CallHello();\n return 0;");
WriteFile("tutorial/main.cpp", std::string("#include \"Hello.hpp\"\n") + fileContent);
}
DELAYED_OUTPUT("Let's run the script again.");
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " main.cpp"))
return false;
DELAYED_OUTPUT("You should see the output `Hello from another C++ file`.");
DELAYED_OUTPUT("");
DELAYED_OUTPUT( "If you **ONLY** have a setting that applies to all platforms and profiles like "
"what we have,");
DELAYED_OUTPUT("you can specify the settings directly.");
DELAYED_OUTPUT("Let me update the tutorial/main.yaml file and show you what I mean.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
const std::string yamlContent = R"(Defines: ["WORLD=42"]
SourceFiles: ["./Hello.cpp"]
IncludePaths: ["./"]
)";
WriteFile("tutorial/main.yaml", yamlContent);
}
DELAYED_OUTPUT("I have just updated the YAML file to omit `DefaultPlatform` and `DefaultProfile`.");
DELAYED_OUTPUT("It's much more concise now. Let's run the script again.");
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " main.cpp"))
return false;
DELAYED_OUTPUT("You should see the same output as before.");
DELAYED_OUTPUT("");
DELAYED_OUTPUT( "Finally, let me show you how to specify different settings for "
"different platforms and profiles.");
DELAYED_OUTPUT("Let's update the compile config to have it generate a preprocessed output.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
const std::string yamlContent = R"(Defines: ["WORLD=42"]
SourceFiles: ["./Hello.cpp"]
IncludePaths: ["./"]
OverrideCompileFlags:
DefaultPlatform:
"g++":
Append: "-E"
Windows:
"msvc":
Append: "/P"
)";
WriteFile("tutorial/main.yaml", yamlContent);
}
DELAYED_OUTPUT( "Since output preprocessed file flag is dependent on the compiler, "
"I have specified it per platform and profile.");
DELAYED_OUTPUT( "You can see \"g++\" is under `DefaultPlatform`, meaning the flags will be "
"applied to all platforms. ");
DELAYED_OUTPUT( "So if you specify your profile to be \"g++\" and you are on Windows, "
"it will use the \"-E\" flag.");
DELAYED_OUTPUT("If you are using msvc and you are on Windows, it will use the \"/P\" flag.");
DELAYED_OUTPUT("Let's run the script now.");
RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " main.cpp");
DELAYED_OUTPUT("");
DELAYED_OUTPUT( "You probably see some errors for linking, this is expected since the "
"preprocessed flag doesn't generate any object files.");
DELAYED_OUTPUT("This is just a demonstration on specifying platform/profile specific settings.");
DELAYED_OUTPUT("But the default profile and settings should be good enough for the most part.");
DELAYED_OUTPUT("Let me remove the flags I have just added.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
{
const std::string yamlContent = R"(Defines: ["WORLD=42"]
SourceFiles: ["./Hello.cpp"]
IncludePaths: ["./"]
)";
WriteFile("tutorial/main.yaml", yamlContent);
}
DELAYED_OUTPUT("Finally, you can generate a build config template which documents all the fields.");
DELAYED_OUTPUT("You can do that by using the `--create-script-template`/ `-t` option.");
DELAYED_OUTPUT("This will either create a new file or prepend the template to the existing file.");
if(!RunCommandWithPrompt(runcpp2ExecutablePath + " -t tutorial/template.yaml"))
return false;
DELAYED_OUTPUT("You can see the template in tutorial/template.yaml");
DELAYED_OUTPUT("");
DELAYED_OUTPUT("This concludes the 2nd chapter of the tutorial.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
return true;
}
bool Chapter3_ExternalDependencies()
{
DELAYED_OUTPUT( "===========================================\n"
"Chapter 3/3: External Dependencies\n"
"===========================================\n");
std::error_code ec;
if(!ghc::filesystem::exists("tutorial", ec))
{
ssLOG_ERROR("Missing tutorial directory");
return false;
}
DELAYED_OUTPUT( "It's good to be able to run a C++ file by itself, "
"but there's a limit to what you can do without any external dependencies.");
DELAYED_OUTPUT("This can be done by adding your dependencies to the `Dependencies` field.");
DELAYED_OUTPUT("The most common and simple one is a header library.");
DELAYED_OUTPUT("Let me query and download an example for you.");
#ifdef _WIN32
if(!RunCommandWithPrompt( "powershell -Command \""
"Invoke-WebRequest https://github.com/Neko-Box-Coder/runcpp2/raw/"
"refs/" + downloadBranch + "/Examples/Logging.cpp "
"-OutFile tutorial/Logging.cpp\"", true, false))
{
return false;
}
#else
if(!RunCommandWithPrompt( "curl -L -o tutorial/Logging.cpp "
"https://github.com/Neko-Box-Coder/runcpp2/raw/refs/" +
downloadBranch + "/Examples/Logging.cpp"))
{
return false;
}
#endif
DELAYED_OUTPUT("I have downloaded the example to tutorial/Logging.cpp");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT("A dependency must contain a \"Source\" to determine where it is from.");
DELAYED_OUTPUT("In this case, it is coming from a \"Git\" repository.");
DELAYED_OUTPUT( "If you have a git submodule, you can point it to a local directory with "
"\"Local\" instead of \"Git\"");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "Next, you have \"LibraryType\" which tells runcpp2 what type of dependency "
"this is. Other options include \"Static\", \"Object\" and \"Shared\"");
DELAYED_OUTPUT("That's pretty much it for a header only library. Let's run it shall we?");
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " Logging.cpp"))
return false;
DELAYED_OUTPUT("Let's try an external shared library");
DELAYED_OUTPUT("Let me query and download an example for you.");
#ifdef _WIN32
if(!RunCommandWithPrompt( "powershell -Command \""
"Invoke-WebRequest https://github.com/Neko-Box-Coder/runcpp2/raw/"
"refs/" + downloadBranch + "/Examples/SDLWindow.cpp "
"-OutFile tutorial/SDLWindow.cpp\"", true, false))
{
return false;
}
#else
if(!RunCommandWithPrompt( "curl -L -o tutorial/SDLWindow.cpp "
"https://github.com/Neko-Box-Coder/runcpp2/raw/refs/" +
downloadBranch + "/Examples/SDLWindow.cpp"))
{
return false;
}
#endif
DELAYED_OUTPUT("I have downloaded the example to tutorial/SDLWindow.cpp");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT("Non header dependency has a few more fields. First we have \"LinkProperties\".");
DELAYED_OUTPUT("This can contain 4 inner fields.");
DELAYED_OUTPUT( "First is \"SearchLibraryNames\". "
"Any binary files that is linkable and contains the search term in the filename "
"will be linked against.");
DELAYED_OUTPUT("For example \"Library\" will match against \"MyLibrary.dll\"");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "Next, we have \"SearchDirectories\". This tells runcpp2 where to search for "
"the binaries.");
DELAYED_OUTPUT( "This is **NOT** recursive search. You need to supply the directories that "
"may contain the binaries we are linking against.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT("Finally, we have \"ExcludeLibraryNames\" and \"AdditionalLinkOptions\".");
DELAYED_OUTPUT("\"ExcludeLibraryNames\" will not link the binaries that match the filename.");
DELAYED_OUTPUT( "\"AdditionalLinkOptions\" is a list of link flags needed when linking against "
"the dependency binaries we found.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
DELAYED_OUTPUT( "The example I have just downloaded will build SDL2 from source, "
"then link against the built binary and display a Window.");
DELAYED_OUTPUT( "It might take a bit of time to build SDL2 but only happens when you run "
"the script for the first time. Let's run it now.");
if(!integrationTest)
{
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " SDLWindow.cpp"))
return false;
}
else
{
DELAYED_OUTPUT("running SDLWindow.cpp skipped for integration testing");
if(!RunCommandWithPrompt("cd tutorial && " + runcpp2ExecutablePath + " --build SDLWindow.cpp"))
return false;
}
DELAYED_OUTPUT("You can also have a dependency as a standalone YAML file which you can import.");
DELAYED_OUTPUT("Let me move the SDL2 dependency to a standalone YAML file.");
DELAYED_OUTPUT("Press enter to continue...");
GetInput(true);
//Try to extract SDL dependency and write it to standalone YAML
{
std::string fileContent = ReadFile("tutorial/SDLWindow.cpp");
if(fileContent.empty())
{
ssLOG_ERROR("Failed to read tutorial/SDLWindow.cpp");
return false;
}
size_t commentStart = fileContent.find("/*");
size_t commentEnd = fileContent.find("*/");
if(commentStart == std::string::npos || commentEnd == std::string::npos)
{
ssLOG_ERROR("Failed to find comment block in tutorial/SDLWindow.cpp");
return false;
}
//Store the comment block (+2 to include the */)
std::string commentBlock = fileContent.substr(commentStart, commentEnd - commentStart + 2);
//Replace the comment block with PLACEHOLDER
std::string newInlineConfig = R"(/* runcpp2
Dependencies:
- Name: SDL2
Source:
ImportPath: "SDL2.yaml"
*/)";
fileContent.replace(commentStart, commentEnd - commentStart + 2, newInlineConfig);
//Find the SDL dependency block
size_t sdlStart = commentBlock.find("Name: SDL2");
if(sdlStart == std::string::npos)
{
ssLOG_ERROR("Failed to find Name: SDL2 in tutorial/SDLWindow.cpp");
return false;
}
//Extract the SDL dependency block
int expectedIndent = 0;
std::string sdlContent;
{
for(int i = (int)sdlStart - 1;
i >= 0 && (fileContent[i] == ' ' || fileContent[i] == '-');
--i)
{
expectedIndent++;
}
size_t sdlEnd = sdlStart;
for(int i = (int)sdlStart + 1; i < (int)commentBlock.length(); ++i)
{
if(commentBlock[i] == '\n')
{
size_t lineStart = i + 1;
if(lineStart >= commentBlock.length())
{
sdlEnd = i;
break;
}
//Count spaces at start of line
int spaces = 0;
while(lineStart + spaces < commentBlock.length())
{
if(commentBlock[lineStart + spaces] == ' ')
spaces++;
//Short empty line, remove it
else if(commentBlock[lineStart + spaces] == '\n' && spaces < expectedIndent)
commentBlock.erase(lineStart, spaces + 1);
else if(commentBlock[lineStart + spaces] == '\r')
continue;
else
break;
}
//If line has fewer spaces than expected indent, we've found the end
if(spaces < expectedIndent)
{
sdlEnd = i;
break;
}
//Update where we last saw valid sdl content
sdlEnd = i;
}
}
sdlContent = commentBlock.substr(sdlStart, sdlEnd - sdlStart);
}
//Trim each line of the SDL dependency block
{
size_t firstNewline = sdlContent.find('\n');
if(firstNewline == std::string::npos)
{
ssLOG_ERROR("Failed to find first newline in tutorial/SDLWindow.cpp");
return false;
}
std::string indentSpaces(expectedIndent, ' ');
indentSpaces = "\n" + indentSpaces;
size_t currentIndentPos = sdlContent.find(indentSpaces, firstNewline);
while(currentIndentPos != std::string::npos)
{
sdlContent.replace(currentIndentPos, indentSpaces.length(), "\n");
currentIndentPos = sdlContent.find(indentSpaces, ++currentIndentPos);
}
}
//Write the SDL dependency block to a standalone YAML file
if(!WriteFile("tutorial/SDL2.yaml", sdlContent))
{
ssLOG_ERROR("Failed to write tutorial/SDL2.yaml");
return false;
}