private static async Task<int> ExecuteAsync(CommonOptions commonOptions,
            string connection,
            string provider,
            bool dataAnnotations,
            string context,
            bool force,
            string outputDir,
            IEnumerable<string> schemas,
            IEnumerable<string> tables,
            string environment)
        {
            await new OperationExecutor(commonOptions, environment)
                .ReverseEngineerAsync(
                    provider,
                    connection,
                    outputDir,
                    context,
                    schemas,
                    tables,
                    dataAnnotations,
                    force);

            Reporter.Error.WriteLine("Done");

            return 0;
        }
        private static int Execute(CommonOptions commonOptions,
            string from,
            string to,
            string output,
            bool idempotent,
            string context,
            string environment)
        {
            var sql = new OperationExecutor(commonOptions, environment)
                .ScriptMigration(from, to, idempotent, context);

            if (string.IsNullOrEmpty(output))
            {
                Reporter.Output.WriteLine(sql);
            }
            else
            {
                Reporter.Verbose.WriteLine("Writing SQL script to '" + output + "'".Bold().Black());
                File.WriteAllText(output, sql, Encoding.UTF8);

                // TODO https://github.com/aspnet/EntityFramework/issues/4771
                // Reporter.Error.WriteLine("Done");
            }

            return 0;
        }
        private static int Execute(CommonOptions commonOptions,
            string context, 
            string environment, 
            bool force)
        {
            new OperationExecutor(commonOptions, environment)
                .RemoveMigration(context, force);

            return 0;
        }
        private static int Execute(CommonOptions commonOptions,
            string environment,
            Action<IEnumerable<Type>> reportResultsAction)
        {
            var contextTypes = new OperationExecutor(commonOptions, environment)
                .GetContextTypes();

            reportResultsAction(contextTypes);

            return 0;
        }
        private static int Execute(CommonOptions commonOptions,
            string context,
            string environment,
            Action<IEnumerable<MigrationInfo>> reportResultsAction)
        {
            var migrations = new OperationExecutor(commonOptions, environment)
                .GetMigrations(context);

            reportResultsAction(migrations);

            return 0;
        }
        private static int Execute(CommonOptions commonOptions,
            string name,
            string outputDir,
            string context,
            string environment,
            Action<MigrationFiles> reporter)
        {
            var files = new OperationExecutor(commonOptions, environment)
                .AddMigration(name, outputDir, context);

            reporter?.Invoke(files);

            Reporter.Error.WriteLine("Done. To undo this action, use 'ef migrations remove'");

            return 0;
        }
Пример #7
0
        public static Command Create()
        {
            var command = new Command(
                name: "refresh",
                description: CoreStrings.RefreshCommandDescription,
                argument: new Argument <string[]>
            {
                Name        = "references",
                Description = CoreStrings.RefreshCommandArgumentDescription,
                Arity       = ArgumentArity.ZeroOrMore
            });

            command.AddOption(CommonOptions.ProjectOption());
            command.AddOption(new Option(
                                  aliases: new[] { "--dry-run" },
                                  description: CoreStrings.DryRunOptionDescription,
                                  argument: Argument.None
                                  ));

            command.Handler = CommandHandler.Create <IConsole, FileInfo, bool, string[]>(
                async(console, project, dryRun, references) =>
            {
                try
                {
                    var command = new RefreshCommand(console, project);
                    await command.RefreshAsync(dryRun, references);

                    return(0);
                }
                catch (CLIToolException e)
                {
                    console.LogError(e);

                    return(-1);
                }
            });

            return(command);
        }
Пример #8
0
        public GeneralOptions GetGeneralOptions()
        {
            var commonOptions = new CommonOptions
            {
                NotificationTitle = _notificationTitle,
                SucessText        = _sucessText,
                FailureText       = _failureText,
                NotifierType      = _notifierType
            };

            var pushbulletOptions = new PushbulletOptions
            {
                AuthToken      = _pushbulletAuthToken,
                TargetDeviceId = _pushbulletTargetDeviceId
            };

            return(new GeneralOptions
            {
                Common = commonOptions,
                Pushbullet = pushbulletOptions
            });
        }
