Пример #1
0
        public Program()
        {
            options = new OptionSet();

            options.Add("offset=", "", v => offset_type = v);
            options.Add("all", "", v => show_all = v != null);
            options.Add("dos-header", "", v => show_dos_header = v != null);
            options.Add("dos-stub", "", v => show_dos_stub = v != null);
            options.Add("file-header", "", v => show_file_header = v != null);
            options.Add("optional-header", "", v => show_opt_header = v != null);
            options.Add("data-directories", "", v => show_data_directories = v != null);
            options.Add("sections", "", v => show_section_table = v != null);
            options.Add("debug", "", v => show_debug = v != null);
            options.Add("load-config", "", v => show_load_config = v != null);

            offset_type = "fo";
            show_all = false;
            show_dos_header = false;
            show_dos_stub = false;
            show_file_header = false;
            show_opt_header = false;
            show_data_directories = false;
            show_section_table = false;
            show_debug = false;
            show_load_config = false;
        }
Пример #2
0
        static void Main(string[] args)
        {
            string DirectoryName = null;
            bool Unzip = false;

            OptionSet options = new OptionSet();

            options.Add("?|h|help", value => PrintUsage());
            options.Add("output=", value => DirectoryName = value); // TODO -- Not currently used.
            options.Add("u", value => Unzip = true);

            foreach (string File in options.Parse(args))
            {
                Console.WriteLine("FIle ==> " + File); // TODO
                if (Unzip)
                {
                    Console.WriteLine("Unzip: {0} / {1}", File, File.Substring(0, File.Length - 4));
                    ZipFile.ExtractToDirectory(File, File.Substring(0, File.Length - 4));
                }
                else
                {
                    Console.WriteLine("Zip: {0} / {1}", File, File + ".zip");
                    ZipFile.CreateFromDirectory(File, File + ".zip");
                }
            }
        }
Пример #3
0
        static void Main(string[] args)
        {
            OptionSet Options = new OptionSet();
            bool SaveToFile = false;
            string FileName = null;
            int SleepDuration = 0;

            Options.Add("?|h|help", value => PrintUsage());
            Options.Add("f", value => SaveToFile = (value != null));
            Options.Add("filename=", value => FileName = value);
            Options.Add("timeout=", value => SleepDuration = Convert.ToInt32(value));

            Options.Parse(args);

            if (SleepDuration != 0)
            {
                System.Threading.Thread.Sleep(SleepDuration * 1000);
            }

            InjectPrintscreenKeySequence();

            using (Stream stream = printscreen.Properties.Resources.CameraSnap)
            {
                new SoundPlayer(stream).PlaySync();
            }

            if (SaveToFile || FileName != null)
            {
                SaveImageToFile(FileName);
            }
        }
        public void AddOptions(OptionSet options)
        {
            ArgumentUtility.CheckNotNull ("options", options);

              options.Add (
            "att|attribute=",
            "Mark affected methods with custom attribute [None | Generated | Custom] (default = Generated)",
            att => _mode = (AttributeMode) Enum.Parse (typeof (AttributeMode), att));
              options.Add (
            "attPrefix=",
            "The unspeakable prefix for the virtual method. (default value: '<>virtualized_')",
            prefix => _unspeakablePrefix = prefix);
              options.Add (
            "attFullName=",
            "Fullname of the attribute type (default value: 'NonVirtualAttributeNonVirtualAttribute').",
              at => {
                _attName = at.Substring (at.LastIndexOf (".") + 1, at.Length - at.LastIndexOf (".") - 1);
                _attNamespace = at.Substring (0, at.LastIndexOf ("."));
              } );
              options.Add (
            "attFile|attributeFile=",
            "Assembly containing the custom attribute (dll or exe). ONLY applicable in 'Custom' attribute mode!",
            custAtt => _attributeAssembly = custAtt);

              _selectionFactory = new TargetSelectorFactory ();
              _selectionFactory.AddOptions (options);
        }
 protected override void SetOptions(OptionSet options)
 {
     SetCommonOptions(options);
     options.Add("project=", "Name of the project", v => ProjectName = v);
     options.Add("from=", "Name of the environment to get the current deployment from, e.g., Staging", v => FromEnvironmentName = v);
     options.Add("to=|deployto=", "Environment to deploy to, e.g., Production", v => DeployToEnvironmentNames.Add(v));
 }
 internal static LexerOptions ParseOptions(string[] args)
 {
     var options = new OptionSet();
     var help = false;
     options.Add("h|?|help", "output this help information", o => help = true);
     var version = false;
     options.Add("V|version", "report version", o => version = true);
     var operands = options.Parse(args);
     if(help)
     {
         PrintHelp(options);
         return null;
     }
     if(version)
     {
         PrintVersion();
         return null;
     }
     if(operands.Count != 1)
     {
         Console.WriteLine("Must specify a single lexer file");
         PrintHelp(options);
         return null;
     }
     return new LexerOptions(operands[0]);
 }
Пример #7
0
        public static void Main(string[] args)
        {
            var libs = new List<Assembly> ();
            var opts = new OptionSet ();

            opts.Add ("r=", "load extra {ASSEMBLY}",
            x => {
                try {
                    libs.Add (System.Reflection.Assembly.LoadFile (x));
                } catch (System.IO.FileNotFoundException) {
                    Console.Error.WriteLine ("Error: no such assembly file " + x);
                    System.Environment.Exit (1);
                } catch (Exception e) {
                    Console.Error.WriteLine ("Error: " + e.Message);
                    System.Environment.Exit (1);
                }
            });

            opts.Add ("help", "print this message",
            x => {
                Console.WriteLine ("Usage: xamlpreviewer [OPTIONS] [FILE.xaml]");
                Console.WriteLine ();
                opts.WriteOptionDescriptions (Console.Out);
                Console.WriteLine ();
                System.Environment.Exit (1);
            });

            var remain = opts.Parse (args);
            string file = null;
            if (remain.Count > 0)
                file = remain [0];

            Start (file, libs);
        }
Пример #8
0
 public SignatureCommand()
 {
     options = new OptionSet();
     options.Positional("basis-file", "The file to read and create a signature from.", v => basisFilePath = v);
     options.Positional("signature-file", "The file to write the signature to.", v => signatureFilePath = v);
     options.Add("chunk-size=", string.Format("Maximum bytes per chunk. Defaults to {0}. Min of {1}, max of {2}.", SignatureBuilder.DefaultChunkSize, SignatureBuilder.MinimumChunkSize, SignatureBuilder.MaximumChunkSize), v => configuration.Add(builder => builder.ChunkSize = short.Parse(v)));
     options.Add("progress", "Whether progress should be written to stdout", v => configuration.Add(builder => builder.ProgressReporter = new ConsoleProgressReporter()));
 }
Пример #9
0
        public static void Run(params string[] args)
        {
            var logger = LoggerFactory();

            var config = new ElevatorConfiguration();
            var optionSet = new OptionSet();
            optionSet.Add("up", option =>
            {
                config.Direction = option;
            });
            optionSet.Add("assembly=", option =>
            {
                config.AssemblyIsSpecified = true;
                config.AssemblyName = option;
            });
            optionSet.Parse(args);

            if (string.IsNullOrEmpty(config.Direction))
            {
                logger.Log("You have to specify direction:");
                logger.Log("\tElevator.exe -up, for going up");
                logger.Log("\tElevator.exe -down, for going down (not supported yet)");
            }
            else if (!config.AssemblyIsSpecified)
            {
                logger.Log("You have to specify migration assembly:");
                logger.Log("\tElevator.exe -up -assembly:name.dll");
            }

            if (config.IsValid())
            {
                var migrationAssembly = Assembly.LoadFrom(Path.Combine(Environment.CurrentDirectory, config.AssemblyName));
                var levelDataStorageClasses = new LevelDataStorageClassFinder().Find(migrationAssembly);
                if (levelDataStorageClasses.Any())
                {
                    var levelDataStorage = Activator.CreateInstance(levelDataStorageClasses.First()) as ILevelDataStorage;
                    levelDataStorage.Initialize();

                    var levelsCalsses = new ElevatorLevelClassFinder().Find(migrationAssembly);
                    var levelFactory = new LevelFactory();
                    var levels = new List<Level>();

                    foreach (var levelClass in levelsCalsses)
                    {
                        levels.Add(levelFactory.NewLevel(levelClass));
                    }

                    var elevator = new Lift(new ConsoleLogger(), levelDataStorage);
                    elevator.AddLevel(levels.ToArray());
                    elevator.Start();
                    elevator.Top();
                }
                else
                {
                    logger.Log("Could not find a class in assembly 'Tests.Empty.dll' that implements the ILevelDataStorage interface.");
                }
            }
        }
Пример #10
0
 protected static void ParseJoinedOptions(string[] args, OptionSet set1, OptionSet set2)
 {
     var temp = new OptionSet();
     foreach (var s in set1)
         temp.Add(s);
     foreach (var s in set2)
         temp.Add(s);
     temp.Parse(args);
 }
Пример #11
0
 public PatchCommand()
 {
     options = new OptionSet();
     options.Positional("basis-file", "The file that the delta was created for.", v => basisFilePath = v);
     options.Positional("delta-file", "The delta to apply to the basis file", v => deltaFilePath = v);
     options.Positional("new-file", "The file to write the result to.", v => newFilePath = v);
     options.Add("progress", "Whether progress should be written to stdout", v => progressReporter = new ConsoleProgressReporter());
     options.Add("skip-verification", "Skip checking whether the basis file is the same as the file used to produce the signature that created the delta.", v => skipHashCheck = true);
 }
Пример #12
0
        private Program()
        {
            Context.Clear();
            AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => Context.Clear();

            optionSet = new OptionSet();
            optionSet.Add("port:", OptionCategory.General, "Change default port (8585).", s => port = int.Parse(s));
            optionSet.Add("h|?|help", OptionCategory.Help, string.Empty, v => PrintUsageAndExit(0));
        }
