/
Main.java
1833 lines (1663 loc) · 71.7 KB
/
Main.java
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
package com.laytonsmith.core;
import com.laytonsmith.PureUtilities.ArgumentParser;
import com.laytonsmith.PureUtilities.ArgumentParser.ArgumentBuilder;
import com.laytonsmith.PureUtilities.ArgumentSuite;
import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery;
import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscoveryCache;
import com.laytonsmith.PureUtilities.CommandExecutor;
import com.laytonsmith.PureUtilities.Common.ArrayUtils;
import com.laytonsmith.PureUtilities.Common.FileUtil;
import com.laytonsmith.PureUtilities.Common.OSUtils;
import com.laytonsmith.PureUtilities.Common.RSAEncrypt;
import com.laytonsmith.PureUtilities.Common.StreamUtils;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.PureUtilities.Common.UIUtils;
import com.laytonsmith.PureUtilities.DaemonManager;
import com.laytonsmith.PureUtilities.JavaVersion;
import com.laytonsmith.PureUtilities.MapBuilder;
import com.laytonsmith.PureUtilities.TermColors;
import com.laytonsmith.PureUtilities.XMLDocument;
import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.annotations.api;
import com.laytonsmith.core.apps.AppsApiUtil;
import com.laytonsmith.core.compiler.CompilerEnvironment;
import com.laytonsmith.core.compiler.OptimizationUtilities;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.environments.RuntimeMode;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigCompileGroupException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.extensions.Extension;
import com.laytonsmith.core.extensions.ExtensionManager;
import com.laytonsmith.core.extensions.ExtensionTracker;
import com.laytonsmith.core.functions.FunctionBase;
import com.laytonsmith.core.functions.FunctionList;
import com.laytonsmith.core.functions.Meta;
import com.laytonsmith.core.functions.Scheduling;
import com.laytonsmith.core.telemetry.DefaultTelemetry;
import com.laytonsmith.core.telemetry.Telemetry;
import com.laytonsmith.persistence.PersistenceNetwork;
import com.laytonsmith.persistence.PersistenceNetworkImpl;
import com.laytonsmith.persistence.io.ConnectionMixinFactory;
import com.laytonsmith.tools.ExampleLocalPackageInstaller;
import com.laytonsmith.tools.Interpreter;
import com.laytonsmith.tools.MSLPMaker;
import com.laytonsmith.tools.Manager;
import com.laytonsmith.tools.ProfilerSummary;
import com.laytonsmith.tools.SyntaxHighlighters;
import com.laytonsmith.tools.UILauncher;
import com.laytonsmith.tools.docgen.DocGen;
import com.laytonsmith.tools.docgen.DocGenExportTool;
import com.laytonsmith.tools.docgen.DocGenTemplates;
import com.laytonsmith.tools.docgen.ExtensionDocGen;
import com.laytonsmith.tools.docgen.sitedeploy.APIBuilder;
import com.laytonsmith.tools.docgen.sitedeploy.SiteDeploy;
import com.laytonsmith.tools.pnviewer.PNViewer;
import java.awt.HeadlessException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import jline.console.ConsoleReader;
import org.json.simple.JSONValue;
/**
*
*
*/
public class Main {
private static final boolean IS_DEBUG = java.lang.management.ManagementFactory.getRuntimeMXBean()
.getInputArguments().toString().contains("jdwp");
public static class CmdlineToolCollection {
private final ArgumentSuite suite;
private final Map<ArgumentParser, CommandLineTool> dynamicTools;
public CmdlineToolCollection(ArgumentSuite suite, Map<ArgumentParser, CommandLineTool> dynamicTools) {
this.suite = suite;
this.dynamicTools = dynamicTools;
}
/**
* Gets the argument suite for the command line tools
* @return
*/
public ArgumentSuite getSuite() {
return suite;
}
/**
* Gets the tools themselves, keyed on the ArgumentParser object associated with this tool
* @return
*/
public Map<ArgumentParser, CommandLineTool> getDynamicTools() {
return dynamicTools;
}
}
public static CmdlineToolCollection GetCommandLineTools() {
ArgumentSuite suite = new ArgumentSuite()
.addDescription("These are the command line tools for MethodScript. For more information about a"
+ " particular mode, run the help mode with the mode you need help in as the argument."
+ " To run a command, in general, use the command:\n\n"
+ "\tjava -jar " + MethodScriptFileLocations.getDefault().getJarFile().getName()
+ " <mode name> <[mode specific arguments]>\n"
+ "or\n"
+ "\tmscript -- <mode name> <[mode specific arguments]>\n"
+ "if you have previously installed the command line version.");
Map<ArgumentParser, CommandLineTool> dynamicTools = new HashMap<>();
for(Class<? extends CommandLineTool> ctool : ClassDiscovery.getDefaultInstance()
.loadClassesWithAnnotationThatExtend(tool.class, CommandLineTool.class)) {
try {
CommandLineTool tool = ctool.newInstance();
ArgumentParser ap = tool.getArgumentParser();
String toolName = ctool.getAnnotation(tool.class).value();
suite.addMode(toolName, ap, ctool.getAnnotation(tool.class).undocumented());
String[] aliases = ctool.getAnnotation(tool.class).aliases();
if(aliases != null) {
for(String alias : aliases) {
suite.addModeAlias(alias, toolName);
}
}
dynamicTools.put(ap, tool);
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Could not load " + ctool.getName(), ex);
}
}
return new CmdlineToolCollection(suite, dynamicTools);
}
/**
* For some commands, where we don't need to initialize the discovery engine (which is relatively expensive),
* we can pre-load into this fast startup list. This facility is unfortunately not available to extensions, due
* to the nature of how extensions are discovered, but for built in facilities where it makes sense, there's no
* need to discover them the slow way. However, if we forget to update this class, we will still fallback anyways,
* and always find the classes. Classes that are added to this list must be able to function without extensions,
* and without engine startup, as those will not be loaded when the command is executed.
*/
private static final Class[] FAST_STARTUP = new Class[]{
CopyrightMode.class,
InstallCmdlineMode.class,
NewMode.class,
NewTypeMode.class,
JavaVersionMode.class,
EditPrefsMode.class
};
/**
* In general, since fast startup modes don't load things like preferences and whatnot, we couldn't normally
* get telemetry on those modes. However, this is valuable information to have, so we write the metrics output
* locally, and upload them at another time.
* @param mode
* @param full If this is a full startup, then we check all metrics and upload them, including this mode's
* startup. Otherwise we just log the information to another directory and deal with it later during a full
* startup.
*/
private static void HandleModeStartupTelemetry(String mode, boolean full) {
try {
File cache = new File(MethodScriptFileLocations.getDefault().getCacheDirectory(), "telemetry.cache");
if(!full) {
FileUtil.write(mode + "\n", cache, com.laytonsmith.PureUtilities.Common.FileWriteMode.APPEND, true);
} else {
Telemetry.GetDefault().initializeTelemetry();
if(cache.exists()) {
String[] previousStarts = FileUtil.read(cache).split("\n");
for(String s : previousStarts) {
if(s.trim().equals("")) {
continue;
}
Telemetry.GetDefault().log(DefaultTelemetry.StartupModeMetric.class,
MapBuilder.start("mode", s),
null);
}
cache.delete();
cache.deleteOnExit();
}
Telemetry.GetDefault().log(DefaultTelemetry.StartupModeMetric.class, MapBuilder.start("mode", mode),
null);
}
} catch (Throwable ex) {
// Well, that sucks. Normally we want to report these kinds of things, but in this case, we don't, because
// if telemetry is off, we don't want to bug the user about telemetry stuff at all. Oh well, not much to
// be done here. Though at least if we're debugging, let's report it.
if(IS_DEBUG) {
ex.printStackTrace(StreamUtils.GetSystemErr());
}
}
}
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String[] args) throws Exception {
Implementation.setServerType(Implementation.Type.SHELL);
if(args.length > 0) {
for(Class c : FAST_STARTUP) {
String tool = ((tool) c.getAnnotation(tool.class)).value();
if(args[0].equals(tool)) {
String[] a;
if(args.length > 1) {
a = ArrayUtils.slice(args, 1, args.length - 1);
} else {
a = new String[0];
}
HandleModeStartupTelemetry(tool, false);
CommandLineTool t = (CommandLineTool) c.newInstance();
ArgumentParser.ArgumentParserResults res;
try {
res = t.getArgumentParser().match(a);
} catch (ArgumentParser.ResultUseException | ArgumentParser.ValidationException e) {
// They screwed up the args. Rather than just throwing the exception, or duplicating
// code below, let's just stop trying to do the fast startup mode and skip down to
// normal mode, which will still fail, but will prevent us from having to duplicate
// that code up here.
break;
}
t.execute(res);
return;
}
}
}
AppsApiUtil.ConfigureDefaults();
ClassDiscovery cd = ClassDiscovery.getDefaultInstance();
cd.addThisJar();
MethodScriptFileLocations.setDefault(new MethodScriptFileLocations());
ClassDiscoveryCache cdcCache
= new ClassDiscoveryCache(MethodScriptFileLocations.getDefault().getCacheDirectory());
cd.setClassDiscoveryCache(cdcCache);
MSLog.initialize(MethodScriptFileLocations.getDefault().getJarDirectory());
Prefs.init(MethodScriptFileLocations.getDefault().getPreferencesFile());
Prefs.SetColors();
if(Prefs.UseColors()) {
//Use jansi to enable output to color properly, even on windows.
org.fusesource.jansi.AnsiConsole.systemInstall();
}
cd.addAllJarsInFolder(MethodScriptFileLocations.getDefault().getExtensionsDirectory());
ExtensionManager.AddDiscoveryLocation(MethodScriptFileLocations.getDefault().getExtensionsDirectory());
ExtensionManager.Cache(MethodScriptFileLocations.getDefault().getExtensionCacheDirectory());
ExtensionManager.Initialize(ClassDiscovery.getDefaultInstance());
if(args.length == 0) {
args = new String[]{"help"};
}
ArgumentParser mode;
ArgumentParser.ArgumentParserResults parsedArgs;
CmdlineToolCollection collection = GetCommandLineTools();
ArgumentSuite suite = collection.getSuite();
String helpModeName = HelpMode.class.getAnnotation(tool.class).value();
boolean wasError = false;
try {
ArgumentSuite.ArgumentSuiteResults results = suite.match(args, helpModeName);
mode = results.getMode();
parsedArgs = results.getResults();
} catch (ArgumentParser.ResultUseException | ArgumentParser.ValidationException e) {
// The mode was found, but the arguments are wrong. Unlike the below catch,
// we want to print the help just for this mode.
System.out.println(TermColors.RED + e.getMessage() + "\nSee usage.\n" + TermColors.RESET);
String[] newArgs = new String[]{"help", args[0]};
ArgumentSuite.ArgumentSuiteResults results = suite.match(newArgs, helpModeName);
mode = results.getMode();
parsedArgs = results.getResults();
wasError = true;
} catch (ArgumentSuite.ModeNotFoundException e) {
StreamUtils.GetSystemOut().println(TermColors.RED + e.getMessage() + TermColors.RESET);
mode = suite.getMode(helpModeName);
parsedArgs = null;
wasError = true;
}
if(collection.getDynamicTools().containsKey(mode)) {
CommandLineTool tool = collection.getDynamicTools().get(mode);
tool.setSuite(suite);
if(tool.startupExtensionManager()) {
ExtensionManager.Startup();
}
HandleModeStartupTelemetry(args[0], true);
tool.execute(parsedArgs);
if(wasError) {
System.exit(1);
}
if(!tool.noExitOnReturn()) {
System.exit(0);
}
} else {
// This means the requested module could not be found, but our lookup for the help module also failed.
throw new Error("Should not have gotten here");
}
}
@tool("copyright")
public static class CopyrightMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Prints the copyright and exits.");
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
String buildYear = new Scheduling.simple_date().exec(Target.UNKNOWN, null,
new CString("yyyy", Target.UNKNOWN),
new Meta.engine_build_date().exec(Target.UNKNOWN, null)).val();
StreamUtils.GetSystemOut().println("The MIT License (MIT)\n"
+ "\n"
+ "Copyright (c) 2012-" + buildYear + " Methodscript Contributors\n"
+ "\n"
+ "Permission is hereby granted, free of charge, to any person obtaining a copy of \n"
+ "this software and associated documentation files (the \"Software\"), to deal in \n"
+ "the Software without restriction, including without limitation the rights to \n"
+ "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of \n"
+ "the Software, and to permit persons to whom the Software is furnished to do so, \n"
+ "subject to the following conditions:\n"
+ "\n"
+ "The above copyright notice and this permission notice shall be included in all \n"
+ "copies or substantial portions of the Software.\n"
+ "\n"
+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n"
+ "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS \n"
+ "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR \n"
+ "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \n"
+ "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN \n"
+ "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.");
System.exit(0);
}
}
public static ArgumentBuilder.ArgumentBuilderFinal GetEnvironmentParameter() {
// This needs to be changed once CH code is moved out, as extensions will be able to add new environment
// types. Or perhaps not, if the solution is an embedded approach.
ClassDiscovery cd = ClassDiscovery.getDefaultInstance();
cd.addDiscoveryLocation(ClassDiscovery.GetClassContainer(Main.class));
String envs = StringUtils.Join(cd.getClassesThatExtend(Environment.EnvironmentImpl.class)
.stream()
.map((c) -> c.getClassName())
.collect(Collectors.toSet()), ", ", ", or ");
return new ArgumentBuilder()
.setDescription("The environments to target during compilation. May be one or more of "
+ envs + ", but note that " + GlobalEnv.class.getName() + " and "
+ CompilerEnvironment.class.getName()
+ " are provided for you.")
.setUsageName("environments")
.setOptional()
.setName("environments")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.ARRAY_OF_STRINGS);
}
public static Set<Class<? extends Environment.EnvironmentImpl>> GetEnvironmentValue(
ArgumentParser.ArgumentParserResults parsedArgs) {
List<String> environments = parsedArgs.getStringListArgument("environments", new ArrayList<>());
Set<Class<? extends Environment.EnvironmentImpl>> envs = new HashSet<>();
envs.add(GlobalEnv.class);
envs.add(CompilerEnvironment.class);
for(String e : environments) {
try {
Class c = ClassDiscovery.getDefaultInstance().forName(e).loadClass();
if(!Environment.EnvironmentImpl.class.isAssignableFrom(c)) {
System.out.println("The class " + e + " is not a valid option!");
System.exit(1);
}
envs.add((Class<? extends Environment.EnvironmentImpl>) c);
} catch (ClassNotFoundException ex) {
System.out.println("The class " + e + " could not be found!");
System.exit(1);
}
}
return envs;
}
@tool("install-cmdline")
public static class InstallCmdlineMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Installs MethodScript to your system, so that commandline scripts work. (Currently only unix is supported.)")
.addArgument(new ArgumentBuilder()
.setDescription("Sets the name of the command. This allows support for multiple installations per system.")
.setUsageName("command name")
.setOptional()
.setName("command")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING)
.setDefaultVal("mscript"));
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
Telemetry.GetDefault().doNag();
String commandName = parsedArgs.getStringArgument("command");
Interpreter.install(commandName);
System.exit(0);
}
}
@tool("uninstall-cmdline")
public static class UninstallCmdlineMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Uninstalls the MethodScript interpreter from your system.");
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
Interpreter.uninstall();
System.exit(0);
}
}
@tool(value = "version", aliases = {"-v", "--v", "-version", "--version"})
public static class VersionMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Prints the version of CommandHelper, and exits.");
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
// TODO: This should eventually be changed to use an independent
// versioning scheme for CH and MS.
Telemetry.GetDefault().doNag();
StreamUtils.GetSystemOut().println("You are running "
+ Implementation.GetServerType().getBranding() + " version " + Static.loadSelfVersion());
for(ExtensionTracker e : ExtensionManager.getTrackers().values()) {
StreamUtils.GetSystemOut().println(e.getIdentifier() + ": " + e.getVersion());
}
}
}
@tool("manager")
public static class ManagerMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Launches the built in interactive data manager, which will allow command line access"
+ " to the full persistence database.");
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
Implementation.forceServerType(Implementation.Type.SHELL);
ClassDiscovery.getDefaultInstance()
.addDiscoveryLocation(ClassDiscovery.GetClassContainer(Main.class));
Manager.start();
}
}
@tool("mslp")
public static class MSLPMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Creates an MSLP file based on the directory specified.")
.addArgument(new ArgumentBuilder().setDescription("The path to the folder")
.setUsageName("path/to/folder")
.setRequiredAndDefault())
.addArgument(GetEnvironmentParameter());
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
String mslp = parsedArgs.getStringArgument();
Set<Class<? extends Environment.EnvironmentImpl>> envs = GetEnvironmentValue(parsedArgs);
if(mslp.isEmpty()) {
StreamUtils.GetSystemOut().println("Usage: --mslp path/to/folder");
System.exit(1);
}
MSLPMaker.start(mslp, envs);
}
}
@tool("interpreter")
public static class InterpreterMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Launches the minimal cmdline interpreter.")
.addArgument(new ArgumentBuilder().setDescription("Sets the initial working directory of the"
+ " interpreter. This is optional, but"
+ " is automatically set by the mscript program. The option name is strange, to avoid any"
+ " conflicts with"
+ " script arguments.")
.setUsageName("location")
.setOptional()
.setName("location-----")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING)
.setDefaultVal("."));
}
@Override
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
Telemetry.GetDefault().doNag();
new Interpreter(parsedArgs.getStringListArgument(), parsedArgs.getStringArgument("location-----"));
}
}
@tool("new")
public static class NewMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Creates a blank, executable script in the specified location with the appropriate permissions,"
+ " having the correct hashbang, and ready to be executed. If"
+ " the specified file already exists, it will refuse to create it, unless --force is set.")
.addArgument(new ArgumentBuilder()
.setDescription("Location and name to create the script as. Multiple arguments can be provided,"
+ " and they will create multiple files.")
.setUsageName("file")
.setRequiredAndDefault())
.addArgument(new ArgumentBuilder()
.setDescription("Forces the file to be overwritten, even if it already exists.")
.asFlag().setName('f', "force"));
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws IOException {
CreateNewFiles(parsedArgs.getStringListArgument(), parsedArgs.isFlagSet('f'));
}
public static void CreateNewFiles(List<String> files, boolean force) throws IOException {
String li = OSUtils.GetLineEnding();
for(String file : files) {
File f = new File(file);
if(f.exists() && !force) {
System.out.println(file + " already exists, refusing to create");
continue;
}
f.createNewFile();
f.setExecutable(true);
FileUtil.write("#!/usr/bin/env /usr/local/bin/mscript"
+ li
+ "<!" + li
+ "\tstrict;" + li
+ "\tname: " + f.getName() + ";" + li
+ "\tauthor: " + System.getProperty("user.name") + ";" + li
+ "\tcreated: " + new Scheduling.simple_date().exec(Target.UNKNOWN, null, new CString("yyyy-MM-dd", Target.UNKNOWN)).val() + ";" + li
+ "\tdescription: " + ";" + li
+ ">" + li + li, f, true);
}
}
}
@tool("new-type")
public static class NewTypeMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Creates a new type. This command should only be run at the root of a classLibrary,"
+ " and given the class name, will create the appropriate folder structure (as necessary)"
+ " as well as providing a default file prepopulated with a reasonable template. If the"
+ " file already exists, will refuse to continue.")
.addArgument(new ArgumentBuilder()
.setDescription("The template type to use")
.setUsageName("template")
.setOptional()
.setName('t', "type")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING)
.setDefaultVal("class"))
.addArgument(new ArgumentBuilder()
.setDescription("The class name to create. This should be the fully qualified class"
+ " name.")
.setUsageName("fully qualified class name")
.setRequiredAndDefault()
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING));
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
String clazz = parsedArgs.getStringArgument();
String template = parsedArgs.getStringArgument('t').toLowerCase();
List<String> validTemplates = Arrays.asList("annotation", "class", "enum", "interface");
if(!validTemplates.contains(template)) {
System.err.println("Invalid template type specified. Valid template types are: "
+ validTemplates.toString());
}
String classSimpleName;
String[] split = clazz.split("\\.", -1);
classSimpleName = split[split.length - 1];
String author = System.getProperty("user.name");
String created = new Scheduling.simple_date().exec(Target.UNKNOWN, null,
new CString("yyyy-MM-dd", Target.UNKNOWN)).val();
File file = new File(clazz.replace(".", "/") + ".ms");
if(file.exists()) {
System.err.println("File " + file + " already exists. Refusing to continue.");
System.exit(1);
}
if(file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
String allTemplate;
if(split[0].equals("ms")) {
allTemplate = StreamUtils.GetResource("/templates/new-type-templates/native-all.ms");
} else {
allTemplate = StreamUtils.GetResource("/templates/new-type-templates/all.ms");
}
String typeTemplate = StreamUtils.GetResource("/templates/new-type-templates/" + template + ".ms");
allTemplate = String.format(allTemplate, classSimpleName, author, created, clazz);
typeTemplate = String.format(typeTemplate, clazz);
FileUtil.write(allTemplate + typeTemplate, file);
}
}
@tool("json-api")
public static class JsonTool extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Prints the api.json file to stdout. This takes no parameters.");
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
APIBuilder.main(null);
System.exit(0);
}
@Override
public boolean startupExtensionManager() {
return false;
}
}
@tool("doc-export")
public static class DocExportMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Outputs all known function documentation as a json. This includes known extensions"
+ " as well as the built in functions.")
.addArgument(new ArgumentBuilder()
.setDescription("Provides the path to your extension directory.")
.setUsageName("extension folder")
.setOptional()
.setName("extension-dir")
.setDefaultVal("./CommandHelper/extensions")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING))
.addArgument(new ArgumentBuilder()
.setDescription("The file to output the generated json to. If this parameter is missing, it is"
+ " simply printed to screen.")
.setUsageName("output file")
.setOptional()
.setName('o', "output-file")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING));
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
ClassDiscovery cd = ClassDiscovery.getDefaultInstance();
String extensionDirS = parsedArgs.getStringArgument("extension-dir");
String outputFileS = parsedArgs.getStringArgument("output-file");
OutputStream outputFile = StreamUtils.GetSystemOut();
if(outputFileS != null) {
outputFile = new FileOutputStream(new File(outputFileS));
}
Implementation.forceServerType(Implementation.Type.BUKKIT);
File extensionDir = new File(extensionDirS);
if(extensionDir.exists()) {
//Might not exist, but that's ok, however we will print a warning
//to stderr.
for(File f : extensionDir.listFiles()) {
if(f.getName().endsWith(".jar")) {
cd.addDiscoveryLocation(f.toURI().toURL());
}
}
} else {
StreamUtils.GetSystemErr().println("Extension directory specified doesn't exist: "
+ extensionDirS + ". Continuing anyways.");
}
new DocGenExportTool(cd, outputFile).export();
}
}
@tool("cmdline-args")
public static class CmdlineArgsTool extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription(Implementation.GetServerType().getBranding() + " requires certain arguments"
+ " to be passed to the java program to properly start up."
+ " This tool prints out the arguments that it needs,"
+ " in a version specific manner. Depending on your system, and the version of"
+ " the program, you may get different arguments, but these will always be up"
+ " to date. You can either integrate them into your startup flow manually,"
+ " or dynamically call this command to automatically update it. The command"
+ " may return an empty string. If so, this means that no commandline flags"
+ " are needed.");
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
String args = "";
if(JavaVersion.getMajorVersion() > 8) {
// Need to add the --add-opens values. The values live in interpreter-helper/modules
String modules = Static.GetStringResource("/interpreter-helpers/modules");
modules = modules.replaceAll("(.*)\n", "--add-opens $1=ALL-UNNAMED ");
args += " " + modules;
}
args += "-Xrs ";
StreamUtils.GetSystemOut().println(args.trim());
}
}
@tool("site-deploy")
public static class SiteDeployTool extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Deploys the documentation site, using the preferences specified in the configuration"
+ " file. This mechanism completely re-writes"
+ " the remote site, so that builds are totally reproduceable.")
.addArgument(new ArgumentBuilder()
.setDescription("The path to the config file for deployment")
.setUsageName("config file")
.setOptional()
.setName('c', "config")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING)
.setDefaultVal(MethodScriptFileLocations.getDefault().getSiteDeployFile().getAbsolutePath()))
.addArgument(new ArgumentBuilder()
.setDescription("Generates the preferences file initially, which you can then fill in.")
.asFlag().setName("generate-prefs"))
.addArgument(new ArgumentBuilder()
.setDescription("Generally, when the uploader runs, it checks the remote server to see if"
+ " the file already exists there (and is unchanged compared to the local file). If it is"
+ " unchanged, the upload is skipped. However, even checking with the remote to see"
+ " what the status of the remote file is takes time. If you are the only one uploading"
+ " files, then we can simply use a local cache of what the remote system has, and we"
+ " can skip the step of checking with the remote server for any given file. The cache is"
+ " always populated, whether or not this flag is set, so if you aren't sure if you can"
+ " trust the cache, run once without this flag, then for future runs, you can be sure that"
+ " the local cache is up to date.")
.asFlag().setName("use-local-cache"))
.addArgument(new ArgumentBuilder()
.setDescription("Clears the local cache of all entries, then exits.")
.asFlag().setName("clear-local-cache"))
.addArgument(new ArgumentBuilder()
.setDescription("Validates all of the uploaded web pages, and prints out a summary of the"
+ " results. This uses the value defined in the config file for validation.")
.asFlag().setName('d', "do-validation"))
.addArgument(new ArgumentBuilder()
.setDescription("When set, does not clear the progress bar line. This is mostly useful"
+ " when debugging the site-deploy tool itself.")
.asFlag().setName("no-progress-clear"))
.addArgument(new ArgumentBuilder()
.setDescription("If set, overrides the post-script value in the config.")
.setUsageName("script-location")
.setOptional()
.setName("override-post-script")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING)
.setDefaultVal(""))
.addArgument(new ArgumentBuilder()
.setDescription("If the rsa key is in the non-default location, that location be specified"
+ " here")
.setUsageName("id-rsa-path")
.setOptional()
.setName("override-id-rsa")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING)
.setDefaultVal(""));
/*.addFlag("install", "When installing a fresh server, it is useful to have the setup completely automated. If this flag"
+ " is set, then the server is assumed to be a fresh ubuntu server, with nothing else on it. In that case,"
+ " the server will be installed from scratch automatically. NOTE: This will not account for the fact that"
+ " the documentation website is generally configured to allow for multiple versions of documentation. Old"
+ " versions will not be accounted for or uploaded. This process, if desired, must be done manually. If this"
+ " option is configured, the installation will occur before the upload or processing of files. During installation,"
+ " a \"lock\" file will be created, and if that file is present, it is assumed that the installation"
+ " has already occurred on the instance, and will not be repeated. This is a safety measure to ensure"
+ " that the instance will not attempt to be redeployed, making it safe to always add the install"
+ " flag. If this flag is set, additional options need to be added to the config file. The remote server"
+ " is assumed to be an already running AWS ubuntu instance, with security groups configured and a pem"
+ " file available, but no login is necessary.")*/
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
boolean clearLocalCache = parsedArgs.isFlagSet("clear-local-cache");
if(clearLocalCache) {
PersistenceNetwork p = SiteDeploy.getPersistenceNetwork();
if(p == null) {
System.out.println("Cannot get reference to persistence network");
System.exit(1);
return;
}
DaemonManager dm = new DaemonManager();
p.clearKey(dm, new String[]{"site_deploy", "local_cache"});
dm.waitForThreads();
System.out.println("Local cache cleared");
System.exit(0);
}
boolean generatePrefs = parsedArgs.isFlagSet("generate-prefs");
boolean useLocalCache = parsedArgs.isFlagSet("use-local-cache");
boolean doValidation = parsedArgs.isFlagSet("do-validation");
boolean noProgressClear = parsedArgs.isFlagSet("no-progress-clear");
String configString = parsedArgs.getStringArgument("config");
String overridePostScript = parsedArgs.getStringArgument("override-post-script");
String overrideIdRsa = parsedArgs.getStringArgument("override-id-rsa");
if(overrideIdRsa.equals("")) {
overrideIdRsa = null;
}
if("".equals(configString)) {
System.err.println("Config file missing, check command and try again");
System.exit(1);
}
File config = new File(configString);
SiteDeploy.run(generatePrefs, useLocalCache, config, "", doValidation, !noProgressClear,
overridePostScript, overrideIdRsa);
}
}
@tool("api")
public static class APIMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Prints documentation for the function specified, then exits. The argument is actually"
+ " a regex, with ^ and $ added to it, so if you would like to search the function list,"
+ " you can instead provide the rest of the regex. If multiple matches are found, the full"
+ " list of matches is printed out. For instance \"array.*\" will return all the functions"
+ " that start with the word \"array\".")
.addArgument(new ArgumentBuilder()
.setDescription("The name of the function to print the information for")
.setUsageName("functionRegex")
.setRequiredAndDefault()
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING))
.addArgument(new ArgumentBuilder()
.setDescription("Instead of displaying the results in the console, launches the website with"
+ " this function highlighted. The local documentation is guaranteed to be consistent"
+ " with your local version of MethodScript, while the online results may be slightly"
+ " stale, or may be from a different build, but the results are generally richer.")
.asFlag().setName('o', "online"))
.addArgument(new ArgumentBuilder()
.setDescription("Also prints out the examples for the function (if any).")
.asFlag().setName('e', "examples"))
.addArgument(new ArgumentBuilder()
.setDescription("The API platform to use. By default, INTERPRETER_JAVA, but may be one of "
+ StringUtils.Join(api.Platforms.values(), ", ", ", or "))
.setUsageName("platform")
.setOptional()
.setName("platform")
.setArgType(ArgumentBuilder.BuilderTypeNonFlag.STRING)
.setDefaultVal("INTERPRETER_JAVA"));
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
String function = parsedArgs.getStringArgument();
boolean examples = parsedArgs.isFlagSet('e');
api.Platforms platform = api.Platforms.valueOf(parsedArgs.getStringArgument("platform"));
if("".equals(function)) {
StreamUtils.GetSystemErr().println("Usage: java -jar CommandHelper.jar api <function name>");
System.exit(1);
}
List<FunctionBase> fl = new ArrayList<>();
for(FunctionBase fb : FunctionList.getFunctionList(platform, null)) {
if(fb.getName().matches("^" + function + "$")) {
fl.add(fb);
}
}
if(fl.isEmpty()) {
StreamUtils.GetSystemErr().println("The function '" + function + "' was not found.");
System.exit(1);
} else if(fl.size() == 1) {
FunctionBase f = fl.get(0);
if(parsedArgs.isFlagSet("online")) {
String url = String.format("https://methodscript.com/docs/%s/API/functions/%s",
MSVersion.LATEST.toString(), f.getName());
System.out.println("Launching browser to " + url);
if(!UIUtils.openWebpage(new URL(url))) {
System.err.println("Could not launch browser");
}
} else {
StreamUtils.GetSystemOut().println(Interpreter.formatDocsForCmdline(f.getName(), examples));
}
} else {
StreamUtils.GetSystemOut().println("Multiple function matches found:");
for(FunctionBase fb : fl) {
StreamUtils.GetSystemOut().println(fb.getName());
}
}
System.exit(0);
}
}
@tool("verify")
public static class VerifyMode extends AbstractCommandLineTool {
@Override
public ArgumentParser getArgumentParser() {
return ArgumentParser.GetParser()
.addDescription("Compiles the given file, returning a json describing the errors in the file, or"
+ " returning nothing if the file compiles cleanly. The target environment(s)"
+ " must be specified if not targetting command line.")
.addArgument(new ArgumentBuilder()
.setDescription("The file to check")
.setUsageName("file")
.setRequiredAndDefault())
.addArgument(GetEnvironmentParameter());
}
@Override
public boolean startupExtensionManager() {
return false;
}
@Override
public void execute(ArgumentParser.ArgumentParserResults parsedArgs) throws Exception {
String file = parsedArgs.getStringArgument();
if("".equals(file)) {
StreamUtils.GetSystemErr().println("File parameter is required.");
System.exit(1);
}
Environment env = Environment.createEnvironment(new CompilerEnvironment());
env.getEnv(CompilerEnvironment.class).setLogCompilerWarnings(false);
Set<Class<? extends Environment.EnvironmentImpl>> envs = GetEnvironmentValue(parsedArgs);
File f = new File(file);
String script = FileUtil.read(f);
try {
try {
MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, env, f, file.endsWith("ms")), null,
envs);
} catch (ConfigCompileException ex) {
Set<ConfigCompileException> s = new HashSet<>(1);
s.add(ex);
throw new ConfigCompileGroupException(s);
}
} catch (ConfigCompileGroupException ex) {
List<Map<String, Object>> err = new ArrayList<>();
for(ConfigCompileException e : ex.getList()) {
Map<String, Object> error = new HashMap<>();
error.put("msg", e.getMessage());
error.put("file", e.getFile().getAbsolutePath());
error.put("line", e.getLineNum());
error.put("col", e.getColumn());
// TODO: Need to track target length for this
error.put("len", 0);
err.add(error);
}
String serr = JSONValue.toJSONString(err);
StreamUtils.GetSystemOut().println(serr);
}
}