Пример #9
0
        protected virtual void ConfigureContainer(ContainerBuilder builder, CommonOptions options)
        {
            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            builder.RegisterInstance(fileSystem).As <ICalamariFileSystem>();
            builder.RegisterType <VariablesFactory>().AsSelf();
            builder.Register(c => c.Resolve <VariablesFactory>().Create(options)).As <IVariables>().SingleInstance();
            builder.RegisterType <ScriptEngine>().As <IScriptEngine>();
            builder.RegisterType <VariableLogger>().AsSelf();
            builder.RegisterInstance(Log).As <ILog>().SingleInstance();
            builder.RegisterType <FreeSpaceChecker>().As <IFreeSpaceChecker>().SingleInstance();
            builder.RegisterType <CommandLineRunner>().As <ICommandLineRunner>().SingleInstance();
            builder.RegisterType <FileSubstituter>().As <IFileSubstituter>();
            builder.RegisterType <SubstituteInFiles>().As <ISubstituteInFiles>();
            builder.RegisterType <CombinedPackageExtractor>().As <ICombinedPackageExtractor>();
            builder.RegisterType <ExtractPackage>().As <IExtractPackage>();
            builder.RegisterType <CodeGenFunctionsRegistry>().SingleInstance();
            builder.RegisterType <AssemblyEmbeddedResources>().As <ICalamariEmbeddedResources>();

            var assemblies = GetAllAssembliesToRegister().ToArray();

            builder.RegisterAssemblyTypes(assemblies).AssignableTo <ICodeGenFunctions>().As <ICodeGenFunctions>().SingleInstance();

            builder.RegisterAssemblyTypes(assemblies)
            .AssignableTo <IScriptWrapper>()
            .Except <TerminalScriptWrapper>()
            .As <IScriptWrapper>()
            .SingleInstance();

            builder.RegisterAssemblyTypes(assemblies)
            .AssignableTo <ICommand>()
            .Where(t => ((CommandAttribute)Attribute.GetCustomAttribute(t, typeof(CommandAttribute))).Name
                   .Equals(options.Command, StringComparison.OrdinalIgnoreCase))
            .Named <ICommand>(t => ((CommandAttribute)Attribute.GetCustomAttribute(t, typeof(CommandAttribute))).Name);

            builder.RegisterInstance(options).AsSelf().SingleInstance();

            builder.RegisterModule <StructuredConfigVariablesModule>();
        }
Пример #10
0
        public static Command Create()
        {
            var command = new Command(
                name: "add-file",
                description: CoreStrings.AddFileCommandDescription);

            command.AddArgument(new Argument <string[]>
            {
                Name        = "files",
                Description = CoreStrings.AddFileCommandArgumentDescription,
                Arity       = ArgumentArity.OneOrMore
            });

            command.AddOption(CommonOptions.ProjectOption());
            command.AddOption(CommonOptions.ServiceOption());
            command.AddOption(CommonOptions.AdditionalImportDirsOption());
            command.AddOption(CommonOptions.AccessOption());

            command.Handler = CommandHandler.Create <IConsole, FileInfo, Services, Access, string, string[]>(
                async(console, project, services, access, additionalImportDirs, files) =>
            {
                try
                {
                    var command = new AddFileCommand(console, project);
                    await command.AddFileAsync(services, access, additionalImportDirs, files);

                    return(0);
                }
                catch (CLIToolException e)
                {
                    console.LogError(e);

                    return(-1);
                }
            });

            return(command);
        }
Пример #11
0
        public static BuildCommand FromArgs(string[] args, string msbuildPath = null)
        {
            PerformanceLogEventSource.Log.CreateBuildCommandStart();

            var msbuildArgs = new List <string>();

            var parser = Parser.Instance;

            var parseResult = parser.ParseFrom("dotnet build", args);

            parseResult.ShowHelpOrErrorIfAppropriate();

            CommonOptions.ValidateSelfContainedOptions(parseResult.HasOption(BuildCommandParser.SelfContainedOption),
                                                       parseResult.HasOption(BuildCommandParser.NoSelfContainedOption));

            msbuildArgs.Add($"-consoleloggerparameters:Summary");

            if (parseResult.HasOption(BuildCommandParser.NoIncrementalOption))
            {
                msbuildArgs.Add("-target:Rebuild");
            }
            var arguments = parseResult.ValueForArgument <IEnumerable <string> >(BuildCommandParser.SlnOrProjectArgument) ?? Array.Empty <string>();

            msbuildArgs.AddRange(parseResult.OptionValuesToBeForwarded(BuildCommandParser.GetCommand()));

            msbuildArgs.AddRange(arguments);

            bool noRestore = parseResult.HasOption(BuildCommandParser.NoRestoreOption);

            BuildCommand command = new BuildCommand(
                msbuildArgs,
                noRestore,
                msbuildPath);

            PerformanceLogEventSource.Log.CreateBuildCommandStop();

            return(command);
        }
        protected async Task <int> Run(string[] args)
        {
            try
            {
                SecurityProtocols.EnableAllSecurityProtocols();
                var options = CommonOptions.Parse(args);

                log.Verbose($"Calamari Version: {GetType().Assembly.GetInformationalVersion()}");

                if (options.Command.Equals("version", StringComparison.OrdinalIgnoreCase))
                {
                    return(0);
                }

                var envInfo = string.Join($"{Environment.NewLine}  ",
                                          EnvironmentHelper.SafelyGetEnvironmentInformation());
                log.Verbose($"Environment Information: {Environment.NewLine}  {envInfo}");

                EnvironmentHelper.SetEnvironmentVariable("OctopusCalamariWorkingDirectory",
                                                         Environment.CurrentDirectory);
                ProxyInitializer.InitializeDefaultProxy();

                var builder = new ContainerBuilder();
                ConfigureContainer(builder, options);
                using (var container = builder.Build())
                {
                    container.Resolve <VariableLogger>().LogVariables();

                    await ResolveAndExecuteCommand(container, options);

                    return(0);
                }
            }
            catch (Exception ex)
            {
                return(ConsoleFormatter.PrintError(ConsoleLog.Instance, ex));
            }
        }