Пример #13
0
        public static void Main(string[] args)
        {
            bool showHelp = false;
            bool showVersion = false;

            // search in the local directory for espg files
            // so Windows ppl don't have to have it installed
            ProjFourWrapper.CustomSearchPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            MapSerializer ms = new MapSerializer();
            ms.AddDatabaseFeatureSourceType<PostGISFeatureSource>();
            ms.AddDatabaseFeatureSourceType<Cumberland.Data.SqlServer.SqlServerFeatureSource>();

            OptionSet options = new OptionSet();

            options.Add("h|help",  "show this message and exit",
                        delegate (string v) { showHelp = v!= null; });
            options.Add("v|version",
                        "Displays the version",
                        delegate(string v) { showVersion = v != null; });

            options.Parse(args);

            if (showVersion)
            {
                System.Console.WriteLine("Version " +
                                         System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
                return;
            }

            if (showHelp)
            {
                ShowHelp(options);
                return;
            }

            if (args.Length == 0)
            {
                Console.WriteLine("No Map file specified");
                ShowHelp(options);
                return;
            }

            if (args.Length == 1)
            {
                Console.WriteLine("No output file specified");
                ShowHelp(options);
                return;
            }

            Map map = ms.Deserialize(args[0]);

            File.WriteAllText(args[1],
                KeyholeMarkupLanguage.CreateFromMap(map),
                Encoding.UTF8);
        }
        public OctopusSessionFactory(ILog log, ICommandLineArgsProvider commandLineArgsProvider)
        {
            this.log = log;

            var options = new OptionSet();
            options.Add("server=", "The base URL for your Octopus server - e.g., http://myserver/", v => serverBaseUrl = v);
            options.Add("user="******"[Optional] Username to use when authenticating with the server.", v => user = v);
            options.Add("pass="******"[Optional] Password to use when authenticating with the server.", v => pass = v);

            options.Parse(commandLineArgsProvider.Args);
        }
        public void AddOptions(OptionSet options)
        {
            ArgumentUtility.CheckNotNull ("options", options);

              options.Add (
              "e|exclude=",
              "The targeted assemblies (eg: -b=Remotion.Interfaces.dll -b=SomeLibrary.*.dll)",
              b => _blackList.Add (b));
              options.Add (
              "s|subdirs",
              "Include subdirectories of the workingdir.",
              b => _includeSubDirs = (b != null ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
        }
        public void AddOptions(OptionSet options)
        {
            ArgumentUtility.CheckNotNull ("options", options);

              options.Add (
            "newInfo=",
            "The assembly qualified name of the info provider class for the NewTransformer.",
            n => _infoProviderName = n);
              options.Add (
            "newWrap",
            "Make ctor protected and introduce factory method.",
            f => _factoryMakeProtected = (f != null));
        }
        public void AddOptions(OptionSet options)
        {
            ArgumentUtility.CheckNotNull ("options", options);

              options.Add (
            "k|defaultKey=",
            "The default key (.snk) to be used to sign Assemblies.",
            key => _defaultKeyFile = key);
              options.Add (
            "y|keyDir=",
            "The root dir of all available keys (.snk) to sign Assemblies.",
            allKeys => _allKeysDirectory = allKeys);
        }
 public void Configure(OptionSet set, List<IZipOperation> operations)
 {
     set.Add("remove=", value =>
         {
             var regex = new Regex(value);
             operations.Add(new RemoveOperation(regex, value));
         });
     set.Add("iremove=", "Ignore case remove regex", value =>
         {
             var regex = new Regex(value, RegexOptions.IgnoreCase);
             operations.Add(new RemoveOperation(regex, "i/" + value));
         });
 }
Пример #19
0
        static void Main(string[] args)
        {
            string sourcePath = null;
            string targetPath = null;
            string filePattern = null;
            FileAttributes fileAttributes = FileAttributes.Normal;
            bool help = false;

            // Create the command line option set.
            OptionSet optionSet = new OptionSet();
            optionSet.Add("?", "Displays this help message.", v => help = true);
            optionSet.Add("td:", "Target Directory.", v => targetPath = v);
            optionSet.Add("sd:", "Source Directory.", v => sourcePath = v);
            optionSet.Add("fp:", @"File Pattern. Optional. Defaults to ""*.*"".", v => filePattern = v ?? "*.*");
            optionSet.Add("fa:", @"ile Attributes. Optional. Comma delimited list. Defaults to ""Any"".",
                v => fileAttributes = v == null ? FileAttributes.Normal :
                    (FileAttributes)Enum.Parse(typeof(FileAttributes), v));
            List<string> unknownOptions = optionSet.Parse(args);

            //
            using(ConsoleWriter consoleWriter = new ConsoleWriter())
            {
                if (unknownOptions != null && unknownOptions.Any())
                {
                    unknownOptions.ForEach(o => consoleWriter.WriteWarning(string.Format("Option not known: \"{0}\".", o)));
                    consoleWriter.WriteInformation(GetForHelpMessage());
                    return;
                }
                if (help)
                {
                    consoleWriter.WriteInformation(GetHelpMessage(optionSet));
                    return;
                }
                if (targetPath == null)
                {
                    consoleWriter.WriteError("Target Directory not specified.");
                    consoleWriter.WriteInformation(GetForHelpMessage());
                    return;
                }
                if (sourcePath == null)
                {
                    consoleWriter.WriteError("Source Directory not specified.");
                    consoleWriter.WriteInformation(GetForHelpMessage());
                    return;
                }
                var fileSystem = new System.IO.Abstractions.FileSystem();
                Cleaner.Clean(fileSystem, targetPath, sourcePath, filePattern, fileAttributes);
            }
        }
 public void AddOptions(OptionSet options)
 {
     options.Add (
        "regex=",
        "The regular expression matching the targeted methods full name.",
        r => _regex = r);
       options.Add (
        "selectionAttribute=",
        "The fullname of the attribute marking the classes or methods that should be made virtual. Subclasses are included.",
        atName => _attributeName = atName);
       options.Add (
        "selectionClassName=",
        "The fullname(s) of the classes whose methods should be made virtual. Subclasses are included.",
        name => _classNames.Add (name));
 }
Пример #21
0
        static void Main(string[] args)
        {
            List<string> FileList = new List<string>();
            OptionSet Options = new OptionSet();
            int PartitionSize = DefaultPartitionSize;
            int DirectoryIndex = 0;
            int FileCount = 0;
            string DirectoryName = "";

            Options.Add("?|h|help", value => PrintUsage());
            Options.Add("count", value => PartitionSize = Int32.Parse(value));
            Options.Parse(args);

            //
            // If we don't have any parameters then we will partition all the files in the current directory.
            //
            if (args.Length == 0)
            {
                args = new string[] { "*.*" };
            }

            foreach (string arg in args)
            {
                if (File.Exists(arg))
                {
                    FileList.Add(arg);
                }
                else
                {
                    //
                    // Not a file, so it's a wildcard (hopefully!).
                    //
                    FileList.AddRange(Directory.EnumerateFiles(".", arg));
                }
            }

            foreach (string FileName in FileList)
            {
                if ((FileCount % PartitionSize) == 0)
                {
                    DirectoryName = String.Format("{0:D4}", DirectoryIndex++);
                    Directory.CreateDirectory(DirectoryName);
                }

                File.Move(FileName, Path.Combine(DirectoryName, FileName));
                FileCount++;
            }
        }
Пример #22
0
 public void BindCommadLineParameters(OptionSet optionSet)
 {
     optionSet
         .Add("i|include=", "Include files to the package", _includes.Add)
         .Add("o|output=", "Name of the output file", x => _outputFileName = x)
         .Add("cn=", "CN of the certificate", x => _cn = x);
 }
Пример #23
0
 public override void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
         .Add(
             "s=|source=",
             "Source - Source location for install. Can include special 'webpi'. Defaults to sources.",
             option => configuration.Sources = option.remove_surrounding_quotes())
         .Add(
             "l|lo|localonly|local-only",
             "LocalOnly - Only search against local machine items.",
             option => configuration.ListCommand.LocalOnly = option != null)
         .Add(
             "pre|prerelease",
             "Prerelease - Include Prereleases? Defaults to false.",
             option => configuration.Prerelease = option != null)
         .Add(
             "u=|user="******"User - used with authenticated feeds. Defaults to empty.",
             option => configuration.SourceCommand.Username = option.remove_surrounding_quotes())
         .Add(
             "p=|password="******"Password - the user's password to the source. Defaults to empty.",
             option => configuration.SourceCommand.Password = option.remove_surrounding_quotes())
         ;
 }
Пример #24
0
 public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
         .Add("s=|source=",
              "Source - Source location for install. Can include special 'webpi'. Defaults to sources.",
              option => configuration.Sources = option.remove_surrounding_quotes())
         .Add("l|lo|localonly|local-only",
              "LocalOnly - Only search against local machine items.",
              option => configuration.ListCommand.LocalOnly = option != null)
         .Add("pre|prerelease",
              "Prerelease - Include Prereleases? Defaults to false.",
              option => configuration.Prerelease = option != null)
         .Add("i|includeprograms|include-programs",
              "IncludePrograms - Used in conjunction with LocalOnly, filters out apps chocolatey has listed as packages and includes those in the list. Defaults to false.",
              option => configuration.ListCommand.IncludeRegistryPrograms = option != null)
         .Add("a|all|allversions|all-versions",
              "AllVersions - include results from all versions.",
              option => configuration.AllVersions = option != null)
         .Add("u=|user="******"User - used with authenticated feeds. Defaults to empty.",
              option => configuration.SourceCommand.Username = option.remove_surrounding_quotes())
         .Add("p=|password="******"Password - the user's password to the source. Defaults to empty.",
              option => configuration.SourceCommand.Password = option.remove_surrounding_quotes())
         ;
     //todo exact name
 }
 protected override void SetOptions(OptionSet options)
 {
     SetCommonOptions(options);
     options.Add("project=", "Name of the project", v => ProjectName = v);
     options.Add("deployto=", "Environment to deploy to, e.g., Production", v => DeployToEnvironmentNames.Add(v));
     options.Add("releaseNumber=|version=", "Version number of the release to deploy.", v => VersionNumber = v);
 }
Пример #26
0
        private static void Main(string[] args)
        {
            bool showVersionNumber = false;
            bool showHelp = false;
            OptionSet opt = new OptionSet();
            opt.Add("?|help", "Display this help.", v => showHelp = true);

            try
            {
                List<string> extra = opt.Parse(args);
            }
            catch (OptionException ex)
            {
                PrintHelp(opt);
            }

            if (showHelp)
            {
                PrintHelp(opt);
            }
            else
            {
                Console.WriteLine(GetUptimeString());
            }
        }
Пример #27
0
 public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
         .Add("s=|source=",
              "Source - The source to find the package(s) to install. Special sources include: ruby, webpi, cygwin, windowsfeatures, and python. Defaults to default feeds.",
              option => configuration.Sources = option)
         .Add("version=",
              "Version - A specific version to uninstall. Defaults to unspecified.",
              option => configuration.Version = option.remove_surrounding_quotes())
         .Add("a|allversions|all-versions",
              "AllVersions - Uninstall all versions? Defaults to false.",
              option => configuration.AllVersions = option != null)
         .Add("ua=|uninstallargs=|uninstallarguments=|uninstall-arguments=",
              "UninstallArguments - Uninstall Arguments to pass to the native installer in the package. Defaults to unspecified.",
              option => configuration.InstallArguments = option.remove_surrounding_quotes())
         .Add("o|override|overrideargs|overridearguments|override-arguments",
              "OverrideArguments - Should uninstall arguments be used exclusively without appending to current package passed arguments? Defaults to false.",
              option => configuration.OverrideArguments = option != null)
         .Add("notsilent|not-silent",
              "NotSilent - Do not uninstall this silently. Defaults to false.",
              option => configuration.NotSilent = option != null)
         .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=",
              "PackageParameters - Parameters to pass to the package. Defaults to unspecified.",
              option => configuration.PackageParameters = option.remove_surrounding_quotes())
         .Add("x|forcedependencies|force-dependencies|removedependencies|remove-dependencies",
              "RemoveDependencies - Uninstall dependencies when uninstalling package(s). Defaults to false.",
              option => configuration.ForceDependencies = option != null)
         .Add("n|skippowershell|skip-powershell",
              "Skip Powershell - Do not run chocolateyUninstall.ps1. Defaults to false.",
              option => configuration.SkipPackageInstallProvider = option != null)
         ;
 }
Пример #28
0
        public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
        {
            configuration.Sources = null;
            configuration.PushCommand.TimeoutInSeconds = 300;

            optionSet
                .Add("s=|source=",
                     "Source - The source we are pushing the package to. Use {0} to push to community feed.".format_with(ApplicationParameters.ChocolateyCommunityFeedPushSource),
                     option => configuration.Sources = option.remove_surrounding_quotes())
                .Add("k=|key=|apikey=|api-key=",
                     "ApiKey - The api key for the source. If not specified (and not local file source), does a lookup. If not specified and one is not found for an https source, push will fail.",
                     option => configuration.PushCommand.Key = option.remove_surrounding_quotes())
                .Add("t=|timeout=",
                     "Timeout (in seconds) - The time to allow a package push to occur before timing out. Defaults to 300 seconds (5 minutes).",
                     option =>
                         {
                             int timeout = 0;
                             int.TryParse(option, out timeout);
                             if (timeout > 0)
                             {
                                 configuration.PushCommand.TimeoutInSeconds = timeout;
                             }
                         })
                //.Add("b|disablebuffering|disable-buffering",
                //    "DisableBuffering -  Disable buffering when pushing to an HTTP(S) server to decrease memory usage. Note that when this option is enabled, integrated windows authentication might not work.",
                //    option => configuration.PushCommand.DisableBuffering = option)
                ;
            //todo: push command - allow disable buffering?
        }
Пример #29
0
 public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
         .Add("a|auto|automaticpackage",
              "AutomaticPackage - Generate automatic package instead of normal. Defaults to false",
              option => configuration.NewCommand.AutomaticPackage = option != null)  
         .Add("t=|template=|template-name=",
              "TemplateName - Use a named template in {0}\\templates\\templatename instead of built-in template.".format_with(ApplicationParameters.InstallLocation),
              option => configuration.NewCommand.TemplateName = option)
         .Add("name=",
              "Name [Required]- the name of the package. Can be passed as first parameter without \"--name=\".",
              option =>
                  {
                      configuration.NewCommand.Name = option.remove_surrounding_quotes();
                      configuration.NewCommand.TemplateProperties.Add(TemplateValues.NamePropertyName, option.remove_surrounding_quotes());
                  })
         .Add("version=",
              "Version - the version of the package. Can also be passed as the property PackageVersion=somevalue",
              option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.VersionPropertyName, option.remove_surrounding_quotes()))
         .Add("maintainer=",
              "Maintainer - the name of the maintainer. Can also be passed as the property MaintainerName=somevalue",
              option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.MaintainerPropertyName, option.remove_surrounding_quotes()))
         ;
     //todo: more built-in templates
 }
Пример #30
0
 static void Main(string[] args)
 {
     XmlConfigurator.Configure();
       var options = new OptionSet();
       var principal = 0.0d;
       var rate = 0.0d;
       var payments = 0;
       options.Add("p=|principal=", v => principal = double.Parse(v))
      .Add("r=|rate=", v => rate = double.Parse(v) / 100.0d)
      .Add("n=|payments=", v => payments = int.Parse(v));
       options.Parse(args);
       var calculator = new AmortizationLibrary.AmortizationCalculator();
       var amortizationSchedule = calculator.Calculate(principal, rate, payments);
       foreach(var detail in amortizationSchedule)
       {
     Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}",
       detail.PaymentNumber,
       detail.Payment.ToString("C"),
       detail.InterestPaid.ToString("C"),
       detail.PrincipalPaid.ToString("C"),
       detail.Balance.ToString("C")
       );
       }
       Console.ReadLine();
 }
Пример #31
0
 public void AddOptionSet(OptionSet options)
 {
     options.Add("encoding=", "Text file encoding. The default is 'UTF-8'.", v => Encoding        = Encoding.GetEncoding(v));
     options.Add("bitmap=", "Writes the image as a bitmap. The default is false.", v => UseBitmap = v != null);
 }
Пример #32
0
 public override void Enable(OptionSet options)
 {
     options.Add("log-seq=", "Log output to a Seq server at the specified URL", v => _serverUrl = v);
     options.Add("log-seq-apikey=", "If logging to Seq, an optional API key", v => _apiKey      = v);
     options.Add("log-debug", "Write additional diagnostic log output", v => _level             = LogEventLevel.Debug);
 }
Пример #33
0
 public override void Enable(OptionSet options)
 {
     options.Add("timeout=", "The execution timeout in milliseconds", v => _timeoutMS = int.Parse(v?.Trim() ?? "0"));
 }
Пример #34
0
        public static void Main(string[] args)
        {
            System.Threading.Thread.CurrentThread.Name = "Main";

            // initialize log level
            log4net.Repository.ILoggerRepository repo = log4net.LogManager.GetRepository();
            repo.Threshold = log4net.Core.Level.Error;

            InitLocale();

            var debug  = false;
            var parser = new OptionSet()
            {
                { "d|debug", _("Enable debug output"),
                  val => {
                      debug = true;
                  } }
            };

            parser.Add("h|help", _("Show this help"),
                       val => {
                ShowUsage(parser);
                Environment.Exit(0);
            }
                       );

            try {
                var mainArgs = args.TakeWhile(x => x.StartsWith("-"));
                parser.Parse(mainArgs);
                if (debug)
                {
                    repo.Threshold = log4net.Core.Level.Debug;
                }

                var action = args.Skip(mainArgs.Count()).FirstOrDefault();
                if (String.IsNullOrEmpty(action))
                {
                    ShowUsage(parser);
                    Environment.Exit(1);
                }

                var actionArgs = args.Skip(mainArgs.Count() + 1);
                switch (action.ToLower())
                {
                case "cat":
                    CatAction(action, actionArgs);
                    break;

                case "convert":
                case "copy":
                case "cp":
                    CopyAction(action, actionArgs);
                    break;

                default:
                    throw new OptionException(
                              String.Format(
                                  _("Unknown action: '{0}'"),
                                  action
                                  ),
                              "action"
                              );
                }
            } catch (OptionException ex) {
                Console.Error.WriteLine(_("Command line error: {0}"), ex.Message);
                Environment.Exit(1);
            } catch (Exception e) {
                Logger.Fatal(e);
            }
        }
