示例#1
3
        public ILauncher HandleArguments(string[] args)
        {
            try
            {
                if (args != null) Log.Debug(string.Join(Environment.NewLine, args));
                if (args.Length < 2) return new MainLauncher();
                Log.Info("Has arguments");
                if (args[1].StartsWith("octgn://", StringComparison.InvariantCultureIgnoreCase))
                {
                    Log.Info("Using protocol");
                    var uri = new Uri(args[1]);
                    return HandleProtocol(uri);
                }
                var tableOnly = false;
                int? hostport = null;
                Guid? gameid = null;
                string deckPath = null;
                var os = new Mono.Options.OptionSet()
                         {
                             { "t|table", x => tableOnly = true },
                             { "g|game=",x=> gameid=Guid.Parse(x)},
                             { "d|deck=",x=>deckPath= x},
                             {"x|devmode",x=>DevMode=true}
                         };
                try
                {
                    os.Parse(args);
                }
                catch (Exception e)
                {
                    Log.Warn("Parse args exception: " + String.Join(",", Environment.GetCommandLineArgs()), e);
                }
                if (tableOnly)
                {
                    return new TableLauncher(hostport, gameid);
                }

                if (File.Exists(args[1]))
                {
                    Log.Info("Argument is file");
                    var fi = new FileInfo(args[1]);
                    if (fi.Extension.Equals(".o8d", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Log.Info("Argument is deck");
                        deckPath = args[1];
                    }
                }

                if (deckPath != null)
                {
                    return new DeckEditorLauncher(deckPath);
                }
            }
            catch (Exception e)
            {
                Log.Error("Error handling arguments", e);
                if (args != null) Log.Error(string.Join(Environment.NewLine, args));
            }
            return new MainLauncher();
        }
示例#2
0
		static bool ParseArgs(string[] args)
		{
			bool show_help = false;

			var p = new Mono.Options.OptionSet() {
				{ "q|quick", "quick run", _ => QuickRun = true },
				{ "p|protobuf", "run protobuf tests", _ => RunProtoBufTests = true },
				{ "v|verify", "verify results", _ => EnableResultCheck = true },
				{ "threads=", "number of threads", (int v) => NumThreads = v },
				{ "share", "share serializer between threads", _ => ShareSerializer = true },
				{ "h|help",  "show help", _ => show_help = true },
			};

			List<string> extra;

			try
			{
				extra = p.Parse(args);
			}
			catch (Mono.Options.OptionException e)
			{
				Console.WriteLine(e.Message);
				return false;
			}

			if (show_help || extra.Count > 0)
			{
				p.WriteOptionDescriptions(Console.Out);
				return false;
			}

			return true;
		}
示例#3
0
    public ParametersModel Parse(string[] args)
    {
      var p = new ParametersModel();
      var options = new Mono.Options.OptionSet();

      options.Add("h|help", "prints the help", s => p.Action = ActionType.WriteDescripton);
      options.Add("t|test-connection", "tries to connect to the server using the specified credentials", s => p.Action = ActionType.TestConnection);
      options.Add("b|base-folder=", "use the supplied directory as the base folder for the import", s => p.BaseFolder = s);
      options.Add("v|vault=", "use the specified vault", s => p.Vault = s);
      options.Add("u|user="******"use the specified user", s => p.User = s);
      options.Add("s|server=", "use the specified server", s => p.Server = s);
      options.Add("p|password="******"use the specified password", s => p.Password = s);
      options.Add("c|csv=", "import based on the csv file", s => { p.Action = ActionType.CsvImport; p.CsvImportFile = s; });
      options.Add("d|delimiter=", "csv delimiter", s => p.Delimiter = s);
      options.Add("destroy-by-class=", "destroy objects of the following classes, use Comma ',' as a separator for multiple classes",
        s => { 
          p.Action = ActionType.DestroyObjectsOfClasses;
          p.DestroyObjectOfClasses = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        });
      options.Add("destroy-by-objecttype=", "destroy objects of the specified object types, use Comma ',' as a separator for multiple classes",
        s =>
        {
          p.Action = ActionType.DestroyObjectsOfObjectTypes;
          p.DestroyObjectsOfObjectTypes = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        });
      options.Add("lc|list-classes", "list all classes and their object counts", s => p.Action = ActionType.ListClassesAndObjects);
      options.Add("lo|list-objecttypes", "list all object types and their object counts", s => p.Action = ActionType.ListObjectTypesAndObjects);

      options.Parse(args);
      p.Options = options;
      return p;
    }
示例#4
0
        static void Help(string id, string command, MonoOptionSet options)
        {
            var name = Lazy.Create(() => Path.GetFileNameWithoutExtension(VersionInfo.FileName));
            var opts = Lazy.Create(() => options.WriteOptionDescriptionsReturningWriter(new StringWriter {
                NewLine = Environment.NewLine
            }).ToString());
            var product = Lazy.Create(() => VersionInfo.ProductName);
            var version = Lazy.Create(() => new Version(VersionInfo.FileVersion));

            using var stream = GetManifestResourceStream($"help.{id ?? command}.txt");
            using var reader = new StreamReader(stream);
            using var e      = reader.ReadLines();
            while (e.MoveNext())
            {
                var line =
                    Regex.Replace(e.Current,
                                  @"\$([A-Z][A-Z_]*)\$",
                                  m => m.Groups[1].Value switch
                {
                    "NAME" => name.Value,
                    "COMMAND" => command,
                    "PRODUCT" => product.Value,
                    "VERSION" => version.Value.Trim(3).ToString(),
                    "OPTIONS" => opts.Value,
                    _ => string.Empty
                });
示例#5
0
        static void ParseCommandLineArgs(string[] args)
        {
            var showHelp = false;

            var options = new Mono.Options.OptionSet()
            {
                { "abi=", "ABI triple to generate", v => Abis.Add(v) },
                { "o|out=", "output directory", v => OutputDir = v },
                { "maccore=", "include directory", v => MaccoreDir = v },
                { "monodroid=", "include directory", v => MonodroidDir = v },
                { "mono=", "include directory", v => MonoDir = v },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            try {
                options.Parse(args);
            }
            catch (Mono.Options.OptionException e) {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            if (showHelp)
            {
                // Print usage and exit.
                Console.WriteLine("{0} [--abi=triple] [--out=dir] "
                                  + "[--monodroid/maccore=dir] [--mono=dir]",
                                  AppDomain.CurrentDomain.FriendlyName);
                Environment.Exit(0);
            }
        }
示例#6
0
        static void ParseCommandLineArgs(string[] args)
        {
            var showHelp = false;

            var options = new Mono.Options.OptionSet()
            {
                { "abi=", "ABI triple to generate", v => Abis.Add(v) },
                { "o|out=", "output directory", v => OutputDir = v },
                { "maccore=", "include directory", v => MaccoreDir = v },
                { "monodroid=", "top monodroid directory", v => MonodroidDir = v },
                { "android-ndk=", "Path to Android NDK", v => AndroidNdkPath = v },
                { "targetdir=", "Path to the directory containing the mono build", v => TargetDir = v },
                { "mono=", "include directory", v => MonoDir = v },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            try {
                options.Parse(args);
            }
            catch (Mono.Options.OptionException e) {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            if (showHelp)
            {
                // Print usage and exit.
                Console.WriteLine("{0} <options>",
                                  AppDomain.CurrentDomain.FriendlyName);
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
        }
        public ParametersModel Parse(string[] args)
        {
            var p       = new ParametersModel();
            var options = new Mono.Options.OptionSet();

            options.Add("h|help", "prints the help", s => p.Action                   = ActionType.WriteDescription);
            options.Add("v|vault=", "use the specified vault", s => p.Vault          = s);
            options.Add("u|user="******"use the specified user", s => p.User             = s);
            options.Add("s|server=", "use the specified server", s => p.Server       = s);
            options.Add("p|password="******"use the specified password", s => p.Password = s);
            options.Add("destroy-by-class=", "destroy objects of the following classes, use Comma ',' as a separator for multiple classes",
                        s => {
                p.Action = ActionType.DestroyObjectsOfClasses;
                p.DestroyObjectOfClasses = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            });
            options.Add("destroy-by-objecttype=", "destroy objects of the specified object types, use Comma ',' as a separator for multiple classes",
                        s =>
            {
                p.Action = ActionType.DestroyObjectsOfObjectTypes;
                p.DestroyObjectsOfObjectTypes = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            });
            options.Add("lc|list-classes", "list all classes and their object counts", s => p.Action          = ActionType.ListClassesAndObjects);
            options.Add("lo|list-objecttypes", "list all object types and their object counts", s => p.Action = ActionType.ListObjectTypesAndObjects);

            options.Parse(args);
            p.Options = options;
            return(p);
        }
示例#8
0
        public ParametersModel Parse(string[] args)
        {
            var p = new ParametersModel();
              var options = new Mono.Options.OptionSet();

              options.Add("h|help", "prints the help", s => p.Action = ActionType.WriteDescription);
              options.Add("v|vault=", "use the specified vault", s => p.Vault = s);
              options.Add("u|user="******"use the specified user", s => p.User = s);
              options.Add("s|server=", "use the specified server", s => p.Server = s);
              options.Add("p|password="******"use the specified password", s => p.Password = s);
              options.Add("destroy-by-class=", "destroy objects of the following classes, use Comma ',' as a separator for multiple classes",
            s => {
              p.Action = ActionType.DestroyObjectsOfClasses;
              p.DestroyObjectOfClasses = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            });
              options.Add("destroy-by-objecttype=", "destroy objects of the specified object types, use Comma ',' as a separator for multiple classes",
            s =>
            {
              p.Action = ActionType.DestroyObjectsOfObjectTypes;
              p.DestroyObjectsOfObjectTypes = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            });
              options.Add("lc|list-classes", "list all classes and their object counts", s => p.Action = ActionType.ListClassesAndObjects);
              options.Add("lo|list-objecttypes", "list all object types and their object counts", s => p.Action = ActionType.ListObjectTypesAndObjects);

              options.Parse(args);
              p.Options = options;
              return p;
        }
示例#9
0
        static bool ParseArgs(string[] args)
        {
#if !NET35 && !NET40
            bool show_help = false;
            var  p         = new Mono.Options.OptionSet()
            {
                { "q|quick", "quick run", _ => QuickRun = true },
                { "p|protobuf", "run protobuf tests", _ => RunProtoBufTests = true },
                { "v|verify", "verify results", _ => EnableResultCheck = true },
                { "threads=", "number of threads", (int v) => NumThreads = v },
                { "share", "share serializer between threads", _ => ShareSerializer = true },
                { "h|help", "show help", _ => show_help = true },
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (Mono.Options.OptionException e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }

            if (show_help || extra.Count > 0)
            {
                p.WriteOptionDescriptions(Console.Out);
                return(false);
            }
#endif
            return(true);
        }
示例#10
0
        static void parseArgs(string[] args)
        {
            String sde = "", tab = "";
            bool   expData = false, getMeta = false;
            string fname    = "gdbexp.xml";
            bool   showHelp = false;

            var opt = new Mono.Options.OptionSet()
            {
                { "h|?|help", "Show usage help", v => showHelp = true },
                { "c=", "Sde connection filename (c:\\db.sde)", v => sde = v },
                { "t=", "Tab names list (T.TAB1,T.TAB2)", v => tab = v },
                { "d", "If set, export data (not only schema)", v => expData = true },
                { "m", "If set, export metadata", v => getMeta = true },
                { "f=", "Output filename (gdbexp.xml by default)", v => fname = v },
            };

            opt.Parse(args);

            if (sde == "" || tab == "" || showHelp != false)
            {
                opt.WriteOptionDescriptions(Console.Out);
                throw (new Exception("Wrong args, " +
                                     "usage example: gdbexport2xml.exe -c=c:\\t\\test.sde -t=T.TAB1,T.TAB2"));
            }

            Log.p(String.Format("get params: sdeConnFname [{0}], tabNames [{1}], " +
                                "expData [{2}], expMeta [{3}], expFile [{4}]",
                                sde, tab, expData, getMeta, fname));
            expGDB2XML p = new expGDB2XML(sde, tab, expData, getMeta, fname);

            mTask = p;
        } // method parseArgs
示例#11
0
        private static void Main(string[] args)
        {
            var sourceControlPath = string.Empty;
            var rootPath          = string.Empty;
            var files             = new List <string>();
            var options           = new Mono.Options.OptionSet
            {
                { "s|src:", "The path to the source control system.", x => sourceControlPath = x },
                { "r|root:", "The root path under which all source code files belong.", x => rootPath = x },
                { "p|pdb:", "The fully qualified path to the one or more debug (PDB) files.", files.Add }
            };

            options.Parse(args);

            var symbols = files.Select(x => x.Standardize())
                          .Where(File.Exists)
                          .Select(x => new DebugSymbol(x, rootPath))
                          .ToArray();

            var indexer = new NetworkShareIndexer(sourceControlPath);

            foreach (var symbol in symbols)
            {
                indexer.Index(symbol);
            }
        }
示例#12
0
        private static void showHelpAndExit(Mono.Options.OptionSet options, String message = null)
        {
            StringWriter writer = new StringWriter();

            if (message == null)
            {
                writer.WriteLine("Requested Help page");
            }
            else
            {
                writer.WriteLine(message);
            }

            writer.WriteLine("Usage: {0} [options] --generate|--convert --rootlib|--subdir [--] lib-name [path] [outpath]", codename);
            writer.WriteLine("  lib-name defines library target name");
            writer.WriteLine("  path defines working directory (default is .)");
            writer.WriteLine("  outpath defines output directory (default is .)");
            writer.WriteLine("Options : ");
            options.WriteOptionDescriptions(writer);

            if (message == null)
            {
                throw new CodeExit(writer.ToString());
            }
            else
            {
                throw new CodeException(writer.ToString());
            }
        }
示例#13
0
 static void ShowHelp(Mono.Options.OptionSet p)
 {
     Console.WriteLine("Usage: delta [OPTIONS] {fileA} {fileB}");
     Console.WriteLine("cmp a with b and writes out the delta");
     Console.WriteLine();
     Console.WriteLine("Options:");
     p.WriteOptionDescriptions(Console.Out);
 }
示例#14
0
 static void ShowHelp(Mono.Options.OptionSet p)
 {
     Console.WriteLine("Usage: CsvToPly [OPTIONS]+ input.csv output.ply");
     Console.WriteLine("Converts a mesh CSV from PIX to a PLY mesh");
     Console.WriteLine();
     Console.WriteLine("Options:");
     p.WriteOptionDescriptions(Console.Out);
 }
示例#15
0
        protected virtual OutOfProcessServerOptions ParseOptions(string[] args, out Mono.Options.OptionSet Options)
        {
            var ret = new OutOfProcessServerOptions();

            ret.Parse(args, out Options);

            return(ret);
        }
 public static void ShowHelp(Mono.Options.OptionSet p)
 {
     Console.WriteLine("Usage: hac.exe [OPTIONS]");
     Console.WriteLine("Perform Hierarchical Agglomerative Clustering on a given set of data.");
     Console.WriteLine("The data consists of sets of coordinates of points in multidimensional space.");
     Console.WriteLine();
     Console.WriteLine("Options:");
     p.WriteOptionDescriptions(Console.Out);
 }
示例#17
0
 public WindowsPathResolver()
 {
     m_options = new Mono.Options.OptionSet();
     m_options.Add("v|verbose", "Verbose mode", v => { m_verbose = true; });
     m_options.Add("f|file", "Want file resolution", v => { m_resolution = Resolution.File; });
     m_options.Add("d|directory", "Want directory resolution", v => { m_resolution = Resolution.Directory; });
     m_options.Add("cmake", "CMake style path", v => { m_path_style = PathStyle.CMake; });
     m_options.Add("h|help", "Show help page", v => { m_show_help = true; });
 }
示例#18
0
 static void ShowHelp(Mono.Options.OptionSet p)
 {
     Console.Error.WriteLine("Usage: cp [OPTIONS] {sourceBase} {targetBase} {filename}"
                             + "\ncopies files given by name in a textfile relative to {sourceBase} and {targetBase}."
                             + "\n- when the lines are tab-separated the last column is used as filename."
                             + "\n- when the columen left next to the filename can by converted to a number, it is treated as the filesize to show the progress"
                             );
     Console.Error.WriteLine("\nOptions:");
     p.WriteOptionDescriptions(Console.Error);
 }
示例#19
0
        public Task <int> Run(string[] arguments)
        {
            var opts = new Mono.Options.OptionSet {
                { "list", "Lists all available generators", s => ListGenerators() },
            };

            var remainingArgs = opts.Parse(arguments);

            return(Task.FromResult(0));
        }
示例#20
0
        static void Main(string[] args)
        {
            bool show_help = false;

            var p = new Mono.Options.OptionSet()
            {
                { "q|quick", "quick run", _ => QuickRun = true },
                { "p|protobuf", "run protobuf tests", _ => RunProtoBufTests = true },
                { "v|verify", "verify results", _ => EnableResultCheck = true },
                { "threads=", "number of threads", (int v) => NumThreads = v },
                { "share", "share serializer between threads", _ => ShareSerializer = true },
                { "h|help", "show help", _ => show_help = true },
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (Mono.Options.OptionException e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            if (show_help || extra.Count > 0)
            {
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            if (ShareSerializer)
            {
                s_sharedSerializer = Tester.CreateSerializer();
            }

            List <Thread> threads = new List <Thread>();

            for (int i = 0; i < NumThreads; ++i)
            {
                var thread = new Thread(Test);
                threads.Add(thread);
            }

            foreach (var thread in threads)
            {
                thread.Start();
            }

            foreach (var thread in threads)
            {
                thread.Join();
            }
        }
示例#21
0
        static void ParseCommandLineArgs(string[] args)
        {
            var showHelp = args.Length == 0;

            string vsVersions = string.Join(", ",
                                            Enum.GetNames(typeof(VisualStudioVersion))
                                            .Select(s => s.StartsWith("VS", StringComparison.InvariantCulture) ? s.Substring(2) : s));

            var optionSet = new Mono.Options.OptionSet()
            {
                { "gen=", "target generator (C, C++, Obj-C, Java)", v => Generator = v },
                { "p|platform=", "target platform (iOS, macOS, Android, Windows)", v => Platform = v },
                { "o|out|outdir=", "output directory", v => OutputDir = v },
                { "c|compile", "compiles the generated output", v => CompileCode = true },
                { "d|debug", "enables debug mode for generated native and managed code", v => DebugMode = true },
                { "t|target=", "compilation target (static, shared, app)", v => Target = ConvertToCompilationTarget(v) },
                { "dll|shared", "compiles as a shared library", v => Target = CompilationTarget.SharedLibrary },
                { "static", "compiles as a static library", v => Target = CompilationTarget.StaticLibrary },
                { "vs=", $"Visual Studio version for compilation: {vsVersions} (defaults to Latest)", v => VsVersion = v },
                { "v|verbose", "generates diagnostic verbose output", v => Verbose = true },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            Generator = "C";
            VsVersion = "latest";

            try
            {
                Assemblies = optionSet.Parse(args);
            }
            catch (Mono.Options.OptionException e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            if (showHelp)
            {
                // Print usage and exit.
                Console.WriteLine("{0} [options]+ ManagedAssembly.dll", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine("Generates target language bindings for interop with managed code.");
                Console.WriteLine();
                optionSet.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }

            if (Assemblies == null || Assemblies.Count == 0)
            {
                Console.WriteLine("At least one managed assembly must be passed as input.");
                Environment.Exit(0);
            }
        }
示例#22
0
    public ParametersModel GetParameters(string[] args)
    {
      var p = new ParametersModel();
      var optionSet = new Mono.Options.OptionSet();

      optionSet.Add("s=|source-file", "specify the source file to watch", s => p.SourceFile = s);
      optionSet.Add("t=|target-file", "specify the target file path", s => p.TargetFile = s);
      optionSet.Add("?|h|help", "prints this description", s => p.Action = ActionType.Help);
      p.OptionSet = optionSet;

      optionSet.Parse(args);

      return p;
    }
示例#23
0
        private void FillStartupParameters()
        {
            Parameters.PipeName = "mysql";

            // get our host information
            Parameters.HostName = WinService.MachineName == "." ? "localhost" : WinService.MachineName;
            Parameters.HostIPv4 = Utilities.GetIPv4ForHostName(Parameters.HostName);

            RegistryKey key = Registry.LocalMachine.OpenSubKey(string.Format(@"SYSTEM\CurrentControlSet\Services\{0}", WinService.ServiceName));

            if (key != null)
            {
                string imagepath = (string)key.GetValue("ImagePath", null);
                key.Close();
                if (imagepath == null)
                {
                    return;
                }

                string[] args = Utilities.SplitArgs(imagepath);
                RealMySqlService = IsRealMySQLService(args[0]);

                // Parse our command line args
                var p = new Mono.Options.OptionSet()
                        .Add("defaults-file=", "", v => Parameters.DefaultsFile = v)
                        .Add("port=|P=", "", v => int.TryParse(v, out Parameters.Port))
                        .Add("enable-named-pipe", v => Parameters.NamedPipesEnabled = true)
                        .Add("socket=", "", v => Parameters.PipeName = v);
                p.Parse(args);
            }
            if (Parameters.DefaultsFile == null)
            {
                return;
            }

            // we have a valid defaults file
            try
            {
                IniFile f = new IniFile(Parameters.DefaultsFile);
                int.TryParse(f.ReadValue("mysqld", "port", Parameters.Port.ToString()), out Parameters.Port);
                Parameters.PipeName = f.ReadValue("mysqld", "socket", Parameters.PipeName);
                // now see if named pipes are enabled
                Parameters.NamedPipesEnabled = Parameters.NamedPipesEnabled || f.HasKey("mysqld", "enable-named-pipe");
            }
            catch
            {
                // ignored
            }
        }
示例#24
0
        static void Main(string[] args)
        {
            bool showOptions = true;
            bool showHelp    = false;
            var  opts        = new Mono.Options.OptionSet
            {
                { "h|help", "Show this help message and exit", n => showHelp = n != null },
                { "s|startup", "Startup mode, don't show the configuration editor", n => showOptions = n == null }
            };

            opts.Parse(args);

            if (showHelp)
            {
                opts.WriteOptionDescriptions(Console.Out);
                return;
            }

            if (mutex.WaitOne(TimeSpan.Zero, true))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var appDataPath = FormUtils.GetApplicationDirectory();

                AltCodeData altCodes;
                try
                {
                    altCodes = AltCodesXmlParser.LoadFromFile(Path.Combine(appDataPath, "alt_codes.xml"));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(R.ErrorFailedToLoadAltCodes + ex.Message, R.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

#if DEBUG
                Data.UnicodeAltCode.DebugPrintMissing(altCodes.AltCodes);
#endif

                Application.Run(new KneeboardApplication(showOptions, altCodes));
            }
            else
            {
                Console.WriteLine("Instance already running. Exiting...");
            }
        }
示例#25
0
            Mono.Options.OptionSet InitializeOptionsParser()
            {
                var result = new Mono.Options.OptionSet
                {
                    { "parameter:", "Add parameter", value => {
                          value = value.Trim('\"');
                          var parts = value.Split('=');
                          if (parts.Length == 2)
                          {
                              _parameters.Add(parts[0], parts[1]);
                          }
                      } },
                    { "project:", "Set the project", value => {
                          ProjectFile = value;
                      } }
                };

                return(result);
            }
示例#26
0
        static void ParseCommandLineArgs(string[] args)
        {
            var showHelp = args.Length == 0;

            var optionSet = new Mono.Options.OptionSet()
            {
                { "gen=", "target generator (C, C++, Obj-C)", v => Generator = v },
                { "o|out=", "output directory", v => OutputDir = v },
                { "c|compile", "compiles the generated output", v => CompileCode = true },
                { "dll|shared", "compiles as a shared library / DLL", v => SharedLibrary = true },
                { "v|verbose", "generates diagnostic verbose output", v => Verbose = true },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            Generator = "C";

            try
            {
                Assemblies = optionSet.Parse(args);
            }
            catch (Mono.Options.OptionException e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            if (showHelp)
            {
                // Print usage and exit.
                Console.WriteLine("{0} [options]+ ManagedAssembly.dll", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine("Generates target language bindings for interop with managed code.");
                Console.WriteLine();
                optionSet.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }

            if (Assemblies == null || Assemblies.Count == 0)
            {
                Console.WriteLine("At least one managed assembly must be passed as input.");
                Environment.Exit(0);
            }
        }
        public virtual void Parse(string[] Args, out Mono.Options.OptionSet Options)
        {
            var ret = this;

            Options = new Mono.Options.OptionSet()
            {
                "This",
                "Is",
                "Another",
                { $@"{nameof(ParentProcess_ID)}=", "the process ID of the parent process", (int x) => ret.ParentProcess_ID = x },
                { $@"{nameof(Terminate_OnParentProcessExit)}=", "if true, will exit when the parent process exits", (bool x) => ret.Terminate_OnParentProcessExit = x },
                { $@"{nameof(Terminate_OnStop)}=", "if true, will exit when 'Stop' is invoked", (bool x) => ret.Terminate_OnStop = x },
                { $@"{nameof(ListenOn_Provider)}=", "the provider to use for listening", (string x) => ret.ListenOn_Provider = x },
                { $@"{nameof(ListenOn_Host)}=", "the host to listen on", (string x) => ret.ListenOn_Host = x },
                { $@"{nameof(ListenOn_Port)}=", "the port to listen on", (string x) => ret.ListenOn_Port = x },
                { $@"{nameof(ListenOn_Key)}=", "the key to listen on", (string x) => ret.ListenOn_Key = x }
            };

            Options.Parse(Args);
        }
示例#28
0
        static Opts GetOpts(string[] args)
        {
            Opts opts = new Opts();
            var p = new Mono.Options.OptionSet() {
                { "r|rname=",   "regex applied to the filename",         v => opts.Pattern = v },
                { "o|out=",     "filename for result of files (UTF8)",   v => opts.OutFilename = v },
                { "p|progress", "prints out the directory currently scanned for a little progress indicator",   v => opts.progress = (v != null) },
                //{ "v", "increase debug message verbosity",                      v => { if (v != null) ++verbosity; } },
                { "h|help",     "show this message and exit",            v => opts.show_help = v != null },
                { "f|format=",  "format the output",                     v => opts.FormatString = v },
                { "j|follow",   "follow junctions",                      v => opts.FollowJunctions = (v != null) }
            };
            try
            {
                opts.Dirs = p.Parse(args);

                if (!String.IsNullOrEmpty(opts.Pattern))
                {
                    Console.Error.WriteLine("pattern parsed for rname [{0}]", opts.Pattern);
                }
                if (!String.IsNullOrEmpty(opts.FormatString))
                {
                    Console.Error.WriteLine("FormatString [{0}]", opts.FormatString);
                }
                if (opts.Dirs.Count() == 0)
                {
                    opts.Dirs.Add(Directory.GetCurrentDirectory());
                }
            }
            catch (Mono.Options.OptionException oex)
            {
                Console.WriteLine(oex.Message);
                return null;
            }
            if (opts.show_help)
            {
                ShowHelp(p);
                return null;
            }
            return opts;
        }
示例#29
0
        static void Help(string id, string command, MonoOptionSet options)
        {
            var opts = Lazy.Create(() => options.WriteOptionDescriptionsReturningWriter(new StringWriter {
                NewLine = Environment.NewLine
            }).ToString());
            var logo = Lazy.Create(() => new StringBuilder().AppendLine($"{VersionInfo.ProductName} (version {new Version(VersionInfo.FileVersion).Trim(3)})")
                                   .AppendLine(VersionInfo.LegalCopyright.Replace("\u00a9", "(C)"))
                                   .ToString());

            using (var stream = GetManifestResourceStream($"help.{id ?? command}.txt"))
                using (var reader = new StreamReader(stream))
                    using (var e = reader.ReadLines())
                        while (e.MoveNext())
                        {
                            var line = e.Current;
                            line = Regex.Replace(line, @"\$([A-Z][A-Z_]*)\$", m =>
                            {
                                switch (m.Groups[1].Value)
                                {
                                case "NAME": return("csmin");

                                case "COMMAND": return(command);

                                case "LOGO": return(logo.Value);

                                case "OPTIONS": return(opts.Value);

                                default: return(string.Empty);
                                }
                            });

                            if (line.Length > 0 && line[line.Length - 1] == '\n')
                            {
                                Console.Write(line);
                            }
                            else
                            {
                                Console.WriteLine(line);
                            }
                        }
        }
示例#30
0
 static void ParseCmdopts(string[] args, Mono.Options.OptionSet options)
 {
     SysCollGen.List <string> extra = new SysCollGen.List <string>();
     log.Info("parseCmdopts()");
     try {
         extra = options.Parse(args);
     } catch (Mono.Options.OptionException exc) {
         Console.Error.WriteLine("{0}: {1}", progName, exc.Message);
         Environment.Exit(1);
     }
     if (0 < extra.Count)
     {
         Console.Error.WriteLine("Extra args: {0}", extra.Count);
     }
     if (showHelp)
     {
         Console.WriteLine("Usage: {0} [options]\n\nOptions:", progName);
         options.WriteOptionDescriptions(Console.Out);
         Environment.Exit(1);
     }
 }
示例#31
0
        static Opts GetOpts(string[] args)
        {
            bool show_help         = false;
            bool wrong_files_given = false;

            Opts opts = new Opts();
            var  p    = new Mono.Options.OptionSet()
            {
                { "o|out=", "filename for result of compare", v => opts.outfile = v },
                { "s|sorted", "write out sorted files", v => opts.writeOutSorted = v != null },
                { "d|debug", "debug", v => opts.debug = v != null },
                { "h|help", "show this message and exit", v => show_help = v != null },
            };

            try
            {
                List <string> twoFiles = p.Parse(args);
                if (twoFiles.Count == 2)
                {
                    opts.fileA = twoFiles[0];
                    opts.fileB = twoFiles[1];
                }
                else
                {
                    Console.Error.WriteLine("you should supply 2 filenames to compare");
                    wrong_files_given = true;
                }
            }
            catch (Mono.Options.OptionException oex)
            {
                Console.WriteLine(oex.Message);
                return(null);
            }
            if (show_help | wrong_files_given)
            {
                ShowHelp(p);
                return(null);
            }
            return(opts);
        }
示例#32
0
        private static void Main(string[] args)
        {
            var sourceControlPath = string.Empty;
            var rootPath = string.Empty;
            var files = new List<string>();
            var options = new Mono.Options.OptionSet
            {
                { "s|src:", "The path to the source control system.", x => sourceControlPath = x },
                { "r|root:", "The root path under which all source code files belong.", x => rootPath = x },
                { "p|pdb:", "The fully qualified path to the one or more debug (PDB) files.", files.Add }
            };
            options.Parse(args);

            var symbols = files.Select(x => x.Standardize())
                .Where(File.Exists)
                .Select(x => new DebugSymbol(x, rootPath))
                .ToArray();

            var indexer = new NetworkShareIndexer(sourceControlPath);
            foreach (var symbol in symbols)
                indexer.Index(symbol);
        }
示例#33
0
        public static Opts GetOpts(string[] args)
        {
            bool show_help  = false;
            Opts tmpOpts    = new Opts();
            Opts resultOpts = null;
            var  p          = new Mono.Options.OptionSet()
            {
                { "t=|threads", $"how many copies should be run in parallel (default: {tmpOpts.MaxThreads})",
                  v => tmpOpts.MaxThreads = Convert.ToInt32(v) },
                { "n|dryrun", "show what would be copied", v => tmpOpts.dryrun = (v != null) },
                { "h|help", "show this message and exit", v => show_help = v != null }
            };

            try
            {
                List <string> parsedArgs = p.Parse(args);
                if (parsedArgs.Count != 3)
                {
                    show_help = true;
                }
                else
                {
                    resultOpts                   = tmpOpts;
                    resultOpts.SrcBase           = parsedArgs[0];
                    resultOpts.TrgBase           = parsedArgs[1];
                    resultOpts.FilenameWithFiles = parsedArgs[2];
                }
            }
            catch (Mono.Options.OptionException oex)
            {
                Console.WriteLine(oex.Message);
            }
            if (show_help)
            {
                ShowHelp(p);
                return(null);
            }
            return(resultOpts);
        }
示例#34
0
        static void Main(string[] args)
        {
            Badger.Common.Diagnostics.Logging.ApplySimpleConfiguation();

            var Logger = log4net.LogManager.GetLogger("GetIcon");

            try {
                var Options = new GetFileIconParameters();


                var Parser = new Mono.Options.OptionSet()
                {
                    {
                        $@"{nameof(GetFileIconParameters.Source_File)}=",
                        "The full path to the executable that will be used for signing executables.",
                        x => {
                            Options.Source_File = x;
                        }
                    },

                    {
                        $@"{nameof(GetFileIconParameters.Dest_File)}=",
                        "The full path to the executable that will be used for signing executables.",
                        x => {
                            Options.Dest_File = x;
                        }
                    },
                };

                Parser.Parse(args);

                Parser.WriteOptionDescriptions(Console.Out);

                ExtractTo(Options);
            } catch (Exception ex) {
                Logger.Error(ex);
            }
        }
示例#35
0
        static void Help(string id, string command, MonoOptionSet options)
        {
            var opts = Lazy.Create(() => options.WriteOptionDescriptionsReturningWriter(new StringWriter {
                NewLine = Environment.NewLine
            }).ToString());
            var logo = Lazy.Create(() => new StringBuilder().AppendLine($"{VersionInfo.ProductName} (version {new Version(VersionInfo.FileVersion).Trim(3)})")
                                   .AppendLine(VersionInfo.LegalCopyright.Replace("\u00a9", "(C)"))
                                   .ToString());

            using var stream = GetManifestResourceStream($"help.{id ?? command}.txt");
            using var reader = new StreamReader(stream);
            using var e      = reader.ReadLines();
            while (e.MoveNext())
            {
                var line = Regex.Replace(e.Current, @"\$([A-Z][A-Z_]*)\$",
                                         m => m.Groups[1].Value switch
                {
                    "NAME" => "csmin",
                    "COMMAND" => command,
                    "LOGO" => logo.Value,
                    "OPTIONS" => opts.Value,
                    _ => string.Empty
                });
示例#36
0
        void SetupStartupOptions()
        {
            var args = Environment.GetCommandLineArgs();

            var p = new Mono.Options.OptionSet();

            p.Add("unityProcessId=", "Unity Process Id", (int i) => StartupOptions.UnityProcessId        = i);
            p.Add("unityRestServerUrl=", "Unity REST Server URL", s => StartupOptions.UnityRestServerUrl = s);

            LoggingService.Log(MonoDevelop.Core.Logging.LogLevel.Info, "ARGS: " + String.Join("!", args));

            try
            {
                p.Parse(args);
            }
            catch (Mono.Options.OptionException e)
            {
                LoggingService.LogInfo("OptionException: " + e.ToString());
            }

            LoggingService.LogInfo("Unity Process ID: " + StartupOptions.UnityProcessId);
            LoggingService.LogInfo("Unity REST Server Url: " + StartupOptions.UnityRestServerUrl);
        }
示例#37
0
        static Configuration ParseCommandLine(
            IEnumerable<string> arguments, List<BuildGroup> buildGroups, 
            Dictionary<string, IProfile> profiles
        )
        {
            var baseConfig = new Configuration();
            var commandLineConfig = new Configuration();
            IProfile defaultProfile = new Profiles.Default();
            var profileAssemblies = new List<string>();
            bool[] autoloadProfiles = new bool[] { true };
            string[] newDefaultProfile = new string[] { null };
            List<string> filenames;

            {
                var os = new Mono.Options.OptionSet {
                    {"o=|out=",
                        "Specifies the output directory for generated javascript and manifests.",
                        (path) => commandLineConfig.OutputDirectory = Path.GetFullPath(path) },
                    {"nac|noautoconfig",
                        "Suppresses automatic loading of same-named .jsilconfig files located next to solutions and/or assemblies.",
                        (b) => commandLineConfig.AutoLoadConfigFiles = b == null },
                    {"nt|nothreads",
                        "Suppresses use of multiple threads to speed up the translation process.",
                        (b) => commandLineConfig.UseThreads = b == null },
                    {"sbc|suppressbugcheck",
                        "Suppresses JSIL bug checks that detect bugs in .NET runtimes and standard libraries.",
                        (b) => commandLineConfig.RunBugChecks = b == null },

                    "Solution Builder options",
                    {"configuration=",
                        "When building one or more solution files, specifies the build configuration to use (like 'Debug').",
                        (v) => commandLineConfig.SolutionBuilder.Configuration = v },
                    {"platform=",
                        "When building one or more solution files, specifies the build platform to use (like 'x86').",
                        (v) => commandLineConfig.SolutionBuilder.Platform = v },
                    {"target=",
                        "When building one or more solution files, specifies the build target to use (like 'Build'). The default is 'Build'.",
                        (v) => commandLineConfig.SolutionBuilder.Target = v },
                    {"logVerbosity=",
                        "When building one or more solution files, specifies the level of log verbosity. Valid options are 'Quiet', 'Minimal', 'Normal', 'Detailed', and 'Diagnostic'.",
                        (v) => commandLineConfig.SolutionBuilder.LogVerbosity = v },

                    "Assembly options",
                    {"p=|proxy=",
                        "Loads a type proxy assembly to provide type information for the translator.",
                        (name) => commandLineConfig.Assemblies.Proxies.Add(Path.GetFullPath(name)) },
                    {"i=|ignore=",
                        "Specifies a regular expression pattern for assembly names that should be ignored during the translation process.",
                        (regex) => commandLineConfig.Assemblies.Ignored.Add(regex) },
                    {"s=|stub=",
                        "Specifies a regular expression pattern for assembly names that should be stubbed during the translation process. " +
                        "Stubbing forces all methods to be externals.",
                        (regex) => commandLineConfig.Assemblies.Stubbed.Add(regex) },
                    {"nd|nodeps",
                        "Suppresses the automatic loading and translation of assembly dependencies.",
                        (b) => commandLineConfig.IncludeDependencies = b == null},
                    {"nodefaults",
                        "Suppresses the default list of stubbed assemblies.",
                        (b) => commandLineConfig.ApplyDefaults = b == null},
                    {"nolocal",
                        "Disables using local proxy types from translated assemblies.",
                        (b) => commandLineConfig.UseLocalProxies = b == null},
                    {"fv=|frameworkVersion=",
                        "Specifies the version of the .NET framework proxies to use. " +
                        "This ensures that correct type information is provided (as different versions of the framework use different standard libraries). " +
                        "The only accepted value is currently '4.0'. Default: '4.0'",
                        (fv) => commandLineConfig.FrameworkVersion = double.Parse(fv)},

                    "Profile options",
                    {"nap|noautoloadprofiles",
                        "Disables automatic loading of profile assemblies from the compiler directory.",
                        (b) => autoloadProfiles[0] = (b == null)},
                    {"pa=|profileAssembly=",
                        "Loads one or more project profiles from the specified profile assembly. Note that this does not force the profiles to be used.",
                        (filename) => profileAssemblies.Add(filename)},
                    {"dp=|defaultProfile=",
                        "Overrides the default profile to use for projects by specifying the name of the new default profile.",
                        (profileName) => newDefaultProfile[0] = profileName},

                    "CodeGenerator options",
                    {"os",
                        "Suppresses struct copy elimination.",
                        (b) => commandLineConfig.CodeGenerator.EliminateStructCopies = b == null},
                    {"ot",
                        "Suppresses temporary local variable elimination.",
                        (b) => commandLineConfig.CodeGenerator.EliminateTemporaries = b == null},
                    {"oo",
                        "Suppresses simplification of operator expressions and special method calls.",
                        (b) => commandLineConfig.CodeGenerator.SimplifyOperators = b == null},
                    {"ol",
                        "Suppresses simplification of loop blocks.",
                        (b) => commandLineConfig.CodeGenerator.SimplifyLoops = b == null},
                };

                filenames = os.Parse(arguments);

                if (filenames.Count == 0) {
                    var asmName = Assembly.GetExecutingAssembly().GetName();
                    Console.WriteLine("==== JSILc v{0}.{1}.{2} ====", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision);
                    Console.WriteLine("Specify one or more compiled assemblies (dll/exe) to translate them. Symbols will be loaded if they exist in the same directory.");
                    Console.WriteLine("You can also specify Visual Studio solution files (sln) to build them and automatically translate their output(s).");
                    Console.WriteLine("Specify the path of a .jsilconfig file to load settings from it.");

                    os.WriteOptionDescriptions(Console.Out);

                    return null;
                }
            }

            {
                if (autoloadProfiles[0])
                    profileAssemblies.AddRange(Directory.GetFiles(
                        GetJSILDirectory(),
                        "JSIL.Profiles.*.dll"
                    ));

                foreach (var filename in profileAssemblies) {
                    var fullPath = Path.GetFullPath(filename);

                    try {
                        var assembly = Assembly.LoadFile(fullPath);

                        foreach (var type in assembly.GetTypes()) {
                            if (
                                type.FindInterfaces(
                                    (interfaceType, o) => interfaceType == (Type)o, typeof(IProfile)
                                ).Length != 1
                            )
                                continue;

                            var ctor = type.GetConstructor(
                                BindingFlags.Public | BindingFlags.Instance,
                                null, System.Type.EmptyTypes, null
                            );
                            var profileInstance = (IProfile)ctor.Invoke(new object[0]);

                            profiles.Add(type.Name, profileInstance);
                        }
                    } catch (Exception exc) {
                        Console.Error.WriteLine("Warning: Failed to load profile '{0}': {1}", filename, exc);
                    }
                }
            }

            commandLineConfig = MergeConfigurations(
                commandLineConfig,
                (from fn in filenames
                 where Path.GetExtension(fn) == ".jsilconfig"
                 select LoadConfiguration(fn)).ToArray()
            );

            if (commandLineConfig.ApplyDefaults.GetValueOrDefault(true)) {
                baseConfig = MergeConfigurations(
                    LoadConfiguration(Path.Combine(
                        GetJSILDirectory(),
                        "defaults.jsilconfig"
                    )),
                    baseConfig
                );
            }

            foreach (var solution in
                     (from fn in filenames where Path.GetExtension(fn) == ".sln" select fn)
                    ) {

                var solutionFullPath = Path.GetFullPath(solution);
                var solutionDir = Path.GetDirectoryName(solutionFullPath);

                if ((solutionDir == null) || (solutionFullPath == null)) {
                    Console.Error.WriteLine("// Can't process solution '{0}' - path seems malformed", solution);
                    continue;
                }

                var solutionConfigPath = Path.Combine(
                    solutionDir,
                    String.Format("{0}.jsilconfig", Path.GetFileName(solutionFullPath))
                );
                var solutionConfig = File.Exists(solutionConfigPath)
                    ? new Configuration[] { LoadConfiguration(solutionConfigPath) }
                    : new Configuration[] {  };

                var mergedSolutionConfig = MergeConfigurations(baseConfig, solutionConfig);
                var config = MergeConfigurations(mergedSolutionConfig, commandLineConfig);
                var buildStarted = DateTime.UtcNow.Ticks;

                var buildResult = SolutionBuilder.SolutionBuilder.Build(
                    solutionFullPath,
                    config.SolutionBuilder.Configuration,
                    config.SolutionBuilder.Platform,
                    config.SolutionBuilder.Target ?? "Build",
                    config.SolutionBuilder.LogVerbosity
                );

                var jss = new JavaScriptSerializer();
                jss.MaxJsonLength = (1024 * 1024) * 64;
                var buildResultJson = jss.Serialize(buildResult);
                buildResult = jss.Deserialize<SolutionBuilder.BuildResult>(buildResultJson);

                var buildEnded = DateTime.UtcNow.Ticks;

                IProfile profile = defaultProfile;

                foreach (var candidateProfile in profiles.Values) {
                    if (!candidateProfile.IsAppropriateForSolution(buildResult))
                        continue;

                    Console.Error.WriteLine("// Auto-selected the profile '{0}' for this project.", candidateProfile.GetType().Name);
                    profile = candidateProfile;
                    break;
                }

                var localVariables = config.ApplyTo(new VariableSet());
                localVariables["SolutionDirectory"] = () => solutionDir;

                var processStarted = DateTime.UtcNow.Ticks;
                profile.ProcessBuildResult(
                    localVariables,
                    profile.GetConfiguration(config),
                    buildResult
                );
                var processEnded = DateTime.UtcNow.Ticks;

                {
                    var logPath = localVariables.ExpandPath(String.Format(
                        "%outputdirectory%/{0}.buildlog", Path.GetFileName(solution)
                    ), false);

                    if (!Directory.Exists(Path.GetDirectoryName(logPath)))
                        Directory.CreateDirectory(Path.GetDirectoryName(logPath));

                    using (var logWriter = new StreamWriter(logPath, false, Encoding.UTF8)) {
                        logWriter.WriteLine(
                            "Build of solution '{0}' processed {1} task(s) and produced {2} result file(s):",
                            solution, buildResult.AllItemsBuilt.Length, buildResult.OutputFiles.Length
                        );

                        foreach (var of in buildResult.OutputFiles)
                            logWriter.WriteLine(of);

                        logWriter.WriteLine("----");
                        logWriter.WriteLine("Elapsed build time: {0:0000.0} second(s).", TimeSpan.FromTicks(buildEnded - buildStarted).TotalSeconds);
                        logWriter.WriteLine("Selected profile '{0}' to process results of this build.", profile.GetType().Name);
                        logWriter.WriteLine("Elapsed processing time: {0:0000.0} second(s).", TimeSpan.FromTicks(processEnded - processStarted).TotalSeconds);
                    }
                }

                var outputFiles = buildResult.OutputFiles.Concat(
                    (from eo in config.SolutionBuilder.ExtraOutputs
                     let expanded = localVariables.ExpandPath(eo, true)
                     select expanded)
                ).ToArray();

                if (outputFiles.Length > 0) {
                    buildGroups.Add(new BuildGroup {
                        BaseConfiguration = mergedSolutionConfig,
                        BaseVariables = localVariables,
                        FilesToBuild = outputFiles,
                        Profile = profile,
                    });
                }
            }

            var assemblyNames = (from fn in filenames
                                 where Path.GetExtension(fn).Contains(",") ||
                                    Path.GetExtension(fn).Contains(" ") ||
                                    Path.GetExtension(fn).Contains("=")
                                 select fn).ToArray();

            var resolver = new Mono.Cecil.DefaultAssemblyResolver();
            var metaResolver = new CachingMetadataResolver(resolver);
            var resolverParameters = new ReaderParameters {
                AssemblyResolver = resolver,
                MetadataResolver = metaResolver,
                ReadSymbols = false,
                ReadingMode = ReadingMode.Deferred,
            };
            var resolvedAssemblyPaths = (from an in assemblyNames
                                      let asm = resolver.Resolve(an, resolverParameters)
                                      where asm != null
                                      select asm.MainModule.FullyQualifiedName).ToArray();

            var mainGroup = (from fn in filenames
                             where
                                 (new[] { ".exe", ".dll" }.Contains(Path.GetExtension(fn)))
                             select fn)
                             .Concat(resolvedAssemblyPaths)
                             .ToArray();

            if (mainGroup.Length > 0) {
                var variables = commandLineConfig.ApplyTo(new VariableSet());

                buildGroups.Add(new BuildGroup {
                    BaseConfiguration = baseConfig,
                    BaseVariables = variables,
                    FilesToBuild = mainGroup,
                    Profile = defaultProfile
                });
            }

            return commandLineConfig;
        }
示例#38
0
文件: Program.cs 项目: haslo/OCTGN
        internal static void Start()
        {
            Application.Current.MainWindow = new Window();
            KillOtherOctgn();
            bool isUpdate = RunUpdateChecker();
            if (isUpdate)
            {
                KillOtherOctgn(true);
                UpdateManager.Instance.UpdateAndRestart();
                return;
            }
            Log.Info("Ping back");
            System.Threading.Tasks.Task.Factory.StartNew(pingOB);

            bool tableOnlyFailed = false;

            int? hostport = null;
            Guid? gameid = null;

            var os = new Mono.Options.OptionSet()
                         {
                             { "t|table", x => TableOnly = true },
                             { "g|game=",x=> gameid=Guid.Parse(x)},
                             { "d|deck",x=>DeckEditorOnly = true}
                         };
            try
            {
                os.Parse(Environment.GetCommandLineArgs());
            }
            catch (Exception e)
            {
                Log.Warn("Parse args exception: " +String.Join(",",Environment.GetCommandLineArgs()),e);
            }

            if (TableOnly)
            {
                try
                {
                    new GameTableLauncher().Launch(hostport,gameid);
                }
                catch (Exception e)
                {
                    Log.Warn("Couldn't host/join table mode",e);
                    tableOnlyFailed = true;
                    Program.Exit();
                }
            }
            if (DeckEditorOnly)
            {
                var win = new DeckBuilderWindow();
                Application.Current.MainWindow = win;
                win.Show();
            }

            if ((!TableOnly || tableOnlyFailed) && !DeckEditorOnly)
            {

                Log.Info("Creating main window...");
                WindowManager.Main = new Main();
                Log.Info("Main window Created, Launching it.");
                Application.Current.MainWindow = WindowManager.Main;
                Log.Info("Main window set.");
                Log.Info("Launching Main Window");
                WindowManager.Main.Show();
                Log.Info("Main Window Launched");
            }

        }
示例#39
0
        static void Main(string[] args)
        {
            bool coloredLogging = true;
            bool printHelp = false;
            bool printVersion = false;

            // Name the main thread
            Thread.CurrentThread.Name = "Main";

            #region Command Line Argument Handling

            Mono.Options.OptionSet set = new Mono.Options.OptionSet()
            {
                { "nocolor", "Disable colored console logging", v => coloredLogging = false },
                { "h|?|help", "Shows launch options", v => printHelp = true },
                { "version", "Show version information", v => printVersion = true }
            };
            set.Parse(args);

            if (printHelp)
            {
                set.WriteOptionDescriptions(Console.Out);
                return;
            }

            if (printVersion)
            {
                string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                Console.WriteLine("Simian " + version);
                return;
            }

            #endregion Command Line Argument Handling

            #region log4net Setup

            // If error level reporting isn't enabled we assume no logger is configured and initialize a default appender
            if (!m_log.Logger.IsEnabledFor(log4net.Core.Level.Error))
            {
                log4net.Appender.AppenderSkeleton appender;

                if (coloredLogging)
                {
                    log4net.Appender.ColoredConsoleAppender coloredAppender = new log4net.Appender.ColoredConsoleAppender();

                    var mapping = new log4net.Appender.ColoredConsoleAppender.LevelColors();
                    mapping.Level = log4net.Core.Level.Debug;
                    mapping.ForeColor = log4net.Appender.ColoredConsoleAppender.Colors.HighIntensity;
                    coloredAppender.AddMapping(mapping);

                    mapping = new log4net.Appender.ColoredConsoleAppender.LevelColors();
                    mapping.Level = log4net.Core.Level.Info;
                    mapping.ForeColor = log4net.Appender.ColoredConsoleAppender.Colors.White;
                    coloredAppender.AddMapping(mapping);

                    mapping = new log4net.Appender.ColoredConsoleAppender.LevelColors();
                    mapping.Level = log4net.Core.Level.Warn;
                    mapping.BackColor = log4net.Appender.ColoredConsoleAppender.Colors.Purple;
                    mapping.ForeColor = log4net.Appender.ColoredConsoleAppender.Colors.White;
                    coloredAppender.AddMapping(mapping);

                    mapping = new log4net.Appender.ColoredConsoleAppender.LevelColors();
                    mapping.Level = log4net.Core.Level.Error;
                    mapping.BackColor = log4net.Appender.ColoredConsoleAppender.Colors.Red;
                    mapping.ForeColor = log4net.Appender.ColoredConsoleAppender.Colors.White;
                    coloredAppender.AddMapping(mapping);

                    appender = coloredAppender;
                }
                else
                {
                    appender = new log4net.Appender.ConsoleAppender();
                }

                appender.Layout = new log4net.Layout.PatternLayout("%timestamp [%thread] %-5level %logger - %message%newline");
                appender.ActivateOptions();
                BasicConfigurator.Configure(appender);

                m_log.Info("No log configuration found, defaulting to console logging");
            }

            // Hook up Debug.Assert statements to log4net
            Debug.Listeners.Insert(0, new log4netTraceListener());

            #endregion log4net Setup

            // Set the working directory to the application dir
            Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

            // Initialize the Simian object
            m_simian = new Simian();

            // Handle Ctrl+C
            Console.CancelKeyPress +=
                delegate(object sender, ConsoleCancelEventArgs e)
                {
                    e.Cancel = true;

                    m_simian.Shutdown();
                    m_running = false;
                };

            // Attempt to load modules
            if (m_simian.LoadModules())
            {
                // Initialize the interactive console
                InteractiveConsole();
            }
            else
            {
                m_log.Error("Application module loading failed, shutting down");
            }
        }
示例#40
0
        public static void SpawnBoss(CommandArgs args)
        {
            if (args.Parameters.Count == 1 && args.Parameters[0] == "list")
            {
                args.Player.SendInfoMessage("Available bosses: {0}", string.Join(", ", bosses));
                return;
            }
            if (args.Parameters.Count < 1)
            {
                args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnboss <boss type> [amount] [-health] [-x] [-y]", TShock.Config.CommandSpecifier);
                return;
            }

            string healthStr = "", xStr = "", yStr = "";

            Mono.Options.OptionSet options = new Mono.Options.OptionSet()
            {
                { "h|health=", v => healthStr = v },
                { "x=", v => xStr = v },
                { "y=", v => yStr = v },
            };
            List <string> parameters       = options.Parse(args.Parameters);

            int health = -1;

            if (int.TryParse(healthStr, out health) && health < 0)
            {
                args.Player.SendErrorMessage("Health amount must be greater than 0!");
                return;
            }

            if (!args.Player.RealPlayer && (string.IsNullOrEmpty(xStr) || string.IsNullOrEmpty(yStr)))
            {
                args.Player.SendErrorMessage("You are required to set coordinates from console! ");
                args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnboss <boss type> [amount] [-health] [-x] [-y]", TShock.Config.CommandSpecifier);
                return;
            }

            int amount = 1;

            if (args.Parameters.Count >= 2 && (!int.TryParse(args.Parameters[1], out amount) || amount <= 0))
            {
                args.Player.SendErrorMessage("Invalid boss amount!");
                return;
            }
            int TileX = args.Player.TileX;
            int TileY = args.Player.TileY;

            if (!string.IsNullOrEmpty(xStr) || !string.IsNullOrEmpty(xStr))
            {
                if (!int.TryParse(xStr, out TileX) || !int.TryParse(yStr, out TileY))
                {
                    args.Player.SendErrorMessage("Invalid X and Y coordinates! Format: -x 1234 -y 1234");
                    return;
                }
            }

            if (TileX < 0 || TileX >= Main.maxTilesX || TileY < 0 || TileY >= Main.maxTilesY)
            {
                args.Player.SendErrorMessage("Given coordinates are invalid!");
                return;
            }

            NPC npc = new NPC();

            switch (args.Parameters[0].ToLower())
            {
            case "*":
            case "all":
                int[] npcIds = { 4, 13, 35, 50, 125, 126, 127, 134, 222, 245, 262, 266, 370, 398, 439, 636, 657 };
                TSPlayer.Server.SetTime(false, 0.0);
                foreach (int i in npcIds)
                {
                    npc.SetDefaults(i);
                    TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
                }
                TSPlayer.All.SendSuccessMessage("{0} has spawned all bosses {1} time(s).", args.Player.Name, amount);
                return;

            case "brain":
            case "brain of cthulhu":
            case "boc":
                npc.SetDefaults(266);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Brain of Cthulhu {1} time(s).", args.Player.Name, amount);
                return;

            case "destroyer":
                npc.SetDefaults(134);
                TSPlayer.Server.SetTime(false, 0.0);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Destroyer {1} time(s).", args.Player.Name, amount);
                return;

            case "duke":
            case "duke fishron":
            case "fishron":
                npc.SetDefaults(370);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Duke Fishron {1} time(s).", args.Player.Name, amount);
                return;

            case "eater":
            case "eater of worlds":
            case "eow":
                npc.SetDefaults(13);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Eater of Worlds {1} time(s).", args.Player.Name, amount);
                return;

            case "eye":
            case "eye of cthulhu":
            case "eoc":
                npc.SetDefaults(4);
                TSPlayer.Server.SetTime(false, 0.0);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Eye of Cthulhu {1} time(s).", args.Player.Name, amount);
                return;

            case "golem":
                npc.SetDefaults(245);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Golem {1} time(s).", args.Player.Name, amount);
                return;

            case "king":
            case "king slime":
            case "ks":
                npc.SetDefaults(50);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned King Slime {1} time(s).", args.Player.Name, amount);
                return;

            case "plantera":
                npc.SetDefaults(262);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Plantera {1} time(s).", args.Player.Name, amount);
                return;

            case "prime":
            case "skeletron prime":
                npc.SetDefaults(127);
                TSPlayer.Server.SetTime(false, 0.0);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron Prime {1} time(s).", args.Player.Name, amount);
                return;

            case "queen bee":
            case "qb":
                npc.SetDefaults(222);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Queen Bee {1} time(s).", args.Player.Name, amount);
                return;

            case "skeletron":
                npc.SetDefaults(35);
                TSPlayer.Server.SetTime(false, 0.0);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron {1} time(s).", args.Player.Name, amount);
                return;

            case "twins":
                TSPlayer.Server.SetTime(false, 0.0);
                npc.SetDefaults(125);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                npc.SetDefaults(126);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Twins {1} time(s).", args.Player.Name, amount);
                return;

            case "wof":
            case "wall of flesh":
                if (Main.wofNPCIndex != -1)
                {
                    args.Player.SendErrorMessage("There is already a Wall of Flesh!");
                    return;
                }
                if (args.Player.Y / 16f < Main.maxTilesY - 205)
                {
                    args.Player.SendErrorMessage("You must spawn the Wall of Flesh in hell!");
                    return;
                }
                NPC.SpawnWOF(new Vector2(args.Player.X, args.Player.Y));
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Wall of Flesh.", args.Player.Name);
                return;

            case "moon":
            case "moon lord":
            case "ml":
                npc.SetDefaults(398);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Moon Lord {1} time(s).", args.Player.Name, amount);
                return;

            case "empress":
            case "empress of light":
            case "eol":
                npc.SetDefaults(636);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Empress of Light {1} time(s).", args.Player.Name, amount);
                return;

            case "queen slime":
            case "qs":
                npc.SetDefaults(657);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Queen Slime {1} time(s).", args.Player.Name, amount);
                return;

            case "lunatic":
            case "lunatic cultist":
            case "cultist":
            case "lc":
                npc.SetDefaults(439);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Lunatic Cultist {1} time(s).", args.Player.Name, amount);
                return;

            case "betsy":
                npc.SetDefaults(551);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Betsy {1} time(s).", args.Player.Name, amount);
                return;

            case "flying dutchman":
            case "flying":
            case "dutchman":
                npc.SetDefaults(491);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Flying Dutchman {1} time(s).", args.Player.Name, amount);
                return;

            case "mourning wood":
                npc.SetDefaults(325);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Mourning Wood {1} time(s).", args.Player.Name, amount);
                return;

            case "pumpking":
                npc.SetDefaults(327);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Pumpking {1} time(s).", args.Player.Name, amount);
                return;

            case "everscream":
                npc.SetDefaults(344);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Everscream {1} time(s).", args.Player.Name, amount);
                return;

            case "santa-nk1":
            case "santa":
                npc.SetDefaults(346);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned Santa-NK1 {1} time(s).", args.Player.Name, amount);
                return;

            case "ice queen":
                npc.SetDefaults(345);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Ice Queen {1} time(s).", args.Player.Name, amount);
                return;

            case "martian saucer":
                npc.SetDefaults(392);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Martian Saucer {1} time(s).", args.Player.Name, amount);
                return;

            case "solar pillar":
                npc.SetDefaults(517);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Solar Pillar {1} time(s).", args.Player.Name, amount);
                return;

            case "nebula pillar":
                npc.SetDefaults(507);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Nebula Pillar {1} time(s).", args.Player.Name, amount);
                return;

            case "vortex pillar":
                npc.SetDefaults(422);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Vortex Pillar {1} time(s).", args.Player.Name, amount);
                return;

            case "stardust pillar":
                npc.SetDefaults(493);
                SpawnNPC(npc.type, npc.FullName, amount, TileX, TileY, health);
                TSPlayer.All.SendSuccessMessage("{0} has spawned the Stardust Pillar {1} time(s).", args.Player.Name, amount);
                return;

            default:
                args.Player.SendErrorMessage("Invalid boss type!");
                return;
            }
        }
示例#41
0
文件: Program.cs 项目: yvt/VxlToObj
        public static void Main(string[] args)
        {
            bool showhelp = false;
            string inputfmt = null;
            string outputfmt = null;
            string slicegen = "simple";
            string texgen = "simple";
            bool quiet = false;
            var filters = new List<IVoxelModelFilter>();

            var p = new Mono.Options.OptionSet()
            {
                { "i|in=",
                    "Specifies the input format. \n" +
                    "- kv6: VOXLAP engine sprite format.\n" +
                    "- vxl: VOXLAP engine worldmap format.\n" +
                    "- vox: MagicaVoxel format.\n",
                    v => inputfmt = v },
                { "o|out=",
                    "Specifies the output format.\n" +
                    "- obj: Wavefront .obj file.",
                    v => outputfmt = v },
                { "f|filter=",
                    "Specifies the filter to apply on the model.\n" +
                    "Parameters can be specified like this: --filter=NAME,PROP=VALUE,...\n" +
                    "Multiple filters can be applied by specifying this option for multiple times.\n" +
                    "- hollowify: Removes invisible voxels.\n" +
                    "    thickness=VALUE: Thickness of the shell. (default = 1)\n" +
                    "    type=chebyshev|manhattan: Specifies the distance function. (default = chebyshev)\n" +
                    "    boundary=empty|solid: Specifies how the space outside the boundary is handled. (default = empty)\n" +
                    "- solidify: Fills the invisible space.",
                    v => filters.Add(ParseFilter(v)) },
                { "s|slicegen=",
                    "Specifies the slice generator.\n" +
                    "- simple: Trivial slice generator that generates up to 6 quads for each voxel.",
                    v => slicegen = v },
                { "t|texgen=",  "Specifies the texture generator.\n" +
                    "- simple: Trivial texture generator. Requires the 'simple' slice generator.",
                    v => texgen = v },
                { "q|quiet",  "No progress indicators are shown",
                   v => quiet = v != null },
                { "h|help",  "Show this message and exit",
                   v => showhelp = v != null }
            };

            List<string> extra;
            try {
                extra = p.Parse(args);
            } catch (Mono.Options.OptionException e) {
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine("Try `VxlToObj --help' for more information.");
                return;
            }

            if (showhelp) {
                Console.WriteLine("USAGE: VxlToObj INFILE OUTFILE.obj [OPTIONS...]");
                Console.WriteLine("");
                Console.WriteLine("OPTIONS:");
                Console.WriteLine("");
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            // Input files
            if (extra.Count != 2)
            {
                Console.Error.WriteLine("Two file names must be provided.");
                Console.Error.WriteLine("Try `VxlToObj --help' for more information.");
                Environment.Exit(1);
                return;
            }
            string infile = extra[0];
            string outfile = extra[1];

            // Validate combinations
            if (slicegen != "simple")
            {
                Console.Error.WriteLine($"Unknown slice generator: {slicegen}");
                Environment.Exit(1);
                return;
            }

            if (texgen != "simple")
            {
                Console.Error.WriteLine($"Unknown texture generator: {texgen}");
                Environment.Exit(1);
                return;
            }

            if (inputfmt == null)
            {
                if (infile.EndsWith(".vxl", StringComparison.InvariantCultureIgnoreCase))
                {
                    inputfmt = "vxl";
                }
                else if (infile.EndsWith(".kv6", StringComparison.InvariantCultureIgnoreCase))
                {
                    inputfmt = "kv6";
                }
                else if (infile.EndsWith(".vox", StringComparison.InvariantCultureIgnoreCase))
                {
                    inputfmt = "vox";
                }
                else
                {
                    Console.Error.WriteLine($"Cannot guess the input format; specify it with -i/--in");
                    Environment.Exit(1);
                    return;
                }
            }
            else if (inputfmt != "vxl" && inputfmt != "kv6" && inputfmt != "vox")
            {
                Console.Error.WriteLine($"Unknown input format: {inputfmt}");
                Environment.Exit(1);
                return;
            }

            if (outputfmt == null)
            {
                if (outfile.EndsWith(".obj", StringComparison.InvariantCultureIgnoreCase))
                {
                    outputfmt = "obj";
                }
                else
                {
                    Console.Error.WriteLine($"Cannot guess the output format; specify it with -o/--out");
                    Environment.Exit(1);
                    return;
                }
            }
            else if (outputfmt != "obj")
            {
                Console.Error.WriteLine($"Unknown output format: {outputfmt}");
                Environment.Exit(1);
                return;
            }

            var modelTask = TaskBuilder.Start("Loading voxels", (progress) =>
            {
                switch (inputfmt)
                {
                    case "vxl":
                        return new VxlVoxelModelLoader().LoadVoxelModel(
                            System.IO.File.ReadAllBytes(infile), progress);
                    case "kv6":
                        return new Kv6VoxelModelLoader().LoadVoxelModel(
                            System.IO.File.ReadAllBytes(infile), progress);
                    case "vox":
                        return new MagicaVoxelModelLoader().LoadVoxelModel(
                            System.IO.File.ReadAllBytes(infile), progress);
                    default:
                        throw new InvalidOperationException();
                }
            });

            foreach (var flt in filters)
            {
                modelTask = modelTask.Then(flt.GetType().Name, (model, progress) =>
                {
                    flt.Apply(ref model, progress);
                    return model;
                });
            }

            var sliceTask = modelTask.Then("Generating mesh", (model, progress) =>
            {
                return new
                {
                    Slices = new SimpleMeshSliceGenerator().GenerateSlices(model, progress),
                    Model = model
                };
            });

            var textureTask = sliceTask.Then("Generating texture", (prev, progress) =>
            {
                System.Drawing.Bitmap bmp;
                new SimpleMeshTextureGenerator().GenerateTextureAndUV(prev.Model, prev.Slices, out bmp, progress);
                return new {
                    Slices = prev.Slices,
                    Model = prev.Model,
                    Texture = bmp
                };
            });

            var outputTask = textureTask.Then("Saving mesh", (prev, progress) =>
            {
                new ObjWriter().Save(prev.Slices, prev.Texture, outfile, progress);
                return (object) null;
            });

            var task = outputTask.Complete();

            if (quiet)
            {
                task(null);
                return;
            }

            var progressListener = new ConsoleProgressListener()
            {
                AutoUpdate = false
            };
            progressListener.Start();

            Exception resultEx = null;

            var th = new System.Threading.Thread(() =>
            {
                try
                {
                    task(progressListener);
                }
                catch (Exception ex)
                {
                    resultEx = ex;
                }
            });

            th.Start();

            while (th.IsAlive)
            {
                progressListener.Update();
                System.Threading.Thread.Sleep(100);
            }

            progressListener.Stop();

            if (resultEx != null)
            {
                Console.Error.WriteLine(resultEx.ToString());
            }
        }
        static void Main(string[] args)
        {
            bool printHelp = false;
            bool printVersion = false;

            string connectionString = null;
            string userUrl = null;
            string inventoryUrl = null;
            string assetUrl = null;
            string gridOwner = null;

            #region Command Line Argument Handling

            Mono.Options.OptionSet set = new Mono.Options.OptionSet()
            {
                { "c=|connection=", "OpenSim database connection string (ex. \"Data Source=localhost;Database=opensim;User ID=opensim;Password=opensim;\")", v => connectionString = v },
                { "u=|user="******"SimianGrid user service URL (ex. http://localhost/Grid/)", v => userUrl = v },
                { "i=|inventory=", "SimianGrid inventory service URL (ex. http://localhost/Grid/) (optional)", v => inventoryUrl = v },
                { "a=|asset=", "SimianGrid asset service URL (ex. http://localhost/Grid/) (optional)", v => assetUrl = v },
                { "g=|gridowner=", "Full name of a migrated user to appoint as the grid owner (ex. \"Master OpenSim\") (optional)", v => gridOwner = v },
                { "h|?|help", "Show this help", v => printHelp = true },
                { "v|version", "Show version information", v => printVersion = true }
            };
            set.Parse(args);

            if (String.IsNullOrEmpty(connectionString) || String.IsNullOrEmpty(userUrl))
                printHelp = true;

            if (printHelp || printVersion)
            {
                string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                Console.WriteLine("OpenSim Robust to SimianGrid database migration tool version " + version);
                Console.WriteLine("part of SimianGrid, an Open Metaverse Foundation project");
                Console.WriteLine("Written by John Hurliman, Intel Corporation");
                Console.WriteLine("Distributed under the BSD license");

                if (printHelp)
                    Console.WriteLine();
                else
                    Environment.Exit(0);
            }

            if (printHelp)
            {
                set.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }

            #endregion Command Line Argument Handling

            try
            {
                Console.WriteLine("Detecting OpenSim database version...");

                bool is070;
                if (TryGetStoreVersion(connectionString, out is070))
                {
                    if (is070)
                        Migrate070(connectionString, userUrl, assetUrl, inventoryUrl, gridOwner);
                    else
                        Migrate069(connectionString, userUrl, assetUrl, inventoryUrl, gridOwner);
                }
                else
                {
                    Console.WriteLine("Failed to detect the OpenSim database version");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Migration failed: " + ex);
            }
        }
示例#43
0
        static void Main(string[] args)
        {
            bool verboseErrors = false;
            try
            {
                string fileName = string.Empty;

                Mono.Options.OptionSet options = new Mono.Options.OptionSet()
                {
                    { "-f|file=", "The data file (xlsx)", val => fileName = val },
                    { "-v|verbose", "Display verbose error messages", val => { if (val != null) { verboseErrors = true; } } }
                };

                options.Parse(args);

                // temp
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = @"C:\Users\rpsmith\Temp\Derby\Game Stats - Template - 2015-04.xlsx";
                }

                if (!File.Exists(fileName))
                {
                    fileName = Path.Combine(Environment.CurrentDirectory, fileName);
                }
                if (!File.Exists(fileName))
                {
                    Console.WriteLine("That file doesn't exist.");
                    if (verboseErrors)
                    {
                        Console.WriteLine("(I was looking for " + fileName + ")");
                    }
                    return;
                }

                var dbConnection = ConfigurationManager.ConnectionStrings["SlowJams"].ConnectionString;
                FileInfo file = new FileInfo(fileName);

                var derbyEtl = new DerbyETL(file.FullName, dbConnection, verboseErrors);

                Console.WriteLine("Parsing file " + file.Name + " ...");
                derbyEtl.Extract();

                Console.WriteLine("Loading players...");
                derbyEtl.Transform();

                Console.WriteLine("Uploading data...");
                derbyEtl.Load();

                Console.WriteLine("Done.");
            }
            catch (Exception e)
            {
                string error = "Woah, shit just got real yo. Error: " + e.Message;
                if (verboseErrors)
                {
                    error = error + "\r\n" + e.StackTrace;
                }
                Console.WriteLine(error);
            }
        }
示例#44
0
        static void ParseCommandLine(IEnumerable<string> arguments, List<KeyValuePair<Configuration, IEnumerable<string>>> buildGroups)
        {
            var baseConfig = new Configuration();
            List<string> filenames;

            {
                var os = new Mono.Options.OptionSet {
                    {"o=|out=",
                        "Specifies the output directory for generated javascript and manifests. " +
                        "You can use '%configpath%' in jsilconfig files to refer to the directory containing the configuration file, and '%assemblypath%' to refer to the directory containing the assembly being translated.",
                        (path) => baseConfig.OutputDirectory = Path.GetFullPath(path) },
                    {"nac|noautoconfig",
                        "Suppresses automatic loading of same-named .jsilconfig files located next to solutions and/or assemblies.",
                        (b) => baseConfig.AutoLoadConfigFiles = b == null },
                    {"nt|nothreads",
                        "Suppresses use of multiple threads to speed up the translation process.",
                        (b) => baseConfig.UseThreads = b == null },

                    "Solution Builder options",
                    {"configuration=",
                        "When building one or more solution files, specifies the build configuration to use (like 'Debug').",
                        (v) => baseConfig.SolutionBuilder.Configuration = v },
                    {"platform=",
                        "When building one or more solution files, specifies the build platform to use (like 'x86').",
                        (v) => baseConfig.SolutionBuilder.Platform = v },

                    "Assembly options",
                    {"p=|proxy=",
                        "Loads a type proxy assembly to provide type information for the translator.",
                        (name) => baseConfig.Assemblies.Proxies.Add(Path.GetFullPath(name)) },
                    {"i=|ignore=",
                        "Specifies a regular expression pattern for assembly names that should be ignored during the translation process.",
                        (regex) => baseConfig.Assemblies.Ignored.Add(regex) },
                    {"s=|stub=",
                        "Specifies a regular expression pattern for assembly names that should be stubbed during the translation process. " +
                        "Stubbing forces all methods to be externals.",
                        (regex) => baseConfig.Assemblies.Stubbed.Add(regex) },
                    {"nd|nodeps",
                        "Suppresses the automatic loading and translation of assembly dependencies.",
                        (b) => baseConfig.IncludeDependencies = b == null},
                    {"nodefaults",
                        "Suppresses the default list of stubbed assemblies.",
                        (b) => baseConfig.ApplyDefaults = b == null},
                    {"nolocal",
                        "Disables using local proxy types from translated assemblies.",
                        (b) => baseConfig.UseLocalProxies = b == null},
                    {"fv=|frameworkVersion=",
                        "Specifies the version of the .NET framework proxies to use. " +
                        "This ensures that correct type information is provided (as 3.5 and 4.0 use different standard libraries). " +
                        "Accepted values are '3.5' and '4.0'. Default: '4.0'",
                        (fv) => baseConfig.FrameworkVersion = double.Parse(fv)},

                    "Optimizer options",
                    {"os",
                        "Suppresses struct copy elimination.",
                        (b) => baseConfig.Optimizer.EliminateStructCopies = b == null},
                    {"ot",
                        "Suppresses temporary local variable elimination.",
                        (b) => baseConfig.Optimizer.EliminateTemporaries = b == null},
                    {"oo",
                        "Suppresses simplification of operator expressions and special method calls.",
                        (b) => baseConfig.Optimizer.SimplifyOperators = b == null},
                    {"ol",
                        "Suppresses simplification of loop blocks.",
                        (b) => baseConfig.Optimizer.SimplifyLoops = b == null},
                };

                filenames = os.Parse(arguments);

                if (filenames.Count == 0) {
                    var asmName = Assembly.GetExecutingAssembly().GetName();
                    Console.WriteLine("==== JSILc v{0}.{1}.{2} ====", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision);
                    Console.WriteLine("Specify one or more compiled assemblies (dll/exe) to translate them. Symbols will be loaded if they exist in the same directory.");
                    Console.WriteLine("You can also specify Visual Studio solution files (sln) to build them and automatically translate their output(s).");
                    Console.WriteLine("Specify the path of a .jsilconfig file to load settings from it.");

                    os.WriteOptionDescriptions(Console.Out);

                    return;
                }
            }

            baseConfig = MergeConfigurations(
                baseConfig,
                (from fn in filenames
                 where Path.GetExtension(fn) == ".jsilconfig"
                 select LoadConfiguration(fn)).ToArray()
            );

            foreach (var solution in
                     (from fn in filenames where Path.GetExtension(fn) == ".sln" select fn)
                    ) {

                var solutionConfigPath = Path.Combine(
                    Path.GetDirectoryName(solution),
                    String.Format("{0}.jsilconfig", Path.GetFileName(solution))
                );
                var solutionConfig = File.Exists(solutionConfigPath)
                    ? new Configuration[] { LoadConfiguration(solutionConfigPath) }
                    : new Configuration[] {};

                var config = MergeConfigurations(baseConfig, solutionConfig);
                var outputs = SolutionBuilder.Build(
                    solution,
                    config.SolutionBuilder.Configuration,
                    config.SolutionBuilder.Platform
                );

                buildGroups.Add(new KeyValuePair<Configuration, IEnumerable<string>>(
                    config, outputs
                ));
            }

            var mainGroup = (from fn in filenames
                             where
                                 (new[] { ".exe", ".dll" }.Contains(Path.GetExtension(fn)))
                             select fn).ToArray();

            if (mainGroup.Length > 0)
                buildGroups.Add(new KeyValuePair<Configuration, IEnumerable<string>>(
                    baseConfig, mainGroup
                ));
        }
		void SetupStartupOptions ()
		{
			var args = Environment.GetCommandLineArgs ();

			var p = new Mono.Options.OptionSet ();
			p.Add ("unityProcessId=", "Unity Process Id", (int i) => StartupOptions.UnityProcessId = i);
			p.Add("unityRestServerUrl=", "Unity REST Server URL", s => StartupOptions.UnityRestServerUrl = s);

			LoggingService.Log (MonoDevelop.Core.Logging.LogLevel.Info, "ARGS: " + String.Join("!",args));

			try 
			{
				p.Parse (args);
			} 
			catch(Mono.Options.OptionException e)
			{
				LoggingService.LogInfo("OptionException: " + e.ToString());
			}

			LoggingService.LogInfo("Unity Process ID: " + StartupOptions.UnityProcessId);
			LoggingService.LogInfo("Unity REST Server Url: " + StartupOptions.UnityRestServerUrl);
		}
示例#46
0
		public int Run (string[] args)
		{
			Counters.Initialization.BeginTiming ();
			
			var options = new MonoDevelopOptions ();
			var optionsSet = new Mono.Options.OptionSet () {
				{ "nologo", "Do not display splash screen.", s => options.NoLogo = true },
				{ "ipc-tcp", "Use the Tcp channel for inter-process comunication.", s => options.IpcTcp = true },
				{ "newwindow", "Do not open in an existing instance of MonoDevelop", s => options.NewWindow = true },
				{ "h|?|help", "Show help", s => options.ShowHelp = true },
				{ "clog", "Log internal counter data", s => options.LogCounters = true },
				{ "clog-interval=", "Interval between counter logs (in miliseconds)", s => options.LogCountersInterval = int.Parse (s) },
			};
			var remainingArgs = optionsSet.Parse (args);
			if (options.ShowHelp) {
				Console.WriteLine ("MonoDevelop IDE " + MonoDevelop.Ide.BuildVariables.PackageVersionLabel);
				Console.WriteLine ("Options:");
				optionsSet.WriteOptionDescriptions (Console.Out);
				return 0;
			}
			
			if (options.LogCounters) {
				string logFile = Path.Combine (Environment.CurrentDirectory, "monodevelop.clog");
				LoggingService.LogInfo ("Logging instrumentation service data to file: " + logFile);
				InstrumentationService.StartAutoSave (logFile, 1000);
			}
			
			Counters.Initialization.Trace ("Initializing GTK");
			SetupExceptionManager ();
			
			try {
				MonoDevelop.Ide.Gui.GLibLogging.Enabled = true;
			} catch (Exception ex) {
				LoggingService.LogError ("Error initialising GLib logging.", ex);
			}
			
			//OSXFIXME
			Gtk.Application.Init ("monodevelop", ref args);
			InternalLog.Initialize ();
			string socket_filename = null;
			EndPoint ep = null;
			
			DispatchService.Initialize ();
			
			// Set a synchronization context for the main gtk thread
			SynchronizationContext.SetSynchronizationContext (new GtkSynchronizationContext ());
			
			AddinManager.AddinLoadError += OnAddinError;
			
			var startupInfo = new StartupInfo (remainingArgs);
			
			// If a combine was specified, force --newwindow.
			
			if(!options.NewWindow && startupInfo.HasFiles) {
				Counters.Initialization.Trace ("Pre-Initializing Runtime to load files in existing window");
				Runtime.Initialize (true);
				foreach (var file in startupInfo.RequestedFileList) {
					if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile (file.FileName)) {
						options.NewWindow = true;
						break;
					}
				}
			}
			
			DefaultTheme = Gtk.Settings.Default.ThemeName;
			if (!string.IsNullOrEmpty (IdeApp.Preferences.UserInterfaceTheme))
				Gtk.Settings.Default.ThemeName = IdeApp.Preferences.UserInterfaceTheme;
			
			//don't show the splash screen on the Mac, so instead we get the expected "Dock bounce" effect
			//this also enables the Mac platform service to subscribe to open document events before the GUI loop starts.
			if (PropertyService.IsMac)
				options.NoLogo = true;
			
			IProgressMonitor monitor;
			
			if (options.NoLogo) {
				monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor ();
			} else {
				monitor = SplashScreenForm.SplashScreen;
				SplashScreenForm.SplashScreen.ShowAll ();
			}
			
			Counters.Initialization.Trace ("Initializing Runtime");
			monitor.BeginTask (GettextCatalog.GetString ("Starting MonoDevelop"), 2);
			monitor.Step (1);
			Runtime.Initialize (true);
			
			//make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
			Counters.Initialization.Trace ("Initializing Platform Service");
			DesktopService.Initialize ();
			monitor.Step (1);
			monitor.EndTask ();
			
			monitor.Step (1);

			if (options.IpcTcp) {
				listen_socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
				ep = new IPEndPoint (IPAddress.Loopback, ipcBasePort + HashSDBMBounded (Environment.UserName));
			} else {
				socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable ("USER") + "-socket";
				listen_socket = new Socket (AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
				ep = new UnixEndPoint (socket_filename);
			}
				
			// If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
			if (!options.NewWindow && startupInfo.HasFiles) {
				try {
					StringBuilder builder = new StringBuilder ();
					foreach (var file in startupInfo.RequestedFileList) {
						builder.AppendFormat ("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
					}
					listen_socket.Connect (ep);
					listen_socket.Send (Encoding.UTF8.GetBytes (builder.ToString ()));
					return 0;
				} catch {
					// Reset the socket
					if (null != socket_filename && File.Exists (socket_filename))
						File.Delete (socket_filename);
				}
			}
			
			Counters.Initialization.Trace ("Checking System");
			string version = Assembly.GetEntryAssembly ().GetName ().Version.Major + "." + Assembly.GetEntryAssembly ().GetName ().Version.Minor;
			
			if (Assembly.GetEntryAssembly ().GetName ().Version.Build != 0)
				version += "." + Assembly.GetEntryAssembly ().GetName ().Version.Build;
			if (Assembly.GetEntryAssembly ().GetName ().Version.Revision != 0)
				version += "." + Assembly.GetEntryAssembly ().GetName ().Version.Revision;
			
			// System checks
			if (!CheckBug77135 ())
				return 1;
			
			if (!CheckQtCurve ())
				return 1;

			CheckFileWatcher ();
			
			Exception error = null;
			int reportedFailures = 0;
			
			try {
				Counters.Initialization.Trace ("Loading Icons");
				//force initialisation before the workbench so that it can register stock icons for GTK before they get requested
				ImageService.Initialize ();
				
				if (errorsList.Count > 0) {
					if (monitor is SplashScreenForm)
						SplashScreenForm.SplashScreen.Hide ();
					AddinLoadErrorDialog dlg = new AddinLoadErrorDialog ((AddinError[]) errorsList.ToArray (typeof(AddinError)), false);
					if (!dlg.Run ())
						return 1;
					if (monitor is SplashScreenForm)
						SplashScreenForm.SplashScreen.Show ();
					reportedFailures = errorsList.Count;
				}
				
				// no alternative for Application.ThreadException?
				// Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

				Counters.Initialization.Trace ("Initializing IdeApp");
				IdeApp.Initialize (monitor);
				
				// Load requested files
				Counters.Initialization.Trace ("Opening Files");
				IdeApp.OpenFiles (startupInfo.RequestedFileList);
				
				monitor.Step (1);
			
			} catch (Exception e) {
				error = e;
			} finally {
				monitor.Dispose ();
			}
			
			if (error != null) {
				MessageService.ShowException (error,
				                              GettextCatalog.GetString ("MonoDevelop failed to start. The following error has been reported: ") + error.Message);
				return 1;
			}

			if (errorsList.Count > reportedFailures) {
				AddinLoadErrorDialog dlg = new AddinLoadErrorDialog ((AddinError[]) errorsList.ToArray (typeof(AddinError)), true);
				dlg.Run ();
			}
			
			errorsList = null;
			
			// FIXME: we should probably track the last 'selected' one
			// and do this more cleanly
			try {
				listen_socket.Bind (ep);
				listen_socket.Listen (5);
				listen_socket.BeginAccept (new AsyncCallback (ListenCallback), listen_socket);
			} catch {
				// Socket already in use
			}
			
			initialized = true;
			MessageService.RootWindow = IdeApp.Workbench.RootWindow;
			Thread.CurrentThread.Name = "GUI Thread";
			Counters.Initialization.Trace ("Running IdeApp");
			Counters.Initialization.EndTiming ();
				
			AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
				
			IdeApp.Run ();
			
			// unloading services
			if (null != socket_filename)
				File.Delete (socket_filename);
			
			Runtime.Shutdown ();
			InstrumentationService.Stop ();
			
			System.Environment.Exit (0);
			return 0;
		}
        static void ParseCommandLineArgs(string[] args)
        {
            var showHelp = false;

            var options = new Mono.Options.OptionSet () {
                { "abi=", "ABI triple to generate", v => Abis.Add(v) },
                { "o|out=", "output directory", v => OutputDir = v },
                { "maccore=", "include directory", v => MaccoreDir = v },
                { "monodroid=", "top monodroid directory", v => MonodroidDir = v },
                { "android-ndk=", "Path to Android NDK", v => AndroidNdkPath = v },
                { "xamarin-android", "Generate for Xamarin.Android instead of monodroid", v => XamarinAndroid = true },
                { "mono=", "include directory", v => MonoDir = v },
                { "h|help",  "show this message and exit",  v => showHelp = v != null },
            };

            try {
                options.Parse (args);
            }
            catch (Mono.Options.OptionException e) {
                Console.WriteLine (e.Message);
                Environment.Exit(0);
            }

            if (showHelp)
            {
                // Print usage and exit.
                Console.WriteLine("{0} [--abi=triple] [--out=dir] "
                    + "[--monodroid/maccore=dir] [--mono=dir]",
                    AppDomain.CurrentDomain.FriendlyName);
                Environment.Exit(0);
            }
        }
示例#48
0
文件: Program.cs 项目: Caspeco/JSIL
        static void ParseCommandLine(IEnumerable<string> arguments, List<BuildGroup> buildGroups, Dictionary<string, IProfile> profiles)
        {
            var baseConfig = new Configuration();
            IProfile defaultProfile = new Profiles.Default();
            var profileAssemblies = new List<string>();
            bool[] autoloadProfiles = new bool[] { true };
            string[] newDefaultProfile = new string[] { null };
            List<string> filenames;

            {
                var os = new Mono.Options.OptionSet {
                    {"o=|out=",
                        "Specifies the output directory for generated javascript and manifests. " +
                        "You can use '%configpath%' in jsilconfig files to refer to the directory containing the configuration file, and '%assemblypath%' to refer to the directory containing the assembly being translated.",
                        (path) => baseConfig.OutputDirectory = Path.GetFullPath(path) },
                    {"nac|noautoconfig",
                        "Suppresses automatic loading of same-named .jsilconfig files located next to solutions and/or assemblies.",
                        (b) => baseConfig.AutoLoadConfigFiles = b == null },
                    {"nt|nothreads",
                        "Suppresses use of multiple threads to speed up the translation process.",
                        (b) => baseConfig.UseThreads = b == null },

                    "Solution Builder options",
                    {"configuration=",
                        "When building one or more solution files, specifies the build configuration to use (like 'Debug').",
                        (v) => baseConfig.SolutionBuilder.Configuration = v },
                    {"platform=",
                        "When building one or more solution files, specifies the build platform to use (like 'x86').",
                        (v) => baseConfig.SolutionBuilder.Platform = v },

                    "Assembly options",
                    {"p=|proxy=",
                        "Loads a type proxy assembly to provide type information for the translator.",
                        (name) => baseConfig.Assemblies.Proxies.Add(Path.GetFullPath(name)) },
                    {"i=|ignore=",
                        "Specifies a regular expression pattern for assembly names that should be ignored during the translation process.",
                        (regex) => baseConfig.Assemblies.Ignored.Add(regex) },
                    {"s=|stub=",
                        "Specifies a regular expression pattern for assembly names that should be stubbed during the translation process. " +
                        "Stubbing forces all methods to be externals.",
                        (regex) => baseConfig.Assemblies.Stubbed.Add(regex) },
                    {"nd|nodeps",
                        "Suppresses the automatic loading and translation of assembly dependencies.",
                        (b) => baseConfig.IncludeDependencies = b == null},
                    {"nodefaults",
                        "Suppresses the default list of stubbed assemblies.",
                        (b) => baseConfig.ApplyDefaults = b == null},
                    {"nolocal",
                        "Disables using local proxy types from translated assemblies.",
                        (b) => baseConfig.UseLocalProxies = b == null},
                    {"fv=|frameworkVersion=",
                        "Specifies the version of the .NET framework proxies to use. " +
                        "This ensures that correct type information is provided (as 3.5 and 4.0 use different standard libraries). " +
                        "Accepted values are '3.5' and '4.0'. Default: '4.0'",
                        (fv) => baseConfig.FrameworkVersion = double.Parse(fv)},

                    "Profile options",
                    {"nap|noautoloadprofiles",
                        "Disables automatic loading of profile assemblies from the compiler directory.",
                        (b) => autoloadProfiles[0] = (b == null)},
                    {"pa=|profileAssembly=",
                        "Loads one or more project profiles from the specified profile assembly. Note that this does not force the profiles to be used.",
                        (filename) => profileAssemblies.Add(filename)},
                    {"dp=|defaultProfile=",
                        "Overrides the default profile to use for projects by specifying the name of the new default profile..",
                        (profileName) => newDefaultProfile[0] = profileName},

                    "Optimizer options",
                    {"os",
                        "Suppresses struct copy elimination.",
                        (b) => baseConfig.Optimizer.EliminateStructCopies = b == null},
                    {"ot",
                        "Suppresses temporary local variable elimination.",
                        (b) => baseConfig.Optimizer.EliminateTemporaries = b == null},
                    {"oo",
                        "Suppresses simplification of operator expressions and special method calls.",
                        (b) => baseConfig.Optimizer.SimplifyOperators = b == null},
                    {"ol",
                        "Suppresses simplification of loop blocks.",
                        (b) => baseConfig.Optimizer.SimplifyLoops = b == null},
                };

                filenames = os.Parse(arguments);

                if (filenames.Count == 0) {
                    var asmName = Assembly.GetExecutingAssembly().GetName();
                    Console.WriteLine("==== JSILc v{0}.{1}.{2} ====", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision);
                    Console.WriteLine("Specify one or more compiled assemblies (dll/exe) to translate them. Symbols will be loaded if they exist in the same directory.");
                    Console.WriteLine("You can also specify Visual Studio solution files (sln) to build them and automatically translate their output(s).");
                    Console.WriteLine("Specify the path of a .jsilconfig file to load settings from it.");

                    os.WriteOptionDescriptions(Console.Out);

                    return;
                }
            }

            {
                if (autoloadProfiles[0])
                    profileAssemblies.AddRange(Directory.GetFiles(".", "JSIL.Profiles.*.dll"));

                foreach (var filename in profileAssemblies) {
                    var fullPath = Path.GetFullPath(filename);

                    try {
                        var assembly = Assembly.LoadFile(fullPath);

                        foreach (var type in assembly.GetTypes()) {
                            if (
                                type.FindInterfaces(
                                    (interfaceType, o) => interfaceType == (Type)o, typeof(IProfile)
                                ).Length != 1
                            )
                                continue;

                            var ctor = type.GetConstructor(
                                BindingFlags.Public | BindingFlags.Instance,
                                null, System.Type.EmptyTypes, null
                            );
                            var profileInstance = (IProfile)ctor.Invoke(new object[0]);

                            profiles.Add(type.Name, profileInstance);
                        }
                    } catch (Exception exc) {
                        Console.Error.WriteLine("Warning: Failed to load profile '{0}': {1}", filename, exc);
                    }
                }
            }

            baseConfig = MergeConfigurations(
                baseConfig,
                (from fn in filenames
                 where Path.GetExtension(fn) == ".jsilconfig"
                 select LoadConfiguration(fn)).ToArray()
            );

            foreach (var solution in
                     (from fn in filenames where Path.GetExtension(fn) == ".sln" select fn)
                    ) {

                var solutionConfigPath = Path.Combine(
                    Path.GetDirectoryName(solution),
                    String.Format("{0}.jsilconfig", Path.GetFileName(solution))
                );
                var solutionConfig = File.Exists(solutionConfigPath)
                    ? new Configuration[] { LoadConfiguration(solutionConfigPath) }
                    : new Configuration[] { };

                var config = MergeConfigurations(baseConfig, solutionConfig);
                var buildResult = SolutionBuilder.Build(
                    solution,
                    config.SolutionBuilder.Configuration,
                    config.SolutionBuilder.Platform
                );

                IProfile profile = defaultProfile;

                foreach (var candidateProfile in profiles.Values) {
                    if (!candidateProfile.IsAppropriateForSolution(buildResult))
                        continue;

                    Console.Error.WriteLine("// Auto-selected the profile '{0}' for this project.", candidateProfile.GetType().Name);
                    profile = candidateProfile;
                    break;
                }

                profile.ProcessBuildResult(
                    profile.GetConfiguration(config),
                    buildResult
                );

                buildGroups.Add(new BuildGroup {
                    BaseConfiguration = config,
                    FilesToBuild = buildResult.OutputFiles,
                    Profile = profile
                });
            }

            var mainGroup = (from fn in filenames
                             where
                                 (new[] { ".exe", ".dll" }.Contains(Path.GetExtension(fn)))
                             select fn).ToArray();

            if (mainGroup.Length > 0)
                buildGroups.Add(new BuildGroup {
                    BaseConfiguration = baseConfig,
                    FilesToBuild = mainGroup,
                    Profile = defaultProfile
                });
        }
示例#49
-1
        static void Main(string[] args)
        {
            bool show_help = false;

            var p = new Mono.Options.OptionSet() {
                { "q|quick", "quick run", _ => QuickRun = true },
                { "p|protobuf", "run protobuf tests", _ => RunProtoBufTests = true },
                { "v|verify", "verify results", _ => EnableResultCheck = true },
                { "threads=", "number of threads", (int v) => NumThreads = v },
                { "share", "share serializer between threads", _ => ShareSerializer = true },
                { "h|help",  "show help", _ => show_help = true },
            };

            List<string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (Mono.Options.OptionException e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            if (show_help || extra.Count > 0)
            {
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            if (ShareSerializer)
                s_sharedSerializer = Tester.CreateSerializer();

            List<Thread> threads = new List<Thread>();

            for (int i = 0; i < NumThreads; ++i)
            {
                var thread = new Thread(Test);
                threads.Add(thread);
            }

            foreach (var thread in threads)
                thread.Start();

            foreach (var thread in threads)
                thread.Join();
        }