Пример #13
0
        private Func <object, object, bool> GetSerializeIf(Item item, CommonOptions options)
        {
            if (Default == null)
            {
                Default = Factory();
            }
            var d     = item.GetValue(Default);
            var icoll = Utils.GetICollection(item.Type);

            if (d == null || icoll == null)
            {
                return((object obj, object value) => !object.Equals(value, d));
            }
            var  defColl       = (IEnumerable)d;
            var  collMeta      = Get(item.Type, options);
            bool checkForEmpty = options.CheckForEmptyCollections && collMeta.SerializeItemIf != null;

            if (
                defColl.GetEnumerator().MoveNext() &&
                (!checkForEmpty || IsNonEmptyCollectionConditional(Default, defColl, collMeta))
                )
            {
                var m  = Utils.GetPrivateCovariantGeneric(GetType(), nameof(IsEqualCollections), icoll);
                var eq = (Func <object, IEnumerable, bool>)Delegate.CreateDelegate(
                    typeof(Func <object, IEnumerable, bool>), this, m);
                return((object obj, object value) => eq(value, defColl));
            }
            if (checkForEmpty)
            {
                return((object obj, object value) => IsNonEmptyCollectionConditional(obj, value, collMeta));
            }
            var mi = Utils.GetPrivateGeneric(
                GetType(), nameof(IsNonEmptyCollection), icoll.GetGenericArguments()[0]);

            return
                ((Func <object, object, bool>)
                 Delegate.CreateDelegate(typeof(Func <object, object, bool>), this, mi));
        }
Пример #14
0
        public int Launch()
        {
            CommonOptions      commonOptions = _modeRunner.CommonOptions;
            IDirectoryLocation outFolder     = commonOptions.OutputDirectory;
            var log   = outFolder.GetFileLocation("CanvasLog.txt");
            var error = outFolder.GetFileLocation("CanvasError.txt");

            using (ILogger logger = new Logger(log, error))
            {
                try
                {
                    logger.Info($"Running Canvas {_mode} {_version}");
                    logger.Info($"Command-line arguments: {string.Join(" ", _args)}");
                    var checkpointRunner =
                        GetCheckpointRunner(
                            logger,
                            outFolder,
                            commonOptions.StartCheckpoint,
                            commonOptions.StopCheckpoint,
                            commonOptions.WholeGenomeFasta);
                    using (var manager = checkpointRunner.Manager)
                    {
                        IDirectoryLocation loggingFolder = outFolder.CreateSubdirectory("Logging");
                        IsasConfiguration  config        = IsasConfiguration.GetConfiguration();
                        IWorkManager       workManager   = new LocalWorkManager(logger, loggingFolder, 0, config.MaximumMemoryGB, config.MaximumHoursPerProcess);
                        _modeRunner.Run(logger, checkpointRunner, workManager);
                        manager.CheckFinalState();
                    }
                }
                catch (StopCheckpointFoundException) { }
                catch (Exception e)
                {
                    logger.Error($"Canvas workflow error: {e}");
                    return(-1);
                }
            }
            return(0);
        }
Пример #15
0
        void ReadEncryptedVariablesFromFile(CommonOptions options, CalamariVariables variables)
        {
            foreach (var sensitiveFilePath in options.InputVariables.SensitiveVariablesFiles.Where(f => !string.IsNullOrEmpty(f)))
            {
                var sensitiveFilePassword = options.InputVariables.SensitiveVariablesPassword;
                var rawVariables          = string.IsNullOrWhiteSpace(sensitiveFilePassword)
                    ? fileSystem.ReadFile(sensitiveFilePath)
                    : Decrypt(fileSystem.ReadAllBytes(sensitiveFilePath), sensitiveFilePassword);

                try
                {
                    var sensitiveVariables = JsonConvert.DeserializeObject <Dictionary <string, string> >(rawVariables);
                    foreach (var variable in sensitiveVariables)
                    {
                        variables.Set(variable.Key, variable.Value);
                    }
                }
                catch (JsonReaderException)
                {
                    throw new CommandException("Unable to parse sensitive-variables as valid JSON.");
                }
            }
        }
Пример #16
0
 /// <summary>
 /// Main entry point to the CIL extractor.
 /// Call this to extract a given assembly.
 /// </summary>
 /// <param name="layout">The trap layout.</param>
 /// <param name="assemblyPath">The full path of the assembly to extract.</param>
 /// <param name="logger">The logger.</param>
 /// <param name="nocache">True to overwrite existing trap file.</param>
 /// <param name="extractPdbs">Whether to extract PDBs.</param>
 /// <param name="trapFile">The path of the trap file.</param>
 /// <param name="extracted">Whether the file was extracted (false=cached).</param>
 public static void ExtractCIL(string assemblyPath, ILogger logger, CommonOptions options, out string trapFile, out bool extracted)
 {
     trapFile  = "";
     extracted = false;
     try
     {
         var canonicalPathCache      = CanonicalPathCache.Create(logger, 1000);
         var pathTransformer         = new PathTransformer(canonicalPathCache);
         var extractor               = new TracingExtractor(assemblyPath, logger, pathTransformer, options);
         var transformedAssemblyPath = pathTransformer.Transform(assemblyPath);
         using var trapWriter = transformedAssemblyPath.WithSuffix(".cil").CreateTrapWriter(logger, options.TrapCompression, discardDuplicates: true);
         trapFile             = trapWriter.TrapFile;
         if (!options.Cache || !System.IO.File.Exists(trapFile))
         {
             ExtractCIL(extractor, trapWriter, options.PDB);
             extracted = true;
         }
     }
     catch (Exception ex)  // lgtm[cs/catch-of-all-exceptions]
     {
         logger.Log(Severity.Error, string.Format("Exception extracting {0}: {1}", assemblyPath, ex));
     }
 }