Пример #35
0
        /// <summary>
        /// Starts the actual application.
        /// </summary>
        /// <param name="args">The arguments for the application.</param>
        /// <param name="usesShadowCopying">A flag indicating whether shadow copying should be used.</param>
        /// <returns>
        /// The return code for the application.
        /// </returns>
        public int Run(string[] args, bool usesShadowCopying)
        {
            // Parse the command line arguments
            var webOptions  = new WebApiOptions();
            var consoleArgs = new ConsoleRunnerArguments();
            var opts        = new OptionSet();

            opts.Add("h|?|help", "display this help screen", v => consoleArgs.ShowHelp = v != null)
            .Add("c|config=", "the configuration file to use (defaults to ccnet.conf)", v => consoleArgs.ConfigFile = v)
            .Add("r|remoting=", "turn remoting on/off (defaults to on)", v => consoleArgs.UseRemoting                = v == "on")
            .Add("p|project=", "the project to integrate (???)", v => consoleArgs.Project                            = v)
            .Add("v|validate", "validate the configuration file and exit", v => consoleArgs.ValidateConfigOnly       = v != null)
            .Add("l|logging=", "turn logging on/off (defaults to on)", v => consoleArgs.Logging                      = v == "on")
            .Add("sc|shadowCopy=", "turn shadow copying on/off (defaults to on)", v => usesShadowCopying             = v == "on")
            .Add("e|errorpause=", "turn pause on error on/off (defaults to on)", v => consoleArgs.PauseOnError       = v == "on")
            .Add("we|webEndPoint=", "the base endpoint for the web API (default none)", v => webOptions.BaseEndpoint = v);
            try
            {
                opts.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(1);
            }

            // Display the help
            if (consoleArgs.ShowHelp)
            {
                DisplayHelp(opts);
                return(0);
            }

            ICruiseServerFactory factory = null;

            try
            {
                // Start the actual console runner
                if (webOptions.IsConfigured)
                {
                    var apiFactory = new WebApiServerFactory();
                    apiFactory.StartWebApi(apiFactory, webOptions);
                    factory = apiFactory;
                }
                else
                {
                    factory = new CruiseServerFactory();
                }

                runner = new ConsoleRunner(consoleArgs, factory);
                if (!usesShadowCopying)
                {
                    Log.Warning("Shadow-copying has been turned off - hot-swapping will not work!");
                }

                runner.Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                if (consoleArgs.PauseOnError)
                {
                    Console.WriteLine("An unexpected error has caused the console to crash");
                    Console.ReadKey();
                }
                return(2);
            }
            finally
            {
                // Clean up
                runner = null;
                var disposable = factory as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Пример #36
0
        private void Initialize()
        {
            op = new BackupParameters()
            {
                NoWait      = false,
                Incremental = false
            };

            dispatcher = new BackupOperationDispatcher();

            optionSet            = new OptionSet();
            optionSet.OnWarning += s => ConsoleHelper.WriteLineWithColor(ConsoleColor.Yellow, s);
            optionSet.Add("url=", OptionCategory.None, "RavenDB server {0:url}", url => op.ServerUrl            = url);
            optionSet.Add("dest=", OptionCategory.None, "Full {0:path} to backup folder", path => op.BackupPath = path);
            optionSet.Add("nowait", OptionCategory.None, "Return immediately without waiting for a response from the server", _ => op.NoWait = true);
            optionSet.Add("readkey", OptionCategory.None, "Specifying this flag will make the utility wait for key press before exiting.", _ => doReadKeyOnExit = true);
            optionSet.Add("d|database:", OptionCategory.RestoreDatabase, "The database to operate on. If no specified, the operations will be on the default database unless filesystem option is set.", value => op.Database = value);
            optionSet.Add("f|filesystem:", OptionCategory.RestoreFileSystem, "The filesystem to operate on.", value => op.Filesystem = value);
            optionSet.Add("u|user|username:"******"The username to use when the database requires the client to authenticate.", value => op.Credentials.UserName = value);
            optionSet.Add("p|pass|password:"******"The password to use when the database requires the client to authenticate.", value => op.Credentials.Password = value);
            optionSet.Add("domain:", OptionCategory.None, "The domain to use when the database requires the client to authenticate.", value => op.Credentials.Domain = value);
            optionSet.Add("key|api-key|apikey:", OptionCategory.None, "The API-key to use, when using OAuth.", value => op.ApiKey = value);
            optionSet.Add("incremental", OptionCategory.None, "When specified, the backup process will be incremental when done to a folder where a previous backup lies. If dest is an empty folder, or it does not exist, a full backup will be created. For incremental backups to work, the configuration option Raven/Esent/CircularLog must be set to false for Esent storage or option Raven/Voron/AllowIncrementalBackups must be set to true for Voron.", _ => op.Incremental = true);
            optionSet.Add("timeout:", OptionCategory.None, "The timeout to use for requests", s => op.Timeout = int.Parse(s));
            optionSet.Add("h|?|help", OptionCategory.Help, string.Empty, v =>
            {
                PrintUsage();
                Environment.Exit(0);
            });
        }
Пример #37
0
 public override void Enable(OptionSet options)
 {
     options.Add("i=|input=",
                 "CLEF file to ingest; if not specified, `STDIN` will be used",
                 v => InputFilename = string.IsNullOrWhiteSpace(v) ? null : v.Trim());
 }
Пример #38
0
        public void Invoke(string[] args)
        {
            bool showHelp = false;
            bool users    = false;
            bool mods     = false;
            bool forum    = false;

            var options = new OptionSet();

            options.Add(
                "?|help",
                "Show help information.",
                x => showHelp = x != null
                );
            options.Add(
                "users",
                "Show statistics about U413 members.",
                x => users = x != null
                );
            options.Add(
                "modsquad",
                "List all U413 moderators.",
                x => mods = x != null
                );
            options.Add(
                "forum",
                "Display forum statistics.",
                x => forum = x != null
                );

            if (args == null)
            {
                this.CommandResult.WriteLine(DisplayTemplates.InvalidArguments);
            }
            else
            {
                try
                {
                    var parsedArgs = options.Parse(args).ToArray();

                    if (parsedArgs.Length == args.Length)
                    {
                        this.CommandResult.WriteLine(DisplayTemplates.InvalidArguments);
                    }
                    else
                    {
                        if (showHelp)
                        {
                            HelpUtility.WriteHelpInformation(
                                this.CommandResult,
                                this.Name,
                                this.Parameters,
                                this.Description,
                                options
                                );
                        }
                        else
                        {
                            if (users)
                            {
                                var userStats     = _userRepository.GetUserStatistics();
                                var loggedInUsers = _userRepository.GetLoggedInUsers();

                                var displayMode = DisplayMode.DontType;
                                this.CommandResult.WriteLine(displayMode, "There are {0} users registered on U413.", userStats.TotalRegisteredUsers);
                                this.CommandResult.WriteLine(displayMode, "{0} users are currently banned for various acts of faggotry.", userStats.TotalBannedUsers);
                                this.CommandResult.WriteLine();
                                this.CommandResult.WriteLine(displayMode, "{0} users have registered within the last 24 hours.", userStats.NewUsersInTheLast24Hours);
                                this.CommandResult.WriteLine(displayMode, "{0} users have registered within the last week.", userStats.NewUsersInTheLastWeek);
                                this.CommandResult.WriteLine(displayMode, "{0} users have registered within the last month.", userStats.NewUsersInTheLastMonth);
                                this.CommandResult.WriteLine(displayMode, "{0} users have registered within the last year.", userStats.NewUsersInTheLastYear);
                                this.CommandResult.WriteLine();
                                this.CommandResult.WriteLine(displayMode, "{0} users have logged in within the last 24 hours.", userStats.LoggedInWithinTheLast24Hours);
                                this.CommandResult.WriteLine(displayMode, "{0} users have logged in within the last week.", userStats.LoggedInWithinTheLastWeek);
                                this.CommandResult.WriteLine(displayMode, "{0} users have logged in within the last month.", userStats.LoggedInWithinTheLastMonth);
                                this.CommandResult.WriteLine(displayMode, "{0} users have logged in within the last year.", userStats.LoggedInWithinTheLastYear);
                                this.CommandResult.WriteLine();
                                this.CommandResult.WriteLine(displayMode | DisplayMode.Dim, new string('-', AppSettings.DividerLength));
                                this.CommandResult.WriteLine();
                                this.CommandResult.WriteLine(displayMode, "There are currently {0} user(s) online.", loggedInUsers.Count());
                                this.CommandResult.WriteLine();
                                foreach (var user in loggedInUsers)
                                {
                                    this.CommandResult.WriteLine(displayMode, user.Username);
                                }
                            }
                            if (mods)
                            {
                                var staff       = _userRepository.GetModeratorsAndAdministrators();
                                var displayMode = DisplayMode.DontType;
                                this.CommandResult.WriteLine(displayMode, "There are {0} moderators on U413.", staff.Count());
                                this.CommandResult.WriteLine();
                                foreach (var user in staff)
                                {
                                    var tenMinutesAgo = DateTime.UtcNow.AddMinutes(-10);
                                    var isOnline      = user.LastLogin > tenMinutesAgo;
                                    this.CommandResult.WriteLine(
                                        displayMode,
                                        "{0}{1}{2}",
                                        user.Username,
                                        user.IsAdministrator ? " (admin)" : null,
                                        isOnline ? " (online)" : null
                                        );
                                }
                            }
                            if (forum)
                            {
                                var forumStats = _topicRepository.GetForumStats();
                                int numReplies = _topicRepository.GetTopic(forumStats.MostPopularTopic).Replies.Count();

                                var displayMode = DisplayMode.DontType;
                                this.CommandResult.WriteLine(displayMode, "There are {0} total topics on U413.", forumStats.TotalTopics);
                                this.CommandResult.WriteLine(displayMode, "Topic {0} is the most popular topic with {1} replies.", forumStats.MostPopularTopic, numReplies);
                                this.CommandResult.WriteLine(displayMode, "{0} topics have been created within the last 24 hours.", forumStats.TopicsInTheLast24Hours);
                                this.CommandResult.WriteLine(displayMode, "{0} topics have been created within the last week.", forumStats.TopicsInTheLastWeek);
                                this.CommandResult.WriteLine(displayMode, "{0} topics have been created within the last month.", forumStats.TopicsInTheLastMonth);
                                this.CommandResult.WriteLine(displayMode, "{0} topics have been created within the last year.", forumStats.TopicsInTheLastYear);
                                this.CommandResult.WriteLine();
                                this.CommandResult.WriteLine(displayMode, "There are {0} total posts on U413.", forumStats.TotalPosts);
                                this.CommandResult.WriteLine(displayMode, "{0} posts have been made within the last 24 hours.", forumStats.PostsInTheLast24Hours);
                                this.CommandResult.WriteLine(displayMode, "{0} posts have been made within the last week.", forumStats.PostsInTheLastWeek);
                                this.CommandResult.WriteLine(displayMode, "{0} posts have been made within the last month.", forumStats.PostsInTheLastMonth);
                                this.CommandResult.WriteLine(displayMode, "{0} posts have been made within the last year.", forumStats.PostsInTheLastYear);
                            }
                        }
                    }
                }
                catch (OptionException ex)
                {
                    this.CommandResult.WriteLine(ex.Message);
                }
            }
        }
Пример #39
0
        static int Main(string[] args)
        {
            // SslLabsCli ssllabs.com --progress --new --nowait

            Options options = new Options();

            OptionSet parser = new OptionSet();

            parser.Add("p|progress", "Show progress while waiting", s => options.Progress = true);
            parser.Add("n|new", "Force a new scan", s => options.New = true);
            parser.Add("w|nowait", "Exit if no scan is available", s => options.NoWait = true);
            parser.Add("s|save", "Save the scan to a file", s => options.Save          = s);

            List <string> leftoverArgs = parser.Parse(args);

            options.Hostname = leftoverArgs.FirstOrDefault();

            if (string.IsNullOrEmpty(options.Hostname))
            {
                Console.WriteLine("Usage: ");
                Console.WriteLine("  SslLabsCli [options] ssllabs.com");
                Console.WriteLine();
                Console.WriteLine("Options");
                parser.WriteOptionDescriptions(Console.Out);
                Console.WriteLine();

                return(1);
            }

            Analysis analysis = HandleFetch(options);

            if (analysis.Status == AnalysisStatus.ERROR)
            {
                AwesomeConsole.WriteLine("An error occurred", ConsoleColor.Red);
                AwesomeConsole.Write("Status: ");
                AwesomeConsole.WriteLine(analysis.StatusMessage, ConsoleColor.Cyan);

                AwesomeConsole.WriteLine("Messages from SSLLabs");
                Info info = _client.GetInfo();

                foreach (string msg in info.Messages)
                {
                    AwesomeConsole.WriteLine("  " + msg, ConsoleColor.Yellow);
                }

                return(3);
            }

            if (analysis.Status != AnalysisStatus.READY)
            {
                AwesomeConsole.WriteLine("Analysis not available", ConsoleColor.DarkYellow);
                return(2);
            }

            PresentAnalysis(analysis);

            if (!string.IsNullOrEmpty(options.Save))
            {
                File.WriteAllText(options.Save, JsonConvert.SerializeObject(analysis, Formatting.Indented));
            }

            return(0);
        }
Пример #40
0
        static bool ParseCommandLineArgs(string[] args, List <string> messages, ref bool helpShown)
        {
            var showHelp = false;

            optionSet.Add("I=", "the {PATH} of a folder to search for include files", (i) => { AddIncludeDirs(i, messages); });
            optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l));
            optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l));
            optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, messages));
            optionSet.Add("A=", "additional Clang arguments to pass to the compiler while parsing the given header files", (v) => AddArgument(v, messages));

            optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, messages));
            optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on);

            optionSet.Add("iln=|inputlibraryname=|inputlib=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln);
            optionSet.Add("d|debug", "enables debug mode which generates more verbose code to aid debugging", v => options.Debug = true);
            optionSet.Add("c|compile", "enables automatic compilation of the generated code", v => options.Compile = true);
            optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'chsarp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, messages); });
            optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, messages); });
            optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, messages); });

            optionSet.Add("exceptions", "enables support for C++ exceptions in the parser", v => { options.Arguments.Add("-fcxx-exceptions"); });

            optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); });
            optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); });
            optionSet.Add("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); });

            optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); });

            List <string> additionalArguments = null;

            try
            {
                additionalArguments = optionSet.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }

            if (showHelp || additionalArguments != null && additionalArguments.Count == 0)
            {
                helpShown = true;
                ShowHelp();
                return(false);
            }

            foreach (string s in additionalArguments)
            {
                HandleAdditionalArgument(s, messages);
            }

            return(true);
        }