Пример #17
0
        public static Command Create(HttpClient httpClient)
        {
            var command = new Command(
                name: "remove",
                description: CoreStrings.RemoveCommandDescription);

            var projectOption      = CommonOptions.ProjectOption();
            var referencesArgument = new Argument <string[]>
            {
                Name        = "references",
                Description = CoreStrings.RemoveCommandArgumentDescription,
                Arity       = ArgumentArity.OneOrMore
            };

            command.AddOption(projectOption);
            command.AddArgument(referencesArgument);

            command.SetHandler <string, string[], InvocationContext, IConsole>(
                (project, references, context, console) =>
            {
                try
                {
                    var command = new RemoveCommand(console, project, httpClient);
                    command.Remove(references);

                    context.ExitCode = 0;
                }
                catch (CLIToolException e)
                {
                    console.LogError(e);

                    context.ExitCode = -1;
                }
            }, projectOption, referencesArgument);

            return(command);
        }
Пример #18
0
        public async Task <string> ResolveAppHostSourceDirectoryAsync(string archOption, NuGetFramework targetFramework, Architecture arch)
        {
            string rid;
            var    validRids = new string[] { "win-x64", "win-arm64", "osx-x64", "osx-arm64" };

            if (string.IsNullOrEmpty(archOption))
            {
                if (targetFramework != null &&
                    (((targetFramework.Version.Major < 6 && OperatingSystem.IsMacOS()) ||
                      (targetFramework.Version.Major < 5 && OperatingSystem.IsWindows())) &&
                     !arch.Equals(Architecture.X64)))
                {
                    rid = OperatingSystem.IsWindows() ? "win-x64" : "osx-x64";
                }
                else
                {
                    // Use the default app host
                    return(GetDefaultAppHostSourceDirectory());
                }
            }
            else
            {
                rid = CommonOptions.ResolveRidShorthandOptionsToRuntimeIdentifier(null, archOption);
            }

            if (!validRids.Contains(rid))
            {
                throw new GracefulException(string.Format(LocalizableStrings.InvalidRuntimeIdentifier, rid, string.Join(" ", validRids)));
            }

            var packageId   = new PackageId($"microsoft.netcore.app.host.{rid}");
            var packagePath = await _nugetPackageDownloader.DownloadPackageAsync(packageId, packageSourceLocation : _packageSourceLocation);

            var content = await _nugetPackageDownloader.ExtractPackageAsync(packagePath, _tempDir);

            return(Path.Combine(_tempDir.Value, "runtimes", rid, "native"));
        }
Пример #19
0
        public static void ExtractStandalone(
            IEnumerable <string> sources,
            IEnumerable <string> referencePaths,
            IProgressMonitor pm,
            ILogger logger,
            CommonOptions options)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var canonicalPathCache = CanonicalPathCache.Create(logger, 1000);
            var pathTransformer    = new PathTransformer(canonicalPathCache);

            using var analyser = new StandaloneAnalyser(pm, logger, false, pathTransformer);
            try
            {
                AnalyseStandalone(analyser, sources, referencePaths, options, pm, stopwatch);
            }
            catch (Exception ex)  // lgtm[cs/catch-of-all-exceptions]
            {
                analyser.Logger.Log(Severity.Error, "  Unhandled exception: {0}", ex);
            }
        }
Пример #20
0
        public Task <IEnumerable <string> > GetInstalledVersionsAsync(CancellationToken cancellationToken)
        {
            string dotnetDir = CommonOptions.GetDotnetExeDirectory();
            IEnumerable <string> sdks;

            try
            {
                // sdks contain the full path, version is the last part
                //  details: https://github.com/dotnet/runtime/blob/5098d45cc1bf9649fab5df21f227da4b80daa084/src/native/corehost/fxr/sdk_info.cpp#L76
                sdks = NETCoreSdkResolverNativeWrapper.GetAvailableSdks(dotnetDir).Select(Path.GetFileName);
            }
            // The NETCoreSdkResolverNativeWrapper is not properly initialized (case of OSx in test env) - let's manually perform what
            //  sdk_info::get_all_sdk_infos does
            catch (Exception e) when(e is HostFxrRuntimePropertyNotSetException or HostFxrNotFoundException)
            {
                string sdkDir = Path.Combine(dotnetDir, "sdk");

                sdks =
                    Directory.Exists(sdkDir)
                        ? Directory.GetDirectories(sdkDir).Select(Path.GetFileName).Where(IsValidFxVersion)
                        : Enumerable.Empty <string>();
            }
            return(Task.FromResult(sdks));
        }
Пример #21
0
        public int Launch()
        {
            CommonOptions      commonOptions = _modeRunner.CommonOptions;
            IDirectoryLocation outFolder     = commonOptions.OutputDirectory;
            var log   = outFolder.GetFileLocation("CanvasLog.txt");
            var error = outFolder.GetFileLocation("CanvasError.txt");
            IsasConfiguration  config     = IsasConfiguration.GetConfiguration();
            IDirectoryLocation genomeRoot = commonOptions.WholeGenomeFasta?.Parent?.Parent?.Parent?.Parent?.Parent;
            int returnValue = 0;

            IsasFrameworkFactory.RunWithIsasFramework(outFolder, log, error, commonOptions.StartCheckpoint, commonOptions.StopCheckpoint, 0,
                                                      config.MaximumMemoryGB, config.MaximumHoursPerProcess, false, genomeRoot,
                                                      frameworkServices =>
            {
                var logger = frameworkServices.Logger;
                try
                {
                    var executableProcessor = new ExecutableProcessor(new NullSampleSettings(), logger);
#if DotNetCore
                    var runtimeExecutable = new FileLocation(executableProcessor.GetEnvironmentExecutablePath("dotnet"));
#else
                    var runtimeExecutable = CrossPlatform.IsThisLinux() ? new FileLocation(executableProcessor.GetMonoPath()) : null;
#endif
                    frameworkServices.Logger.Info($"Running Canvas {_mode} {_version}");
                    logger.Info($"Command-line arguments: {string.Join(" ", _args)}");
                    _modeRunner.Run(logger, frameworkServices.Checkpointer, frameworkServices.WorkManager, runtimeExecutable);
                    returnValue = 0;
                }
                catch (Exception e)
                {
                    logger.Error($"Canvas workflow error: {e}");
                    returnValue = -1;
                }
            });
            return(returnValue);
        }
Пример #22
0
        void ReadOutputVariablesFromOfflineDropPreviousSteps(CommonOptions options, CalamariVariables variables)
        {
            var outputVariablesFilePath = options.InputVariables.OutputVariablesFile;

            if (string.IsNullOrEmpty(outputVariablesFilePath))
            {
                return;
            }

            var rawVariables = DecryptWithMachineKey(fileSystem.ReadFile(outputVariablesFilePath), options.InputVariables.OutputVariablesPassword);

            try
            {
                var outputVariables = JsonConvert.DeserializeObject <Dictionary <string, string> >(rawVariables);
                foreach (var variable in outputVariables)
                {
                    variables.Set(variable.Key, variable.Value);
                }
            }
            catch (JsonReaderException)
            {
                throw new CommandException("Unable to parse output variables as valid JSON.");
            }
        }
Пример #23
0
 public TumorNormalWgsRunner(CommonOptions commonOptions, SingleSampleCommonOptions singleSampleCommonOptions, TumorNormalOptions tumorNormalOptions)
 {
     _tumorNormalOptions       = tumorNormalOptions;
     CommonOptions             = commonOptions;
     SingleSampleCommonOptions = singleSampleCommonOptions;
 }
Пример #24
0
        private void ExploreType(Type t, CommonOptions options)
        {
            const BindingFlags bindingFlags =
                BindingFlags.Static | BindingFlags.Instance |
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.FlattenHierarchy;

            foreach (var m in t.GetMembers(bindingFlags))
            {
                var attrs = Options.GetItem(m);
                if (attrs.HasAttr(Options.ExcludeAttribute))
                {
                    continue;
                }
                switch (m.MemberType)
                {
                case MemberTypes.Field:
                    var f = m as FieldInfo;
                    if (f.FieldType == typeof(YuzuUnknownStorage))
                    {
                        if (GetUnknownStorage != null)
                        {
                            throw Error("Duplicated unknown storage in field {0}", m.Name);
                        }
                        GetUnknownStorage = obj => (YuzuUnknownStorage)f.GetValue(obj);
                    }
                    else
                    {
                        AddItem(m, options,
                                Must.HasFlag(YuzuItemKind.Field) && f.IsPublic,
                                AllKind.HasFlag(YuzuItemKind.Field) && f.IsPublic);
                    }
                    break;

                case MemberTypes.Property:
                    var p = m as PropertyInfo;
                    var g = p.GetGetMethod();
                    if (p.PropertyType == typeof(YuzuUnknownStorage))
                    {
                        if (GetUnknownStorage != null)
                        {
                            throw Error("Duplicated unknown storage in field {0}", m.Name);
                        }
#if iOS // Apple forbids code generation.
                        GetUnknownStorage = obj => (YuzuUnknownStorage)p.GetValue(obj, Utils.ZeroObjects);
#else
                        var getter = BuildGetter(g);
                        GetUnknownStorage = obj => (YuzuUnknownStorage)getter(obj);
#endif
                    }
                    else
                    {
                        AddItem(m, options,
                                Must.HasFlag(YuzuItemKind.Property) && g != null,
                                AllKind.HasFlag(YuzuItemKind.Property) && g != null);
                    }
                    break;

                case MemberTypes.Method:
                    AddMethod(m as MethodInfo);
                    break;
                }
            }
        }