Пример #41
0
        static void Main(string[] args)
        {
            bool      help        = false;
            string    inputPath   = "";
            string    outputPath  = "";
            bool      disassemble = false;
            bool      assemble    = false;
            bool      recursive   = false;
            bool      verbose     = false;
            string    text        = "";
            bool      repl        = false;
            OptionSet optSet      = new OptionSet();

            optSet.Add("?|help|h", "Prints out the options.", option => help                = option != null);
            optSet.Add("d|disassemble", "Disassembler mode.", option => disassemble         = option != null);
            optSet.Add("a|assemble", "Assembler mode.", option => assemble                  = option != null);
            optSet.Add("i=|in=", "Input File or Directory.", option => inputPath            = option);
            optSet.Add("o=|out=", "Output File or Directory.", option => outputPath         = option);
            optSet.Add("t=|text=", "String to dis/assemble.", option => text                = option);
            optSet.Add("r|recursive", "Process directory recursively.", option => recursive = option != null);
            optSet.Add("v|verbose", "Verbose Logging.", option => verbose = option != null);
            optSet.Add("repl", "REPL mode", option => repl = option != null);
            optSet.Parse(args);

            if (repl)
            {
                RunREPL();
                return;
            }

            /* movd [MAIN+R1+0x6C7634], 0x98967F */

            if (assemble && disassemble)
            {
                Console.Error.WriteLine("You cannot specifiy both assembler and disassembler modes simultaneously.");
                return;
            }

            if (help)
            {
                Console.WriteLine("Usage: CheatASM -d/a -in FILE -out FILE");
                optSet.WriteOptionDescriptions(Console.Error);
            }

            /* ensure input exists and determine if it is a directory or not */
            bool isInputDir = false;
            bool textMode   = false;

            if (Directory.Exists(inputPath))
            {
                isInputDir = true;
                /* if you specified an input directory you must specifiy an output */
                if (outputPath == "")
                {
                    Console.Error.WriteLine("When processing a directoy an output directory *must* be specified.");
                    return;
                }
            }
            else
            {
                if (File.Exists(inputPath))
                {
                    isInputDir = false;
                }
                else
                {
                    if (text == "")
                    {
                        /* input path isn't an existing file or directory */
                        Console.Error.WriteLine("Unable to find the input path specified.");
                        return;
                    }
                    else
                    {
                        textMode = true;
                    }
                }
            }

            /* at this point we know the inputPath exists, and if its a folder or not */

            Assembler    asm    = new Assembler();
            Disassembler disasm = new Disassembler();

            if (isInputDir)
            {
                string[] fileList = Directory.GetFiles(inputPath, "*.txt", new EnumerationOptions()
                {
                    RecurseSubdirectories = recursive
                });

                foreach (var file in fileList)
                {
                    var relativePath = file.Replace(inputPath, "");

                    /* make sure folder exists */
                    var newFolderPath = outputPath + relativePath.Substring(0, relativePath.LastIndexOf(Path.DirectorySeparatorChar));
                    Directory.CreateDirectory(newFolderPath);
                    if (verbose)
                    {
                        Console.WriteLine("Saving " + outputPath + relativePath + "...");
                    }
                    if (assemble)
                    {
                        File.WriteAllText(outputPath + relativePath, asm.AssembleFile(file));
                    }
                    else
                    {
                        File.WriteAllText(outputPath + relativePath, disasm.DisassembleFile(file));
                    }
                }
                Console.WriteLine("Processed " + fileList.Length + " files.");
            }
            else
            {
                /* dealing with a single file */
                if (assemble)
                {
                    if (outputPath != "")
                    {
                        if (textMode)
                        {
                            File.WriteAllText(outputPath, asm.AssembleLine(text));
                        }
                        else
                        {
                            File.WriteAllText(outputPath, asm.AssembleFile(inputPath));
                        }
                    }
                    else
                    {
                        if (textMode)
                        {
                            Console.Write(asm.AssembleLine(text));
                        }
                        else
                        {
                            Console.Write(asm.AssembleFile(inputPath));
                        }
                    }
                }
                else
                {
                    if (outputPath != "")
                    {
                        if (textMode)
                        {
                            File.WriteAllText(outputPath, disasm.DisassembleLine(text));
                        }
                        else
                        {
                            File.WriteAllText(outputPath, disasm.DisassembleFile(inputPath));
                        }
                    }
                    else
                    {
                        if (textMode)
                        {
                            Console.Write(disasm.DisassembleLine(text));
                        }
                        else
                        {
                            Console.Write(disasm.DisassembleFile(inputPath));
                        }
                    }
                }
            }
        }
Пример #42
0
 public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
     .Add("s=|source=",
          "Source - Source location for install. Can include special 'webpi'. Defaults to sources.",
          option => configuration.Sources = option.remove_surrounding_quotes())
     .Add("l|lo|localonly|local-only",
          "LocalOnly - Only search against local machine items.",
          option => configuration.ListCommand.LocalOnly = option != null)
     .Add("pre|prerelease",
          "Prerelease - Include Prereleases? Defaults to false.",
          option => configuration.Prerelease = option != null)
     .Add("i|includeprograms|include-programs",
          "IncludePrograms - Used in conjunction with LocalOnly, filters out apps chocolatey has listed as packages and includes those in the list. Defaults to false.",
          option => configuration.ListCommand.IncludeRegistryPrograms = option != null)
     .Add("a|all|allversions|all-versions",
          "AllVersions - include results from all versions.",
          option => configuration.AllVersions = option != null)
     .Add("version=",
          "Version - Specific version of a package to return.",
          option => configuration.Version = option.remove_surrounding_quotes())
     .Add("u=|user="******"User - used with authenticated feeds. Defaults to empty.",
          option => configuration.SourceCommand.Username = option.remove_surrounding_quotes())
     .Add("p=|password="******"Password - the user's password to the source. Defaults to empty.",
          option => configuration.SourceCommand.Password = option.remove_surrounding_quotes())
     .Add("cert=",
          "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.",
          option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes())
     .Add("cp=|certpassword="******"Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.",
          option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes())
     .Add("page=",
          "Page - the 'page' of results to return. Defaults to return all results. Available in 0.9.10+.",
          option =>
     {
         int page;
         if (int.TryParse(option, out page))
         {
             configuration.ListCommand.Page = page;
         }
         else
         {
             configuration.ListCommand.Page = null;
         }
     })
     .Add("page-size=",
          "Page Size - the amount of package results to return per page. Defaults to 25. Available in 0.9.10+.",
          option => configuration.ListCommand.PageSize = int.Parse(option))
     .Add("e|exact",
          "Exact - Only return packages with this exact name. Available in 0.9.10+.",
          option => configuration.ListCommand.Exact = option != null)
     .Add("by-id-only",
          "ByIdOnly - Only return packages where the id contains the search filter. Available in 0.9.10+.",
          option => configuration.ListCommand.ByIdOnly = option != null)
     .Add("id-starts-with",
          "IdStartsWith - Only return packages where the id starts with the search filter. Available in 0.9.10+.",
          option => configuration.ListCommand.IdStartsWith = option != null)
     .Add("order-by-popularity",
          "OrderByPopularity - Sort by package results by popularity. Available in 0.9.10+.",
          option => configuration.ListCommand.OrderByPopularity = option != null)
     .Add("approved-only",
          "ApprovedOnly - Only return approved packages - this option will filter out results not from the community repository. Available in 0.9.10+.",
          option => configuration.ListCommand.ApprovedOnly = option != null)
     .Add("download-cache|download-cache-only",
          "DownloadCacheAvailable - Only return packages that have a download cache available - this option will filter out results not from the community repository. Available in 0.9.10+.",
          option => configuration.ListCommand.DownloadCacheAvailable = option != null)
     .Add("not-broken",
          "NotBroken - Only return packages that are not failing testing - this option only filters out failing results from the community feed. It will not filter against other sources. Available in 0.9.10+.",
          option => configuration.ListCommand.NotBroken = option != null)
     .Add("detail|detailed",
          "Detailed - Alias for verbose. Available in 0.9.10+.",
          option => configuration.Verbose = option != null)
     ;
 }
Пример #43
0
        public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration config)
        {
            ChocolateyStartupCommand.configureStartupOptions(optionSet);

            optionSet
            .Add("d|debug",
                 "Debug - Show debug messaging.",
                 option => config.Debug = option != null)
            .Add("v|verbose",
                 "Verbose - Show verbose messaging. Very verbose messaging, avoid using under normal circumstances.",
                 option => config.Verbose = option != null)
            .Add("trace",
                 "Trace - Show trace messaging. Very, very verbose trace messaging. Avoid except when needing super low-level .NET Framework debugging. Available in 0.10.4+.",
                 option => config.Trace = option != null)
            .Add("nocolor|no-color",
                 "No Color - Do not show colorization in logging output. This overrides the feature '{0}', set to '{1}'. Available in 0.10.9+.".format_with(ApplicationParameters.Features.LogWithoutColor, config.Features.LogWithoutColor),
                 option => config.Features.LogWithoutColor = option != null)
            .Add("acceptlicense|accept-license",
                 "AcceptLicense - Accept license dialogs automatically. Reserved for future use.",
                 option => config.AcceptLicense = option != null)
            .Add("y|yes|confirm",
                 "Confirm all prompts - Chooses affirmative answer instead of prompting. Implies --accept-license",
                 option =>
            {
                config.PromptForConfirmation = option == null;
                config.AcceptLicense         = option != null;
            })
            .Add("f|force",
                 "Force - force the behavior. Do not use force during normal operation - it subverts some of the smart behavior for commands.",
                 option => config.Force = option != null)
            .Add("noop|whatif|what-if",
                 "NoOp / WhatIf - Don't actually do anything.",
                 option => config.Noop = option != null)
            .Add("r|limitoutput|limit-output",
                 "LimitOutput - Limit the output to essential information",
                 option => config.RegularOutput = option == null)
            .Add("timeout=|execution-timeout=",
                 "CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds. '0' for infinite starting in 0.10.4.".format_with(config.CommandExecutionTimeoutSeconds.to_string()),
                 option =>
            {
                int timeout       = 0;
                var timeoutString = option.remove_surrounding_quotes();
                int.TryParse(timeoutString, out timeout);
                if (timeout > 0 || timeoutString.is_equal_to("0"))
                {
                    config.CommandExecutionTimeoutSeconds = timeout;
                }
            })
            .Add("c=|cache=|cachelocation=|cache-location=",
                 "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
                 option => config.CacheLocation = option.remove_surrounding_quotes())
            .Add("failstderr|failonstderr|fail-on-stderr|fail-on-standard-error|fail-on-error-output",
                 "FailOnStandardError - Fail on standard error output (stderr), typically received when running external commands during install providers. This overrides the feature failOnStandardError.",
                 option => config.Features.FailOnStandardError = option != null)
            .Add("use-system-powershell",
                 "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing. Available in 0.9.10+.",
                 option => config.Features.UsePowerShellHost = option == null)
            .Add("no-progress",
                 "Do Not Show Progress - Do not show download progress percentages. Available in 0.10.4+.",
                 option => config.Features.ShowDownloadProgress = option == null)
            .Add("proxy=",
                 "Proxy Location - Explicit proxy location. Overrides the default proxy location of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.Location),
                 option => config.Proxy.Location = option.remove_surrounding_quotes())
            .Add("proxy-user="******"Proxy User Name - Explicit proxy user (optional). Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy user of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.User),
                 option => config.Proxy.User = option.remove_surrounding_quotes())
            .Add("proxy-password="******"Proxy Password - Explicit proxy password (optional) to be used with username. Requires explicit proxy (`--proxy` or config setting) and user name.  Overrides the default proxy password (encrypted in settings if set). Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.",
                 option => config.Proxy.EncryptedPassword = NugetEncryptionUtility.EncryptString(option.remove_surrounding_quotes()))
            .Add("proxy-bypass-list=",
                 "ProxyBypassList - Comma separated list of regex locations to bypass on proxy. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass list of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassList),
                 option => config.Proxy.BypassList = option.remove_surrounding_quotes())
            .Add("proxy-bypass-on-local",
                 "Proxy Bypass On Local - Bypass proxy for local connections. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass on local setting of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassOnLocal),
                 option => config.Proxy.BypassOnLocal = option != null)
            .Add("log-file=",
                 "Log File to output to in addition to regular loggers. Available in 0.10.8+.",
                 option => config.AdditionalLogFileLocation = option.remove_surrounding_quotes())
            ;
        }