Пример #25
0
 public static bool IsCopyable(Type t, CommonOptions options) =>
 Utils.IsCopyable(t) ?? Meta.Get(t, options).IsCopyable;
 public void Configure(IArgumentsBuilder argumentsBuilder)
 {
     argumentsBuilder.AddRequiredList("p", "package-ids", this.packageIds, "The packages to purge (* Wildcards supported)");
     argumentsBuilder.AddOptional("s", "source", () => this.Source, s => this.Source = s, @"Local source or source name to search for packages");
     CommonOptions.AddVerbose(argumentsBuilder, this.Verbose, b => this.Verbose      = b);
 }
Пример #27
0
 public static Meta Get(Type t, CommonOptions options) =>
 cache.GetOrAdd(Tuple.Create(t, options), MakeMeta);
Пример #28
0
        public static void ExtractStandalone(
            IEnumerable <string> sources,
            IEnumerable <string> referencePaths,
            IProgressMonitor pm,
            ILogger logger,
            CommonOptions options)
        {
            using (var analyser = new Analyser(pm, logger))
                using (var references = new BlockingCollection <MetadataReference>())
                {
                    try
                    {
                        var referenceTasks = referencePaths.Select <string, Action>(path => () =>
                        {
                            var reference = MetadataReference.CreateFromFile(path);
                            references.Add(reference);
                        });

                        var syntaxTrees     = new List <SyntaxTree>();
                        var syntaxTreeTasks = ReadSyntaxTrees(sources, analyser, null, null, syntaxTrees);

                        var sw = new Stopwatch();
                        sw.Start();

                        Parallel.Invoke(
                            new ParallelOptions {
                            MaxDegreeOfParallelism = options.Threads
                        },
                            referenceTasks.Interleave(syntaxTreeTasks).ToArray());

                        if (syntaxTrees.Count == 0)
                        {
                            analyser.Logger.Log(Severity.Error, "  No source files");
                            ++analyser.CompilationErrors;
                        }

                        var compilation = CSharpCompilation.Create(
                            "csharp.dll",
                            syntaxTrees,
                            references
                            );

                        analyser.InitializeStandalone(compilation, options);
                        analyser.AnalyseReferences();

                        foreach (var tree in compilation.SyntaxTrees)
                        {
                            analyser.AnalyseTree(tree);
                        }

                        sw.Stop();
                        analyser.Logger.Log(Severity.Info, "  Models constructed in {0}", sw.Elapsed);

                        sw.Restart();
                        analyser.PerformExtraction(options.Threads);
                        sw.Stop();
                        analyser.Logger.Log(Severity.Info, "  Extraction took {0}", sw.Elapsed);

                        foreach (var type in analyser.MissingNamespaces)
                        {
                            pm.MissingNamespace(type);
                        }

                        foreach (var type in analyser.MissingTypes)
                        {
                            pm.MissingType(type);
                        }

                        pm.MissingSummary(analyser.MissingTypes.Count(), analyser.MissingNamespaces.Count());
                    }
                    catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
                    {
                        analyser.Logger.Log(Severity.Error, "  Unhandled exception: {0}", ex);
                    }
                }
        }