Пример #44
0
 public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
     .Add("s=|source=",
          "Source - The source to find the package(s) to install. Special sources include: ruby, webpi, cygwin, windowsfeatures, and python. Defaults to default feeds.",
          option => configuration.Sources = option.remove_surrounding_quotes())
     .Add("version=",
          "Version - A specific version to install. Defaults to unspecified.",
          option => configuration.Version = option.remove_surrounding_quotes())
     .Add("pre|prerelease",
          "Prerelease - Include Prereleases? Defaults to false.",
          option => configuration.Prerelease = option != null)
     .Add("x86|forcex86",
          "ForceX86 - Force x86 (32bit) installation on 64 bit systems. Defaults to false.",
          option => configuration.ForceX86 = option != null)
     .Add("ia=|installargs=|installarguments=|install-arguments=",
          "InstallArguments - Install Arguments to pass to the native installer in the package. Defaults to unspecified.",
          option => configuration.InstallArguments = option.remove_surrounding_quotes())
     .Add("o|override|overrideargs|overridearguments|override-arguments",
          "OverrideArguments - Should install arguments be used exclusively without appending to current package passed arguments? Defaults to false.",
          option => configuration.OverrideArguments = option != null)
     .Add("notsilent|not-silent",
          "NotSilent - Do not install this silently. Defaults to false.",
          option => configuration.NotSilent = option != null)
     .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=",
          "PackageParameters - Parameters to pass to the package. Defaults to unspecified.",
          option => configuration.PackageParameters = option.remove_surrounding_quotes())
     .Add("argsglobal|args-global|installargsglobal|install-args-global|applyargstodependencies|apply-args-to-dependencies|apply-install-arguments-to-dependencies",
          "Apply Install Arguments To Dependencies  - Should install arguments be applied to dependent packages? Defaults to false.",
          option => configuration.ApplyInstallArgumentsToDependencies = option != null)
     .Add("paramsglobal|params-global|packageparametersglobal|package-parameters-global|applyparamstodependencies|apply-params-to-dependencies|apply-package-parameters-to-dependencies",
          "Apply Package Parameters To Dependencies  - Should package parameters be applied to dependent packages? Defaults to false.",
          option => configuration.ApplyPackageParametersToDependencies = option != null)
     .Add("allowdowngrade|allow-downgrade",
          "AllowDowngrade - Should an attempt at downgrading be allowed? Defaults to false.",
          option => configuration.AllowDowngrade = option != null)
     .Add("m|sxs|sidebyside|side-by-side|allowmultiple|allow-multiple|allowmultipleversions|allow-multiple-versions",
          "AllowMultipleVersions - Should multiple versions of a package be installed? Defaults to false.",
          option => configuration.AllowMultipleVersions = option != null)
     .Add("i|ignoredependencies|ignore-dependencies",
          "IgnoreDependencies - Ignore dependencies when upgrading package(s). Defaults to false.",
          option => configuration.IgnoreDependencies = option != null)
     .Add("n|skippowershell|skip-powershell|skipscripts|skip-scripts|skip-automation-scripts",
          "Skip Powershell - Do not run chocolateyInstall.ps1. Defaults to false.",
          option => configuration.SkipPackageInstallProvider = option != null)
     .Add("failonunfound|fail-on-unfound",
          "Fail On Unfound Packages - If a package is not found in feeds specified, fail instead of warn.",
          option => configuration.UpgradeCommand.FailOnUnfound = option != null)
     .Add("failonnotinstalled|fail-on-not-installed",
          "Fail On Non-installed Packages - If a package is not already intalled, fail instead of installing.",
          option => configuration.UpgradeCommand.FailOnNotInstalled = option != null)
     .Add("u=|user="******"User - used with authenticated feeds. Defaults to empty.",
          option => configuration.SourceCommand.Username = option.remove_surrounding_quotes())
     .Add("p=|password="******"Password - the user's password to the source. Defaults to empty.",
          option => configuration.SourceCommand.Password = option.remove_surrounding_quotes())
     .Add("cert=",
          "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.",
          option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes())
     .Add("cp=|certpassword="******"Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.",
          option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes())
     .Add("ignorechecksum|ignore-checksum|ignorechecksums|ignore-checksums",
          "IgnoreChecksums - Ignore checksums provided by the package. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.9.9+.".format_with(ApplicationParameters.Features.ChecksumFiles, configuration.Features.ChecksumFiles.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.ChecksumFiles = false;
         }
     })
     .Add("allowemptychecksum|allowemptychecksums|allow-empty-checksums",
          "Allow Empty Checksums - Allow packages to have empty/missing checksums for downloaded resources from non-secure locations (HTTP, FTP). Use this switch is not recommended if using sources that download resources from the internet. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.AllowEmptyChecksums = true;
         }
     })
     .Add("allowemptychecksumsecure|allowemptychecksumssecure|allow-empty-checksums-secure",
          "Allow Empty Checksums Secure - Allow packages to have empty checksums for downloaded resources from secure locations (HTTPS). Overrides the default feature '{0}' set to '{1}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.AllowEmptyChecksumsSecure = true;
         }
     })
     .Add("requirechecksum|requirechecksums|require-checksums",
          "Require Checksums - Requires packages to have checksums for downloaded resources (both non-secure and secure). Overrides the default feature '{0}' set to '{1}' and '{2}' set to '{3}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.to_string(), ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.AllowEmptyChecksums       = false;
             configuration.Features.AllowEmptyChecksumsSecure = false;
         }
     })
     .Add("checksum=|downloadchecksum=|download-checksum=",
          "Download Checksum - a user provided checksum for downloaded resources for the package. Overrides the package checksum (if it has one).  Defaults to empty. Available in 0.10.0+.",
          option => configuration.DownloadChecksum = option.remove_surrounding_quotes())
     .Add("checksum64=|checksumx64=|downloadchecksumx64=|download-checksum-x64=",
          "Download Checksum 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Defaults to same as Download Checksum. Available in 0.10.0+.",
          option => configuration.DownloadChecksum64 = option.remove_surrounding_quotes())
     .Add("checksumtype=|checksum-type=|downloadchecksumtype=|download-checksum-type=",
          "Download Checksum Type - a user provided checksum type. Overrides the package checksum type (if it has one). Used in conjunction with Download Checksum. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to 'md5'. Available in 0.10.0+.",
          option => configuration.DownloadChecksumType = option.remove_surrounding_quotes())
     .Add("checksumtype64=|checksumtypex64=|checksum-type-x64=|downloadchecksumtypex64=|download-checksum-type-x64=",
          "Download Checksum Type 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Used in conjunction with Download Checksum 64bit. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to same as Download Checksum Type. Available in 0.10.0+.",
          option => configuration.DownloadChecksumType64 = option.remove_surrounding_quotes())
     .Add("ignorepackagecodes|ignorepackageexitcodes|ignore-package-codes|ignore-package-exit-codes",
          "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.UsePackageExitCodes = false;
         }
     })
     .Add("usepackagecodes|usepackageexitcodes|use-package-codes|use-package-exit-codes",
          "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
          option => configuration.Features.UsePackageExitCodes = option != null
          )
     .Add("except=",
          "Except - a comma-separated list of package names that should not be upgraded when upgrading 'all'. Defaults to empty. Available in 0.9.10+.",
          option => configuration.UpgradeCommand.PackageNamesToSkip = option.remove_surrounding_quotes()
          )
     .Add("stoponfirstfailure|stop-on-first-failure|stop-on-first-package-failure",
          "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.to_string()),
          option => configuration.Features.StopOnFirstPackageFailure = option != null
          )
     .Add("exclude-pre|exclude-prerelease|exclude-prereleases",
          "Exclude Prerelease - Should prerelease be ignored for upgrades? Will be ignored if you pass `--pre`. Available in 0.10.4+.",
          option => configuration.UpgradeCommand.ExcludePrerelease = option != null
          )
     .Add("userememberedargs|userememberedarguments|userememberedoptions|use-remembered-args|use-remembered-arguments|use-remembered-options",
          "Use Remembered Options for Upgrade - use the arguments and options used during install for upgrade. Does not override arguments being passed at runtime. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configuration.Features.UseRememberedArgumentsForUpgrades.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.UseRememberedArgumentsForUpgrades = true;
         }
     })
     .Add("ignorerememberedargs|ignorerememberedarguments|ignorerememberedoptions|ignore-remembered-args|ignore-remembered-arguments|ignore-remembered-options",
          "Ignore Remembered Options for Upgrade - ignore the arguments and options used during install for upgrade. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configuration.Features.UseRememberedArgumentsForUpgrades.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.UseRememberedArgumentsForUpgrades = false;
         }
     })
     ;
 }
Пример #45
0
        public void Invoke(string[] args)
        {
            var options = new OptionSet();

            options.Add(
                "?|help",
                "Show help information.",
                x => HelpUtility.WriteHelpInformation(this, options)
                );

            if (args != null)
            {
                try
                {
                    options.Parse(args);
                }
                catch (OptionException ex)
                {
                    CommandResult.WriteLine(ex.ToString());
                }
            }
            else
            {
                CommandResult.WriteLine(DisplayMode.Inverted, "OMEGA LOCKDOWN ACTIVE");
                CommandResult.WriteLine();
                CommandResult.WriteLine("Welcome agent {0}. I see that you are interested in learning more about the Omega Directive.", CommandResult.CurrentUser.Username);
                CommandResult.WriteLine("We'll begin your briefing from the beginning.");
                CommandResult.WriteLine();
                CommandResult.WriteLine("As an agent of the resistance you already know about exotic matter (XM).");
                CommandResult.WriteLine("What you don't know is that humanity has encountered this matter before the secret French experiments that you've been told about.");
                CommandResult.WriteLine("Exotic matter consists of a group of unknown but powerful particles chemically bonded to form what is known as the Omega Molecule.");
                CommandResult.WriteLine("Strange energetic properties exhibited by Omega resulted in heavy experimentation as scientists believed Omega, if harnessed correctly, could be a virtually unlimited source of energy.");
                CommandResult.WriteLine();
                CommandResult.WriteLine("Unfortunately, Omega proved to be extremely unstable and all attempts to stabalize it were unsuccessful. Not long into the project one of the experimental attempts at stabalization went extremely wrong.");
                CommandResult.WriteLine("In the middle of the experiment several molecules were successfully fused into a stable molecular lattice, but it didn't last long.");
                CommandResult.WriteLine();
                CommandResult.WriteLine(DisplayMode.DontType | DisplayMode.DontWrap | DisplayMode.Parse, "[img]http://omegamolecule.com/content/OmegaLattice.jpg[/img]");
                CommandResult.WriteLine();
                CommandResult.WriteLine("The Omega lattice immediately began to break down causing a chain reaction. The scientists only had a few seconds to enact emergency safety protocols and fill the test chamber with liquid nitrogen, halting the breakdown in mid-cascade.");
                CommandResult.WriteLine("The energy buildup during the last few seconds of the experiment was analyzed vigorously. When the data came back the results were astounding.");
                CommandResult.WriteLine("Just a handful of Omega molecules, if allowed to continue breaking down, would have released an energy equivalent to 1100 times that of an atomic bomb.");
                CommandResult.WriteLine();
                CommandResult.WriteLine("Once the destructive power was revealed it was determined that Omega was too unstable for experimentation and the project was put on permanent hold.");
                CommandResult.WriteLine("The Omega Directive was created to monitor the state of Omega here on Earth and prevent others from experimenting with the molecule.");
                CommandResult.WriteLine("For years nobody else discovered the power of Omega. Several had come close, but never close enough to require intervention, until late last year.");
                CommandResult.WriteLine();
                CommandResult.WriteLine("We have no idea where the first particals of XM began to appear, but it seems the once rare matter is now more abundant on the Earth than we could ever have imagined.");
                CommandResult.WriteLine("XM appears to gather near interesting anomalies known to you as \"portals\". Much to our surprise, these portals appear to be stable structures of Omega Molecules.");
                CommandResult.WriteLine("Needless to say, when we first discovered the properties of these portals we were extremely alarmed and we have since initiated a code blue Omega lockdown as per article 21 subsection D of the Omega Directive.");
                CommandResult.WriteLine("This lockdown forbids us from sharing information about Omega for fear that it could fall into the wrong hands. We must continue to operate in secrecy to protect our race.");
                CommandResult.WriteLine();
                CommandResult.WriteLine("During the lockdown we have continued analyzing these new anomalies to gain a better understanding of the phenomenon. Most members of the Omega Directive have arrived at a consensus that it is highly implausible for these anomalies consisting of stable Omega Molecules to be a natural occurance.");
                CommandResult.WriteLine("Only an intelligence with an extensive understanding of Omega would be able to create so many stable structures. Many have theorized that if enough of these stable anomalies remain within this unkown intelligence's control they could be linked together to form a \"super lattice\". Such a structure would be capable of crossing dimensional barriers that we never imagined existed, let alone that we could cross.");
                CommandResult.WriteLine("As XM particles continue to accumulate around the globe we are becoming increasingly concerned and we must do everything we can to stop it.");
                CommandResult.WriteLine();
                CommandResult.WriteLine("Omega is extremely difficult to erradicate safely. Fortunately for now the stabalization process used on XM particles to form stable Omega structures appears to be practically flawless. Though we are still concerned about the dangers we believe we are relatively safe for the time being.");
                CommandResult.WriteLine("Since we cannot yet safely erradicate the exotic particles from our planet we have taken to doing the next best thing, and that is embracing the Niantic Project. We are still corroborating claims made by Niantic about an alien race known only as \"Shapers\", but the technology developed by Niantic does appear to have the ability to safely manipulate XM particles and stable Omega structures.");
                CommandResult.WriteLine("As an agent of the resistance you already know how to use this technology and we encourage you to continue to do so. However, as part of the Omega Directive we require that you cooperate with fellow Omega agents only for any serious task. Until an agent is a verified member of Omega you have every reason to distrust them, even if they claim to be part of the resistance.");
                CommandResult.WriteLine();
                CommandResult.WriteLine("We are glad to have you as a verified Omega agent, {0}. We hope you will help us keep as many stable structures out of enemy hands as possible. For now, it is our only defense.", CommandResult.CurrentUser.Username);
            }
        }