Пример #29
0
        public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions options)
        {
            var exitCode = Exit.OK;

            Parser.Default.ParseArgumentsStrict(options.options.ToArray(), new CompatOptions(), (string option, object suboptions) =>
            {
                // ParseArgumentsStrict calls us unconditionally, even with bad arguments
                if (!string.IsNullOrEmpty(option) && suboptions != null)
                {
                    CommonOptions comOpts = (CommonOptions)suboptions;
                    comOpts.Merge(opts);
                    _user       = new ConsoleUser(comOpts.Headless);
                    _kspManager = manager ?? new GameInstanceManager(_user);
                    exitCode    = comOpts.Handle(_kspManager, _user);
                    if (exitCode != Exit.OK)
                    {
                        return;
                    }

                    switch (option)
                    {
                    case "list":
                        {
                            var ksp = MainClass.GetGameInstance(_kspManager);

                            const string versionHeader = "Version";
                            const string actualHeader  = "Actual";

                            var output = ksp
                                         .GetCompatibleVersions()
                                         .Select(i => new
                            {
                                Version = i,
                                Actual  = false
                            })
                                         .ToList();

                            output.Add(new
                            {
                                Version = ksp.Version(),
                                Actual  = true
                            });

                            output = output
                                     .OrderByDescending(i => i.Actual)
                                     .ThenByDescending(i => i.Version)
                                     .ToList();

                            var versionWidth = Enumerable
                                               .Repeat(versionHeader, 1)
                                               .Concat(output.Select(i => i.Version.ToString()))
                                               .Max(i => i.Length);

                            var actualWidth = Enumerable
                                              .Repeat(actualHeader, 1)
                                              .Concat(output.Select(i => i.Actual.ToString()))
                                              .Max(i => i.Length);

                            const string columnFormat = "{0}  {1}";

                            _user.RaiseMessage(string.Format(columnFormat,
                                                             versionHeader.PadRight(versionWidth),
                                                             actualHeader.PadRight(actualWidth)
                                                             ));

                            _user.RaiseMessage(string.Format(columnFormat,
                                                             new string('-', versionWidth),
                                                             new string('-', actualWidth)
                                                             ));

                            foreach (var line in output)
                            {
                                _user.RaiseMessage(string.Format(columnFormat,
                                                                 line.Version.ToString().PadRight(versionWidth),
                                                                 line.Actual.ToString().PadRight(actualWidth)
                                                                 ));
                            }
                        }
                        break;

                    case "add":
                        {
                            var ksp        = MainClass.GetGameInstance(_kspManager);
                            var addOptions = (CompatAddOptions)suboptions;

                            GameVersion GameVersion;
                            if (GameVersion.TryParse(addOptions.Version, out GameVersion))
                            {
                                var newCompatibleVersion = ksp.GetCompatibleVersions();
                                newCompatibleVersion.Add(GameVersion);
                                ksp.SetCompatibleVersions(newCompatibleVersion);
                            }
                            else
                            {
                                _user.RaiseError("ERROR: Invalid KSP version.");
                                exitCode = Exit.ERROR;
                            }
                        }
                        break;

                    case "forget":
                        {
                            var ksp        = MainClass.GetGameInstance(_kspManager);
                            var addOptions = (CompatForgetOptions)suboptions;

                            GameVersion GameVersion;
                            if (GameVersion.TryParse(addOptions.Version, out GameVersion))
                            {
                                if (GameVersion != ksp.Version())
                                {
                                    var newCompatibleVersion = ksp.GetCompatibleVersions();
                                    newCompatibleVersion.RemoveAll(i => i == GameVersion);
                                    ksp.SetCompatibleVersions(newCompatibleVersion);
                                }
                                else
                                {
                                    _user.RaiseError("ERROR: Cannot forget actual KSP version.");
                                    exitCode = Exit.ERROR;
                                }
                            }
                            else
                            {
                                _user.RaiseError("ERROR: Invalid KSP version.");
                                exitCode = Exit.ERROR;
                            }
                        }
                        break;

                    default:
                        exitCode = Exit.BADOPT;
                        break;
                    }
                }
            }, () => { exitCode = MainClass.AfterHelp(); });
            return(exitCode);
        }
Пример #30
0
 public AttachmentController(IAttachmentService service, IOptionsMonitor <CommonOptions> optionsMonitor)
 {
     _service = service;
     _options = optionsMonitor.CurrentValue;
 }
Пример #31
0
        private void AddItem(MemberInfo m, CommonOptions options, bool must, bool all)
        {
            var ia = new ItemAttrs(m, Options, all ? AllOptionality : YuzuItemOptionality.None);

            if (ia.Count == 0)
            {
                if (must)
                {
                    throw Error("Item {0} must be serialized", m.Name);
                }
                return;
            }
            if (ia.Count != 1)
            {
                throw Error("More than one of optional, required and member attributes for field '{0}'", m.Name);
            }
            var attrs         = Options.GetItem(m);
            var serializeCond = attrs.Attr(Options.SerializeConditionAttribute);
            var item          = new Item {
                Alias         = Options.GetAlias(ia.Any()) ?? m.Name,
                IsOptional    = ia.Required == null,
                IsCompact     = attrs.HasAttr(Options.CompactAttribute),
                IsCopyable    = attrs.HasAttr(Options.CopyableAttribute),
                IsMember      = ia.Member != null,
                SerializeCond = serializeCond != null?
                                Options.GetSerializeCondition(serializeCond, Type) : null,
                                    SerializeIfMethod = serializeCond != null?
                                                        Options.GetSerializeMethod(serializeCond, Type) : null,
                                                            DefaultValue = serializeCond != null?
                                                                           Options.GetDefault(serializeCond) : YuzuNoDefault.NoDefault,
                                                                               Name = m.Name,
            };

            if (!item.IsOptional)
            {
                RequiredCount += 1;
            }
            var merge = attrs.HasAttr(Options.MergeAttribute);

            switch (m.MemberType)
            {
            case MemberTypes.Field:
                var f = m as FieldInfo;
                if (!f.IsPublic)
                {
                    throw Error("Non-public item '{0}'", f.Name);
                }
                item.Type     = f.FieldType;
                item.GetValue = f.GetValue;
                if (!merge)
                {
                    item.SetValue = f.SetValue;
                }
                item.FieldInfo = f;
                break;

            case MemberTypes.Property:
                var p      = m as PropertyInfo;
                var getter = p.GetGetMethod();
                if (getter == null)
                {
                    throw Error("No getter for item '{0}'", p.Name);
                }
                item.Type = p.PropertyType;
                var setter = p.GetSetMethod();
#if iOS // Apple forbids code generation.
                item.GetValue = obj => p.GetValue(obj, Utils.ZeroObjects);
                if (!merge && setter != null)
                {
                    item.SetValue = (obj, value) => p.SetValue(obj, value, Utils.ZeroObjects);
                }
#else
                if (Utils.IsStruct(Type))
                {
                    item.GetValue = obj => p.GetValue(obj, Utils.ZeroObjects);
                    if (!merge && setter != null)
                    {
                        item.SetValue = (obj, value) => p.SetValue(obj, value, Utils.ZeroObjects);
                    }
                }
                else
                {
                    item.GetValue = BuildGetter(getter);
                    if (!merge && setter != null)
                    {
                        item.SetValue = BuildSetter(setter);
                    }
                }
#endif
                item.PropInfo = p;
                break;

            default:
                throw Error("Member type {0} not supported", m.MemberType);
            }
            if (item.SetValue == null)
            {
                if (!item.Type.IsClass && !item.Type.IsInterface || item.Type == typeof(object))
                {
                    throw Error("Unable to either set or merge item {0}", item.Name);
                }
            }
            var over = Options.GetOverride(item.Type);
            if (over.HasAttr(Options.CompactAttribute))
            {
                item.IsCompact = true;
            }
            if (!over.HasAttr(Options.CopyableAttribute))
            {
                CheckCopyable(item.Type, options);
            }

            if (ia.Member != null && item.SerializeCond == null && !Type.IsAbstract && !Type.IsInterface)
            {
                item.SerializeCond = GetSerializeIf(item, options);
            }
            Items.Add(item);
        }