Пример #46
0
        static int Main(string[] args)
        {
            LogHelper.LogAdapter = new ConsoleLogAdapter();

            int    retCode         = 0;
            string data            = null;
            string error           = null;
            int    sleepms         = 0;
            var    p               = new OptionSet();
            var    readInputToEof  = false;
            var    lines           = new List <string>();
            bool   runWebServer    = false;
            NPath  outfile         = NPath.Default;
            NPath  path            = NPath.Default;
            string releaseNotes    = null;
            int    webServerPort   = -1;
            bool   generateVersion = false;
            bool   generatePackage = false;
            string version         = null;
            string url             = null;
            string readVersion     = null;
            string msg             = null;


            p = p
                .Add("r=", (int v) => retCode                  = v)
                .Add("d=|data=", v => data                     = v)
                .Add("e=|error=", v => error                   = v)
                .Add("f=|file=", v => data                     = File.ReadAllText(v))
                .Add("ef=|errorFile=", v => error              = File.ReadAllText(v))
                .Add("s=|sleep=", (int v) => sleepms           = v)
                .Add("i|input", v => readInputToEof            = true)
                .Add("w|web", v => runWebServer                = true)
                .Add("port=", (int v) => webServerPort         = v)
                .Add("g|generateVersion", v => generateVersion = true)
                .Add("v=|version=", v => version               = v)
                .Add("p|gen-package", "Pass --version --url --path --md5 --rn --msg to generate a package", v => generatePackage = true)
                .Add("u=|url=", v => url = v)
                .Add("path=", v => path  = v.ToNPath())
                .Add("rn=", "Path to file with release notes", v => releaseNotes = v.ReadAllTextIfFileExists())
                .Add("msg=", "Path to file with message for package", v => msg   = v.ReadAllTextIfFileExists())
                .Add("readVersion=", v => readVersion = v)
                .Add("o=|outfile=", v => outfile      = v.ToNPath().MakeAbsolute())
                .Add("h|help", v => p.WriteOptionDescriptions(Console.Out));

            p.Parse(args);

            if (generatePackage)
            {
                var md5 = path.CalculateMD5();
                url += "/" + path.FileName;
                var package = new Package
                {
                    Message         = msg,
                    Md5             = md5,
                    ReleaseNotes    = releaseNotes,
                    ReleaseNotesUrl = null,
                    Url             = url,
                    Version         = TheVersion.Parse(version),
                };

                var json = package.ToJson(lowerCase: true, onlyPublic: false);
                if (outfile.IsInitialized)
                {
                    outfile.WriteAllText(json);
                }
                else
                {
                    Logger.Info(json);
                }
                return(0);
            }

            if (readVersion != null)
            {
                var json    = File.ReadAllText(readVersion);
                var package = json.FromJson <Package>(lowerCase: true, onlyPublic: false);
                Console.WriteLine(package);
                Console.WriteLine($"{package.Url} {package.Version}");
                return(0);
            }

            if (generateVersion)
            {
                Logger.Error($"Generating version json {version} to {(outfile.IsInitialized ? outfile : "console")}");
                var vv = TheVersion.Parse(version);
                url += $"/unity/releases/github-for-unity-{version}.unitypackage";
                var package = new Package {
                    Url = url, Version = vv
                };
                var json = package.ToJson(lowerCase: true, onlyPublic: false);
                if (outfile.IsInitialized)
                {
                    outfile.WriteAllText(json);
                }
                else
                {
                    Logger.Info(json);
                }
                return(0);
            }

            if (runWebServer)
            {
                if (webServerPort < 0)
                {
                    webServerPort = 50000;
                }
                RunWebServer(outfile, webServerPort);
                return(0);
            }

            if (readInputToEof)
            {
                string line;
                while ((line = Console.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }

            if (sleepms > 0)
            {
                Thread.Sleep(sleepms);
            }

            if (!String.IsNullOrEmpty(data))
            {
                Console.WriteLine(data);
            }
            else if (readInputToEof)
            {
                Console.WriteLine(String.Join(Environment.NewLine, lines.ToArray()));
            }

            if (!String.IsNullOrEmpty(error))
            {
                Console.Error.WriteLine(error);
            }

            return(retCode);
        }
Пример #47
0
        static void Main(string[] args)
        {
            string file         = null;
            bool   wait         = false;
            bool   help         = false;
            bool   parallel     = false;
            bool   experimental = false;

            TraceExtensions.DumpStyle style = TraceExtensions.DumpStyle.None;
            var options = new OptionSet()
            {
                { "h|help", "show this help message", v => help = true },
                { "p|parallel", "use parallel parsing(will parse into list only)", v => parallel = true },
                { "w|wait", "wait for keyboard input before terminating", v => wait = true },
                { "e|experimental", "enable some experimental stuff", v => experimental = true },
                //{ "1",              "dump trace as minimal list", v => style = TraceExtensions.DumpStyle.Minimal },
                //{ "2",              "dump trace as minimal human-readable list", v => style = TraceExtensions.DumpStyle.HumanReadableMinimal },
                //{ "3",              "dump trace as human readable list", v => style = TraceExtensions.DumpStyle.HumanReadable },
            };
            int index = 0;
            Func <int, Action <string> > styleSetter = idx => (v) => style = (TraceExtensions.DumpStyle)idx;

            foreach (var ds in Enum.GetNames(typeof(TraceExtensions.DumpStyle)))
            {
                options.Add(index.ToString(), ds, styleSetter(index));
                index++;
            }

            var extra = options.Parse(args);

            if (help)
            {
                WriteHelp(options);
                return;
            }

            if (extra.Count == 0)
            {
                WriteHelp(options);
                Environment.Exit(1);
            }
            else
            {
                file = extra[0];
            }

            if (!File.Exists(file))
            {
                Cout.WriteLine($"File {file} does not exist!");
                Environment.Exit(1);
            }

            Cout.WriteLine($"Processing: {file} using modes: basic{(parallel ? ",parallel" : "")}{(experimental ? ",experimental" : "")}");

            try
            {
                var parserOptions = new ParserOptions {
                    Parallel = parallel, Experimental = experimental
                };
                var parser = Parser.FromFile(file, parserOptions);
                Cout.WriteLine(parser.GetInfo());
                var result = parser.Parse();
                Cout.WriteLine("Parsing is done. Took this long: " + result.ParseDuration);
                Cout.WriteLine();
                if (style != TraceExtensions.DumpStyle.None)
                {
                    Cout.WriteLine("Dumping parsed trace tree in the following style:" + style.ToString());
                    if (wait)
                    {
                        Cout.WriteLine("Last chance to Ctrl-C!");
                        Cout.ReadKey();
                    }
                    if (result is TraceList list)
                    {
                        DumpList(list, style);
                    }
                    else if (result is TraceTree tree)
                    {
                        DumpTree(new ITrace[] { tree.RootTrace }, style);
                    }
                }
            }
            catch (Exception ex)
            {
                Cout.WriteLine("Error: " + ex.Message);
            }
            if (wait)
            {
                Cout.ReadKey();
            }
        }
Пример #48
0
        /// <summary>
        ///   Parses arguments and updates the configuration
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <param name="configuration">The configuration</param>
        /// <param name="setOptions">The set options.</param>
        /// <param name="afterParse">Actions to take after parsing</param>
        /// <param name="validateConfiguration">Validate the configuration</param>
        /// <param name="helpMessage">The help message.</param>
        public static void parse_arguments_and_update_configuration(ICollection <string> args,
                                                                    ChocolateyConfiguration configuration,
                                                                    Action <OptionSet> setOptions,
                                                                    Action <IList <string> > afterParse,
                                                                    Action validateConfiguration,
                                                                    Action helpMessage)
        {
            IList <string> unparsedArguments = new List <string>();

            // add help only once
            if (_optionSet.Count == 0)
            {
                _optionSet
                .Add("?|help|h",
                     "Prints out the help menu.",
                     option => configuration.HelpRequested = option != null);
            }

            if (setOptions != null)
            {
                setOptions(_optionSet);
            }

            try
            {
                unparsedArguments = _optionSet.Parse(args);
            }
            catch (OptionException)
            {
                show_help(_optionSet, helpMessage);
            }

            // the command argument
            if (string.IsNullOrWhiteSpace(configuration.CommandName) && unparsedArguments.Contains(args.FirstOrDefault()))
            {
                var commandName = args.FirstOrDefault();
                if (!Regex.IsMatch(commandName, @"^[-\/+]"))
                {
                    configuration.CommandName = commandName;
                }
                else
                {
                    configuration.HelpRequested = true;
                }
            }

            if (afterParse != null)
            {
                afterParse(unparsedArguments);
            }

            if (configuration.HelpRequested)
            {
                show_help(_optionSet, helpMessage);
            }
            else
            {
                if (validateConfiguration != null)
                {
                    validateConfiguration();
                }
            }
        }
Пример #49
0
 protected override OptionSet Add(OptionSet options, string prototype, string description, OptionCallback callback)
 => options.Add(prototype, description, callback);
Пример #50
0
        public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
        {
            optionSet
            .Add("s=|source=",
                 "Source - The source to find the package(s) to install. Special sources include: ruby, webpi, cygwin, windowsfeatures, and python. Defaults to default feeds.",
                 option => configuration.Sources = option.remove_surrounding_quotes())
            .Add("version=",
                 "Version - A specific version to install. Defaults to unspecified.",
                 option => configuration.Version = option.remove_surrounding_quotes())
            .Add("pre|prerelease",
                 "Prerelease - Include Prereleases? Defaults to false.",
                 option => configuration.Prerelease = option != null)
            .Add("x86|forcex86",
                 "ForceX86 - Force x86 (32bit) installation on 64 bit systems. Defaults to false.",
                 option => configuration.ForceX86 = option != null)
            .Add("ia=|installargs=|installarguments=|install-arguments=",
                 "InstallArguments - Install Arguments to pass to the native installer in the package. Defaults to unspecified.",
                 option => configuration.InstallArguments = option.remove_surrounding_quotes())
            .Add("o|override|overrideargs|overridearguments|override-arguments",
                 "OverrideArguments - Should install arguments be used exclusively without appending to current package passed arguments? Defaults to false.",
                 option => configuration.OverrideArguments = option != null)
            .Add("notsilent|not-silent",
                 "NotSilent - Do not install this silently. Defaults to false.",
                 option => configuration.NotSilent = option != null)
            .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=",
                 "PackageParameters - Parameters to pass to the package. Defaults to unspecified.",
                 option => configuration.PackageParameters = option.remove_surrounding_quotes())
            .Add("allowdowngrade|allow-downgrade",
                 "AllowDowngrade - Should an attempt at downgrading be allowed? Defaults to false.",
                 option => configuration.AllowDowngrade = option != null)
            .Add("m|sxs|sidebyside|side-by-side|allowmultiple|allow-multiple|allowmultipleversions|allow-multiple-versions",
                 "AllowMultipleVersions - Should multiple versions of a package be installed? Defaults to false.",
                 option => configuration.AllowMultipleVersions = option != null)
            .Add("i|ignoredependencies|ignore-dependencies",
                 "IgnoreDependencies - Ignore dependencies when upgrading package(s). Defaults to false.",
                 option => configuration.IgnoreDependencies = option != null)
            .Add("n|skippowershell|skip-powershell|skipscripts|skip-scripts|skip-automation-scripts",
                 "Skip Powershell - Do not run chocolateyInstall.ps1. Defaults to false.",
                 option => configuration.SkipPackageInstallProvider = option != null)
            .Add("failonunfound|fail-on-unfound",
                 "Fail On Unfound Packages - If a package is not found in feeds specified, fail instead of warn.",
                 option => configuration.UpgradeCommand.FailOnUnfound = option != null)
            .Add("failonnotinstalled|fail-on-not-installed",
                 "Fail On Non-installed Packages - If a package is not already intalled, fail instead of installing.",
                 option => configuration.UpgradeCommand.FailOnNotInstalled = option != null)
            .Add("u=|user="******"User - used with authenticated feeds. Defaults to empty.",
                 option => configuration.SourceCommand.Username = option.remove_surrounding_quotes())
            .Add("p=|password="******"Password - the user's password to the source. Defaults to empty.",
                 option => configuration.SourceCommand.Password = option.remove_surrounding_quotes())

            .Add("cert=",
                 "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.",
                 option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes())
            .Add("cp=|certpassword="******"Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.",
                 option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes())
            .Add("ignorechecksum|ignore-checksum|ignorechecksums|ignore-checksums",
                 "IgnoreChecksums - Ignore checksums provided by the package. Available in 0.9.9.9+.",
                 option =>
            {
                if (option != null)
                {
                    configuration.Features.CheckSumFiles = false;
                }
            })
            .Add("ignorepackagecodes|ignorepackageexitcodes|ignore-package-codes|ignore-package-exit-codes",
                 "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
                 option =>
            {
                if (option != null)
                {
                    configuration.Features.UsePackageExitCodes = false;
                }
            })
            .Add("usepackagecodes|usepackageexitcodes|use-package-codes|use-package-exit-codes",
                 "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
                 option => configuration.Features.UsePackageExitCodes = option != null
                 )
            .Add("except=",
                 "Except - a comma-separated list of package names that should not be upgraded when upgrading 'all'. Defaults to empty. Available in 0.9.10+.",
                 option => configuration.UpgradeCommand.PackageNamesToSkip = option.remove_surrounding_quotes())
            ;
        }
Пример #51
0
 public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
     .Add("s=|source=",
          "Source - The source to find the package(s) to install. Special sources include: ruby, webpi, cygwin, windowsfeatures, and python. Defaults to default feeds.",
          option => configuration.Sources = option)
     .Add("version=",
          "Version - A specific version to uninstall. Defaults to unspecified.",
          option => configuration.Version = option.remove_surrounding_quotes())
     .Add("a|allversions|all-versions",
          "AllVersions - Uninstall all versions? Defaults to false.",
          option => configuration.AllVersions = option != null)
     .Add("ua=|uninstallargs=|uninstallarguments=|uninstall-arguments=",
          "UninstallArguments - Uninstall Arguments to pass to the native installer in the package. Defaults to unspecified.",
          option => configuration.InstallArguments = option.remove_surrounding_quotes())
     .Add("o|override|overrideargs|overridearguments|override-arguments",
          "OverrideArguments - Should uninstall arguments be used exclusively without appending to current package passed arguments? Defaults to false.",
          option => configuration.OverrideArguments = option != null)
     .Add("notsilent|not-silent",
          "NotSilent - Do not uninstall this silently. Defaults to false.",
          option => configuration.NotSilent = option != null)
     .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=",
          "PackageParameters - Parameters to pass to the package. Defaults to unspecified.",
          option => configuration.PackageParameters = option.remove_surrounding_quotes())
     .Add("argsglobal|args-global|installargsglobal|install-args-global|applyargstodependencies|apply-args-to-dependencies|apply-install-arguments-to-dependencies",
          "Apply Install Arguments To Dependencies  - Should install arguments be applied to dependent packages? Defaults to false.",
          option => configuration.ApplyInstallArgumentsToDependencies = option != null)
     .Add("paramsglobal|params-global|packageparametersglobal|package-parameters-global|applyparamstodependencies|apply-params-to-dependencies|apply-package-parameters-to-dependencies",
          "Apply Package Parameters To Dependencies  - Should package parameters be applied to dependent packages? Defaults to false.",
          option => configuration.ApplyPackageParametersToDependencies = option != null)
     .Add("m|sxs|sidebyside|side-by-side|allowmultiple|allow-multiple|allowmultipleversions|allow-multiple-versions",
          "AllowMultipleVersions - Should multiple versions of a package be installed? Defaults to false.",
          option => configuration.AllowMultipleVersions = option != null)
     .Add("x|forcedependencies|force-dependencies|removedependencies|remove-dependencies",
          "RemoveDependencies - Uninstall dependencies when uninstalling package(s). Defaults to false.",
          option => configuration.ForceDependencies = option != null)
     .Add("n|skippowershell|skip-powershell|skipscripts|skip-scripts|skip-automation-scripts",
          "Skip Powershell - Do not run chocolateyUninstall.ps1. Defaults to false.",
          option => configuration.SkipPackageInstallProvider = option != null)
     .Add("ignorepackagecodes|ignorepackageexitcodes|ignore-package-codes|ignore-package-exit-codes",
          "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.UsePackageExitCodes = false;
         }
     })
     .Add("usepackagecodes|usepackageexitcodes|use-package-codes|use-package-exit-codes",
          "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
          option => configuration.Features.UsePackageExitCodes = option != null
          )
     .Add("autouninstaller|use-autouninstaller",
          "UseAutoUninstaller - Use auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.to_string()),
          option => configuration.Features.AutoUninstaller = option != null
          )
     .Add("skipautouninstaller|skip-autouninstaller",
          "SkipAutoUninstaller - Skip auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.AutoUninstaller = false;
         }
     })
     .Add("failonautouninstaller|fail-on-autouninstaller",
          "FailOnAutoUninstaller - Fail the package uninstall if the auto uninstaller reports and error. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.to_string()),
          option => configuration.Features.FailOnAutoUninstaller = option != null
          )
     .Add("ignoreautouninstallerfailure|ignore-autouninstaller-failure",
          "Ignore Auto Uninstaller Failure - Do not fail the package if auto uninstaller reports an error. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.FailOnAutoUninstaller = false;
         }
     })
     .Add("stoponfirstfailure|stop-on-first-failure|stop-on-first-package-failure",
          "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.to_string()),
          option => configuration.Features.StopOnFirstPackageFailure = option != null
          )
     ;
 }
        /// <summary>
        /// Save inventory to a file archive
        /// </summary>
        /// <param name="cmdparams"></param>
        protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
        {
            Guid id = Guid.NewGuid();

            Dictionary <string, object> options = new Dictionary <string, object>();

            OptionSet ops = new OptionSet();

            //ops.Add("v|version=", delegate(string v) { options["version"] = v; });
            ops.Add("h|home=", delegate(string v) { options["home"] = v; });
            ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; });
            ops.Add("c|creators", delegate(string v) { options["creators"] = v; });
            ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
            ops.Add("e|exclude=", delegate(string v)
            {
                if (!options.ContainsKey("exclude"))
                {
                    options["exclude"] = new List <String>();
                }
                ((List <String>)options["exclude"]).Add(v);
            });
            ops.Add("f|excludefolder=", delegate(string v)
            {
                if (!options.ContainsKey("excludefolders"))
                {
                    options["excludefolders"] = new List <String>();
                }
                ((List <String>)options["excludefolders"]).Add(v);
            });

            List <string> mainParams = ops.Parse(cmdparams);

            try
            {
                if (mainParams.Count < 6)
                {
                    m_log.Error(
                        "[INVENTORY ARCHIVER]: save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]");
                    return;
                }

                if (options.ContainsKey("home"))
                {
                    m_log.WarnFormat("[INVENTORY ARCHIVER]: Please be aware that inventory archives with creator information are not compatible with OpenSim 0.7.0.2 and earlier.  Do not use the -home option if you want to produce a compatible IAR");
                }

                string firstName = mainParams[2];
                string lastName  = mainParams[3];
                string invPath   = mainParams[4];
                string pass      = mainParams[5];
                string savePath  = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);

                m_log.InfoFormat(
                    "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
                    savePath, invPath, firstName, lastName);

                lock (m_pendingConsoleSaves)
                    m_pendingConsoleSaves.Add(id);

                ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options);
            }
            catch (InventoryArchiverException e)
            {
                m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
            }
        }
Пример #53
0
    private static async Task RunAsync(string[] args)
    {
        var builder = Host.CreateDefaultBuilder(args)
                      .ConfigureServices((_, services) => ConfigureServices(services))
                      .Build();

        var commands = builder.Services.GetRequiredService <IEnumerable <Command> >();

        var commandName = args.FirstOrDefault();

        if (commandName is null ||
            commandName is "-?" or "-h" or "--help")
        {
            var appName = Path.GetFileNameWithoutExtension(Environment.ProcessPath);
            Console.Error.WriteLine($"usage: {appName} <command> [OPTIONS]+");
            Console.Error.WriteLine();

            foreach (var c in commands)
            {
                Console.Error.WriteLine($"  {c.Name,-25}{c.Description}");
            }

            return;
        }

        var command = commands.SingleOrDefault(c => c.Name == commandName);

        if (command is null)
        {
            Console.Error.WriteLine($"error: undefined command '{commandName}'");
            return;
        }

        var help = false;

        var options = new OptionSet();

        command.AddOptions(options);
        options.Add("?|h|help", null, _ => help = true, true);

        try
        {
            var unprocessed = options.Parse(args.Skip(1));

            if (help)
            {
                var appName = Path.GetFileNameWithoutExtension(Environment.ProcessPath);
                Console.Error.WriteLine(command.Description);
                Console.Error.WriteLine($"usage: {appName} {command.Name} [OPTIONS]+");
                options.WriteOptionDescriptions(Console.Error);
                return;
            }

            if (unprocessed.Any())
            {
                foreach (var option in unprocessed)
                {
                    Console.Error.WriteLine($"error: unrecognized argument {option}");
                }
                return;
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.Message);
            return;
        }

        await command.ExecuteAsync();
    }