Пример #32
0
 static void SetCommonOptions(CommonOptions options)
 {
     Config.Debug = options.Debug;
 }
Пример #33
0
        private Meta(Type t, CommonOptions options)
        {
            Type       = t;
            Factory    = defaultFactory;
            Options    = options.Meta ?? MetaOptions.Default;
            IsCopyable = Utils.IsStruct(t);
            var over = Options.GetOverride(t);

            IsCompact = over.HasAttr(Options.CompactAttribute);
            var must = over.Attr(Options.MustAttribute);

            if (must != null)
            {
                Must = Options.GetItemKind(must);
            }
            var all = over.Attr(Options.AllAttribute);

            if (all != null)
            {
                var ok = Options.GetItemOptionalityAndKind(all);
                AllOptionality = ok.Item1;
                AllKind        = ok.Item2;
            }

            Surrogate = new Surrogate(Type, Options);
            foreach (var i in t.GetInterfaces())
            {
                ExploreType(i, options);
            }
            ExploreType(t, options);
            Surrogate.Complete();
            CheckForNoFields(options);

            Items.Sort();
            Item prev = null;

            foreach (var i in Items)
            {
                if (prev != null && prev.CompareTo(i) == 0)
                {
                    throw Error("Duplicate item {0} / {1}", i.Name, i.Alias);
                }
                prev = i;
            }
            var prevTag = "";

            foreach (var i in Items)
            {
                var tag = i.Tag(options);
                if (tag == "")
                {
                    throw Error("Empty tag for field '{0}'", i.Name);
                }
                foreach (var ch in tag)
                {
                    if (ch <= ' ' || ch >= 127)
                    {
                        throw Error("Bad character '{0}' in tag for field '{1}'", ch, i.Name);
                    }
                }
                if (tag == prevTag)
                {
                    throw Error("Duplicate tag '{0}' for field '{1}'", tag, i.Name);
                }
                prevTag = tag;
                TagToItem.Add(tag, i);
            }

            AllowReadingFromAncestor = over.HasAttr(Options.AllowReadingFromAncestorAttribute);
            if (AllowReadingFromAncestor)
            {
                var ancestorMeta = Get(t.BaseType, options);
                if (ancestorMeta.Items.Count != Items.Count)
                {
                    throw Error(
                              "Allows reading from ancestor {0}, but has {1} items instead of {2}",
                              t.BaseType.Name, Items.Count, ancestorMeta.Items.Count);
                }
            }

            var alias = over.Attr(Options.AliasAttribute);

            if (alias != null)
            {
                var aliases = Options.GetReadAliases(alias);
                if (aliases != null)
                {
                    Dictionary <string, Type> readAliases = readAliasCache.GetOrAdd(options, MakeReadAliases);
                    foreach (var a in aliases)
                    {
                        if (String.IsNullOrWhiteSpace(a))
                        {
                            throw Error("Empty read alias");
                        }
                        Type duplicate;
                        if (readAliases.TryGetValue(a, out duplicate))
                        {
                            throw Error("Read alias '{0}' was already defined for '{1}'", a, duplicate.Name);
                        }
                        readAliases.Add(a, t);
                    }
                }
                WriteAlias = Options.GetWriteAlias(alias);
                if (WriteAlias != null && WriteAlias == "")
                {
                    throw Error("Empty write alias");
                }
            }

            if (over.HasAttr(Options.CopyableAttribute))
            {
                IsCopyable = true;
            }
            else if (HasAnyTrigger())
            {
                IsCopyable = false;
            }
        }
Пример #34
0
 public CommonOptionsController(IOptions <CommonOptions> options)
 {
     _options = options.Value;
 }
Пример #35
0
            public string NameTagged(CommonOptions options)
            {
                var tag = Tag(options);

                return(Name + (tag == Name ? "" : " (" + tag + ")"));
            }
Пример #36
0
 public static string GetClientId(CommonOptions options)
 {
     return(string.IsNullOrWhiteSpace(options.Client)
         ? $"cmqtt{Process.GetCurrentProcess().Id}"
         : options.Client);
 }