Пример #54
0
        static void CopyAction(string action, IEnumerable <string> args)
        {
            var sourceFormat      = "";
            var destinationFormat = "";
            var parameters        = new List <string>();
            var parser            = new OptionSet()
            {
                { "source-format=", _("Source format (valid values: auto, db4o, sqlite)"),
                  val => {
                      if (val == "auto")
                      {
                          val = "";
                      }
                      sourceFormat = val;
                  } },
                { "destination-format=", _("Destination format (valid values: auto, db4o, sqlite)"),
                  val => {
                      if (val == "auto")
                      {
                          val = "";
                      }
                      destinationFormat = val;
                  } },
                { "<>",
                  val => {
                      if (!val.StartsWith("-"))
                      {
                          parameters.Add(val);
                          return;
                      }
                      throw new OptionException(
                                String.Format(_("Unknown {0} option: '{1}'"),
                                              action, val),
                                val
                                );
                  } }
            };

            parser.Add("h|help", _("Show this help"),
                       val => {
                Console.WriteLine(
                    String.Format(
                        _("Usage: smuxi-message-buffer {0} [action-options] source_db(s)... destination_db"),
                        action
                        )
                    );
                Console.WriteLine();
                Console.WriteLine("  source_db(s)... " + _("Source file path(s)"));
                Console.WriteLine("  destination_db " + _("Destination file path or -/empty for stdout"));
                Console.WriteLine();
                Console.WriteLine(_("Options:"));
                parser.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
                       );

            parser.Parse(args);
            if (parameters.Count < 2)
            {
                throw new OptionException(
                          _("source_db and destination_db are required"),
                          action
                          );
            }
            var sourceFiles     = parameters.Take(parameters.Count - 1).ToArray();
            var destinationFile = parameters.Last();

            if (destinationFile == "-")
            {
                destinationFile = "";
            }
            Copy(sourceFiles, sourceFormat, destinationFile, destinationFormat);
        }
Пример #55
0
 public Command()
 {
     _optionSet = new OptionSet();
     _optionSet.Add("h|help", "Show command help", x => _helpCommand = true);
 }
        /// <summary>
        /// Load a whole region from an opensimulator archive.
        /// </summary>
        /// <param name="cmdparams"></param>
        public void HandleLoadOarConsoleCommand(string module, string[] cmdparams)
        {
            bool    mergeOar       = false;
            bool    skipAssets     = false;
            bool    forceTerrain   = false;
            bool    forceParcels   = false;
            bool    noObjects      = false;
            Vector3 displacement   = new Vector3(0f, 0f, 0f);
            float   rotation       = 0f;
            Vector3 rotationCenter = new Vector3(Constants.RegionSize / 2f, Constants.RegionSize / 2f, 0);

            OptionSet options = new OptionSet();

            options.Add("m|merge", delegate(string v) { mergeOar = (v != null); });
            options.Add("s|skip-assets", delegate(string v) { skipAssets = (v != null); });
            options.Add("force-terrain", delegate(string v) { forceTerrain = (v != null); });
            options.Add("forceterrain", delegate(string v) { forceTerrain = (v != null); });   // downward compatibility
            options.Add("force-parcels", delegate(string v) { forceParcels = (v != null); });
            options.Add("forceparcels", delegate(string v) { forceParcels = (v != null); });   // downward compatibility
            options.Add("no-objects", delegate(string v) { noObjects = (v != null); });
            options.Add("displacement=", delegate(string v)
            {
                try
                {
                    displacement = v == null ? Vector3.Zero : Vector3.Parse(v);
                }
                catch
                {
                    m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing displacement");
                    m_log.ErrorFormat("[ARCHIVER MODULE]    Must be represented as vector3: --displacement \"<128,128,0>\"");
                    return;
                }
            });
            options.Add("rotation=", delegate(string v)
            {
                try
                {
                    rotation = v == null ? 0f : float.Parse(v);
                }
                catch
                {
                    m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation");
                    m_log.ErrorFormat("[ARCHIVER MODULE]    Must be an angle in degrees between -360 and +360: --rotation 45");
                    return;
                }
                // Convert to radians for internals
                rotation = Util.Clamp <float>(rotation, -359f, 359f) / 180f * (float)Math.PI;
            });
            options.Add("rotation-center=", delegate(string v)
            {
                try
                {
                    rotationCenter = v == null ? Vector3.Zero : Vector3.Parse(v);
                }
                catch
                {
                    m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation displacement");
                    m_log.ErrorFormat("[ARCHIVER MODULE]    Must be represented as vector3: --rotation-center \"<128,128,0>\"");
                    return;
                }
            });

            // Send a message to the region ready module

            /* bluewall* Disable this for the time being
             * IRegionReadyModule rready = m_scene.RequestModuleInterface<IRegionReadyModule>();
             *
             * if (rready != null)
             * {
             *  rready.OarLoadingAlert("load");
             * }
             */

            List <string> mainParams = options.Parse(cmdparams);

            //            m_log.DebugFormat("MERGE OAR IS [{0}]", mergeOar);
            //
            //            foreach (string param in mainParams)
            //                m_log.DebugFormat("GOT PARAM [{0}]", param);

            Dictionary <string, object> archiveOptions = new Dictionary <string, object>();

            if (mergeOar)
            {
                archiveOptions.Add("merge", null);
            }
            if (skipAssets)
            {
                archiveOptions.Add("skipAssets", null);
            }
            if (forceTerrain)
            {
                archiveOptions.Add("force-terrain", null);
            }
            if (forceParcels)
            {
                archiveOptions.Add("force-parcels", null);
            }
            if (noObjects)
            {
                archiveOptions.Add("no-objects", null);
            }
            archiveOptions.Add("displacement", displacement);
            archiveOptions.Add("rotation", rotation);
            archiveOptions.Add("rotation-center", rotationCenter);

            if (mainParams.Count > 2)
            {
                DearchiveRegion(mainParams[2], Guid.Empty, archiveOptions);
            }
            else
            {
                DearchiveRegion(DEFAULT_OAR_BACKUP_FILENAME, Guid.Empty, archiveOptions);
            }
        }
Пример #57
0
        private static void AddWebGLGlobeJsonOptions(OptionSet optionSet, ConversionOptions options)
        {
            const string heightScalarParamDesc = "A scale factor for the height component of each coordinate.  Defaults to 1.";

            optionSet.Add("webGLGlobeJsonHeightScalar=", heightScalarParamDesc, (double v) => options.WebGLGlobeJson.HeightScalar = v);
        }
Пример #58
0
 public void UpdateOptions(OptionSet options)
 {
     options.Add("azure", "Enables deploy to azure support", v => performAzureWorkaround = (v != null));
 }
Пример #59
0
        private Program()
        {
            var databaseOptions = smugglerApi.Options;
            var filesOptions    = smugglerFilesApi.Options;

            selectionDispatching = new OptionSet();
            selectionDispatching.Add("d|d2|database|database2:", OptionCategory.None, string.Empty, value =>
            {
                if (mode == SmugglerMode.Unknown || mode == SmugglerMode.Database)
                {
                    mode = SmugglerMode.Database;
                }
                else
                {
                    PrintUsageAndExit(new ArgumentException("Database and Filesystem parameters are mixed. You cannot use both in the same request."));
                }
            });
            selectionDispatching.Add("f|f2|filesystem|filesystem2:", OptionCategory.None, string.Empty, value =>
            {
                if (mode == SmugglerMode.Unknown || mode == SmugglerMode.Filesystem)
                {
                    mode = SmugglerMode.Filesystem;
                }
                else
                {
                    PrintUsageAndExit(new ArgumentException("Database and Filesystem parameters are mixed. You cannot use both in the same request."));
                }
            });

            databaseOptionSet = new OptionSet();
            databaseOptionSet.Add("operate-on-types:", OptionCategory.SmugglerDatabase, "Specify the types to operate on. Specify the types to operate on. You can specify more than one type by combining items with a comma." + Environment.NewLine +
                                  "Default is all items." + Environment.NewLine +
                                  "Usage example: Indexes,Documents,Attachments", value =>
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(value) == false)
                    {
                        databaseOptions.OperateOnTypes = (ItemType)Enum.Parse(typeof(ItemType), value, ignoreCase: true);
                    }
                }
                catch (Exception e)
                {
                    PrintUsageAndExit(e);
                }
            });
            databaseOptionSet.Add("metadata-filter:{=}", OptionCategory.SmugglerDatabase, "Filter documents by a metadata property." + Environment.NewLine +
                                  "Usage example: Raven-Entity-Name=Posts, or Raven-Entity-Name=Posts,Persons for multiple document types", (key, val) => databaseOptions.Filters.Add(new FilterSetting
            {
                Path        = "@metadata." + key,
                ShouldMatch = true,
                Values      = FilterSetting.ParseValues(val)
            }));
            databaseOptionSet.Add("negative-metadata-filter:{=}", OptionCategory.SmugglerDatabase, "Filter documents NOT matching a metadata property." + Environment.NewLine +
                                  "Usage example: Raven-Entity-Name=Posts", (key, val) => databaseOptions.Filters.Add(
                                      new FilterSetting
            {
                Path        = "@metadata." + key,
                ShouldMatch = false,
                Values      = FilterSetting.ParseValues(val)
            }));
            databaseOptionSet.Add("filter:{=}", OptionCategory.SmugglerDatabase, "Filter documents by a document property" + Environment.NewLine +
                                  "Usage example: Property-Name=Value", (key, val) => databaseOptions.Filters.Add(
                                      new FilterSetting
            {
                Path        = key,
                ShouldMatch = true,
                Values      = FilterSetting.ParseValues(val)
            }));
            databaseOptionSet.Add("negative-filter:{=}", OptionCategory.SmugglerDatabase, "Filter documents NOT matching a document property" + Environment.NewLine +
                                  "Usage example: Property-Name=Value", (key, val) => databaseOptions.Filters.Add(
                                      new FilterSetting
            {
                Path        = key,
                ShouldMatch = false,
                Values      = FilterSetting.ParseValues(val)
            }));
            databaseOptionSet.Add("transform:", OptionCategory.SmugglerDatabase, "Transform documents using a given script (import only)", script => databaseOptions.TransformScript           = script);
            databaseOptionSet.Add("transform-file:", OptionCategory.SmugglerDatabase, "Transform documents using a given script file (import only)", script => databaseOptions.TransformScript = File.ReadAllText(script));
            databaseOptionSet.Add("max-steps-for-transform-script:", OptionCategory.SmugglerDatabase, "Maximum number of steps that transform script can have (import only)", s => databaseOptions.MaxStepsForTransformScript = int.Parse(s));
            databaseOptionSet.Add("batch-size:", OptionCategory.SmugglerDatabase, "The batch size for requests", s => databaseOptions.BatchSize = int.Parse(s));
            databaseOptionSet.Add("chunk-size:", OptionCategory.SmugglerDatabase, "The number of documents to import before new connection will be opened", s => databaseOptions.ChunkSize = int.Parse(s));
            databaseOptionSet.Add("d|database:", OptionCategory.SmugglerDatabase, "The database to operate on. If no specified, the operations will be on the default database.", value => databaseOptions.Source.DefaultDatabase = value);
            databaseOptionSet.Add("d2|database2:", OptionCategory.SmugglerDatabase, "The database to export to. If no specified, the operations will be on the default database. This parameter is used only in the between operation.", value => databaseOptions.Destination.DefaultDatabase = value);
            databaseOptionSet.Add("wait-for-indexing", OptionCategory.SmugglerDatabase, "Wait until all indexing activity has been completed (import only)", _ => databaseOptions.WaitForIndexing = true);
            databaseOptionSet.Add("excludeexpired", OptionCategory.SmugglerDatabase, "Excludes expired documents created by the expiration bundle", _ => databaseOptions.ShouldExcludeExpired     = true);
            databaseOptionSet.Add("limit:", OptionCategory.SmugglerDatabase, "Reads at most VALUE documents/attachments.", s => databaseOptions.Limit        = int.Parse(s));
            databaseOptionSet.Add("timeout:", OptionCategory.SmugglerDatabase, "The timeout to use for requests", s => databaseOptions.Timeout               = TimeSpan.FromMilliseconds(int.Parse(s)));
            databaseOptionSet.Add("incremental", OptionCategory.SmugglerDatabase, "States usage of incremental operations", _ => databaseOptions.Incremental = true);
            databaseOptionSet.Add("u|user|username:"******"The username to use when the database requires the client to authenticate.", value => GetCredentials(databaseOptions.Source).UserName = value);
            databaseOptionSet.Add("u2|user2|username2:", OptionCategory.SmugglerDatabase, "The username to use when the database requires the client to authenticate. This parameter is used only in the between operation.", value => GetCredentials(databaseOptions.Destination).UserName = value);
            databaseOptionSet.Add("p|pass|password:"******"The password to use when the database requires the client to authenticate.", value => GetCredentials(databaseOptions.Source).Password = value);
            databaseOptionSet.Add("p2|pass2|password2:", OptionCategory.SmugglerDatabase, "The password to use when the database requires the client to authenticate. This parameter is used only in the between operation.", value => GetCredentials(databaseOptions.Destination).Password = value);
            databaseOptionSet.Add("domain:", OptionCategory.SmugglerDatabase, "The domain to use when the database requires the client to authenticate.", value => GetCredentials(databaseOptions.Source).Domain = value);
            databaseOptionSet.Add("domain2:", OptionCategory.SmugglerDatabase, "The domain to use when the database requires the client to authenticate. This parameter is used only in the between operation.", value => GetCredentials(databaseOptions.Destination).Domain = value);
            databaseOptionSet.Add("key|api-key|apikey:", OptionCategory.SmugglerDatabase, "The API-key to use, when using OAuth.", value => databaseOptions.Source.ApiKey = value);
            databaseOptionSet.Add("key2|api-key2|apikey2:", OptionCategory.SmugglerDatabase, "The API-key to use, when using OAuth. This parameter is used only in the between operation.", value => databaseOptions.Destination.ApiKey = value);
            databaseOptionSet.Add("strip-replication-information", OptionCategory.SmugglerDatabase, "Remove all replication information from metadata (import only)", _ => databaseOptions.StripReplicationInformation            = true);
            databaseOptionSet.Add("continuation-token:", OptionCategory.SmugglerDatabase, "Activates the usage of a continuation token in case of unreliable connections or huge imports", s => databaseOptions.ContinuationToken = s);
            databaseOptionSet.Add("skip-conflicted", OptionCategory.SmugglerDatabase, "The database will issue and error when conflicted documents are put. The default is to alert the user, this allows to skip them to continue.", _ => databaseOptions.SkipConflicted = true);

            filesystemOptionSet = new OptionSet();
            filesystemOptionSet.Add("timeout:", OptionCategory.SmugglerFileSystem, "The timeout to use for requests", s => filesOptions.Timeout = TimeSpan.FromMilliseconds(int.Parse(s)));
            filesystemOptionSet.Add("incremental", OptionCategory.SmugglerFileSystem, "States usage of incremental operations", _ => filesOptions.Incremental = true);
            filesystemOptionSet.Add("u|user|username:"******"The username to use when the filesystem requires the client to authenticate.", value => GetCredentials(filesOptions.Source).UserName = value);
            filesystemOptionSet.Add("u2|user2|username2:", OptionCategory.SmugglerFileSystem, "The username to use when the filesystem requires the client to authenticate. This parameter is used only in the between operation.", value => GetCredentials(filesOptions.Destination).UserName = value);
            filesystemOptionSet.Add("p|pass|password:"******"The password to use when the filesystem requires the client to authenticate.", value => GetCredentials(filesOptions.Source).Password = value);
            filesystemOptionSet.Add("p2|pass2|password2:", OptionCategory.SmugglerFileSystem, "The password to use when the filesystem requires the client to authenticate. This parameter is used only in the between operation.", value => GetCredentials(filesOptions.Destination).Password = value);
            filesystemOptionSet.Add("domain:", OptionCategory.SmugglerFileSystem, "The domain to use when the filesystem requires the client to authenticate.", value => GetCredentials(filesOptions.Source).Domain = value);
            filesystemOptionSet.Add("domain2:", OptionCategory.SmugglerFileSystem, "The domain to use when the filesystem requires the client to authenticate. This parameter is used only in the between operation.", value => GetCredentials(filesOptions.Destination).Domain = value);
            filesystemOptionSet.Add("key|api-key|apikey:", OptionCategory.SmugglerFileSystem, "The API-key to use, when using OAuth.", value => filesOptions.Source.ApiKey = value);
            filesystemOptionSet.Add("key2|api-key2|apikey2:", OptionCategory.SmugglerFileSystem, "The API-key to use, when using OAuth. This parameter is used only in the between operation.", value => filesOptions.Destination.ApiKey   = value);
            filesystemOptionSet.Add("f|filesystem:", OptionCategory.SmugglerFileSystem, "The filesystem to operate on. If no specified, the operations will be on the default filesystem.", value => filesOptions.Source.DefaultFileSystem = value);
            filesystemOptionSet.Add("f2|filesystem2:", OptionCategory.SmugglerFileSystem, "The filesystem to export to. If no specified, the operations will be on the default filesystem. This parameter is used only in the between operation.", value => filesOptions.Destination.DefaultFileSystem = value);
        }
Пример #60
0
 public Program()
 {
     optionSet = new OptionSet();
     optionSet.Add("fs-server:", OptionCategory.RestoreFileSystem, "The url of the RavenDB instance where attachments will be copied to the specified file system", value =>
     {
         use2NdConnection = true;
         fsConnectionStringOptions.Url = value;
     });
     optionSet.Add("d|database:", OptionCategory.RestoreDatabase, "The database to operate on. If no specified, the operations will be on the default database.", value => dbConnectionStringOptions.DefaultDatabase = value);
     optionSet.Add("fs|filesystem:", OptionCategory.RestoreFileSystem, "The file system to export to.", value => fileSystemName = value);
     optionSet.Add("u|user|username:"******"The username to use when the database requires the client to authenticate.", value => ((NetworkCredential)dbConnectionStringOptions.Credentials).UserName = value);
     optionSet.Add("u2|user2|username2:", OptionCategory.None, "The username to use when the file system requires the client to authenticate.", value =>
     {
         use2NdConnection = true;
         ((NetworkCredential)fsConnectionStringOptions.Credentials).UserName = value;
     });
     optionSet.Add("db-pass|db-password:"******"The password to use when the database requires the client to authenticate.", value => ((NetworkCredential)dbConnectionStringOptions.Credentials).Password = value);
     optionSet.Add("fs-pass|fs-password:"******"The password to use when the file system requires the client to authenticate.", value =>
     {
         use2NdConnection = true;
         ((NetworkCredential)fsConnectionStringOptions.Credentials).Password = value;
     });
     optionSet.Add("db-domain:", OptionCategory.RestoreDatabase, "The domain to use when the database requires the client to authenticate.", value => ((NetworkCredential)dbConnectionStringOptions.Credentials).Domain = value);
     optionSet.Add("fs-domain:", OptionCategory.RestoreFileSystem, "The domain to use when the file system requires the client to authenticate.", value =>
     {
         use2NdConnection = true;
         ((NetworkCredential)fsConnectionStringOptions.Credentials).Domain = value;
     });
     optionSet.Add("db-key|db-api-key|db-apikey:", OptionCategory.RestoreDatabase, "The API-key to use if the database requires OAuth authentication.", value => dbConnectionStringOptions.ApiKey = value);
     optionSet.Add("fs-key|fs-api-key|fs-apikey:", OptionCategory.RestoreFileSystem, "The API-key to use if the file system requires OAuth authentication.", value =>
     {
         use2NdConnection = true;
         fsConnectionStringOptions.ApiKey = value;
     });
     optionSet.Add("bs|batch-size:", OptionCategory.None, "Batch size for downloading attachments at once and uploading one-by-one to the file system. Default: 128.", value => batchSize = int.Parse(value));
     optionSet.Add("delete-copied-attachments", OptionCategory.RestoreDatabase, "Delete an attachment after uploading it to the file system.", v => deleteCopiedAttachments = true);
     optionSet.Add("h|?|help", OptionCategory.Help, string.Empty, v => PrintUsageAndExit(0));
 }