예제 #1
0
        public static async Task <bool> TryWriteFileOutputAsync(this IOutputCommand command, string path, IConsoleHost host, Func <string> generator)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var directory = DynamicApis.PathGetDirectoryName(path);
                if (!string.IsNullOrEmpty(directory) && await DynamicApis.DirectoryExistsAsync(directory).ConfigureAwait(false) == false)
                {
                    await DynamicApis.DirectoryCreateDirectoryAsync(directory).ConfigureAwait(false);
                }

                var data = generator();
                if (!await DynamicApis.FileExistsAsync(path) || await DynamicApis.FileReadAllTextAsync(path) != data)
                {
                    await DynamicApis.FileWriteAllTextAsync(path, data).ConfigureAwait(false);

                    host?.WriteMessage("Code has been successfully written to file.\n");
                }
                else
                {
                    host?.WriteMessage("Code has been successfully generated but not written to file (no change detected).\n");
                }
                return(true);
            }
            return(false);
        }
예제 #2
0
        private async Task LoadAllDependenciesAsync(List <PackageReferenceInfo> packages, IConsoleHost host)
        {
            host.WriteMessage($"Load dependencies ");

            var tasks = new List <Task>();

            foreach (var entry in packages.ToList())
            {
                tasks.Add(LoadDependenciesAsync(entry, packages, tasks, host));
            }

            while (true)
            {
                List <Task> list = null;
                lock (packages)
                {
                    list = tasks.ToList();
                }

                await Task.WhenAll(list);

                lock (packages)
                {
                    if (tasks.All(t => t.IsCompleted))
                    {
                        break;
                    }
                }
            }

            host.WriteMessage($"\n");
        }
예제 #3
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            foreach (var projectPath in GetProjectPaths())
            {
                try
                {
                    var projectDirectory = System.IO.Path.GetDirectoryName(projectPath);

                    var binDirectory = System.IO.Path.Combine(projectDirectory, "bin");
                    var objDirectory = System.IO.Path.Combine(projectDirectory, "obj");

                    if (Directory.Exists(binDirectory))
                    {
                        Directory.Delete(binDirectory, true);
                        host.WriteMessage("Deleted directory " + binDirectory + "\n");
                    }

                    if (Directory.Exists(objDirectory))
                    {
                        Directory.Delete(objDirectory, true);
                        host.WriteMessage("Deleted directory " + objDirectory + "\n");
                    }
                }
                catch (Exception e)
                {
                    host.WriteError(e + "\n");
                }
            }

            return(Task.FromResult <object>(null));
        }
예제 #4
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            foreach (var projectPath in GetProjectPaths())
            {
                try
                {
                    using (var projectInformation = ProjectExtensions.LoadProject(projectPath))
                    {
                        if (projectInformation.Project.GeneratesPackage() || projectInformation.Project.HasVersion())
                        {
                            var versions = BumpVersion(projectInformation.Project, "Version", "1.0.0");

                            host.WriteMessage("[x] Bumped version of " + System.IO.Path.GetFileName(projectPath) +
                                              " from " + versions.Item2 +
                                              " to " + versions.Item1 + "\n");

                            if (!Simulate)
                            {
                                projectInformation.Project.Save();
                            }
                        }
                        else
                        {
                            host.WriteMessage("[ ] Ignoring " + System.IO.Path.GetFileName(projectPath) + ": Not GeneratePackageOnBuild\n");
                        }
                    }
                }
                catch (Exception e)
                {
                    host.WriteError(e + "\n");
                }
            }

            return(Task.FromResult <object>(null));
        }
예제 #5
0
        private async Task ExecuteDocumentAsync(IConsoleHost host, string filePath)
        {
            host.WriteMessage("\nExecuting file '" + filePath + "' with variables '" + Variables + "'...\n");

            var document = await NSwagDocument.LoadWithTransformationsAsync(filePath, Variables);

            if (document.Runtime != Runtime.Default)
            {
                if (document.Runtime != RuntimeUtilities.CurrentRuntime)
                {
                    throw new InvalidOperationException("The specified runtime in the document (" + document.Runtime + ") differs " +
                                                        "from the current process runtime (" + RuntimeUtilities.CurrentRuntime + "). " +
                                                        "Change the runtime with the '/runtime:" + document.Runtime + "' parameter " +
                                                        "or run the file with the correct command line binary.");
                }

                if (document.SelectedSwaggerGenerator == document.SwaggerGenerators.WebApiToOpenApiCommand &&
                    document.SwaggerGenerators.WebApiToOpenApiCommand.IsAspNetCore == false &&
                    document.Runtime != Runtime.Debug &&
                    document.Runtime != Runtime.WinX86 &&
                    document.Runtime != Runtime.WinX64)
                {
                    throw new InvalidOperationException("The runtime " + document.Runtime + " in the document must be used " +
                                                        "with ASP.NET Core. Enable /isAspNetCore:true.");
                }
            }

            await document.ExecuteAsync();

            host.WriteMessage("Done.\n");
        }
예제 #6
0
        public static Task <bool> TryWriteFileOutputAsync(this IOutputCommand command, string path, IConsoleHost host, NewLineBehavior newLineBehavior, Func <string> generator)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var directory = DynamicApis.PathGetDirectoryName(path);
                if (!string.IsNullOrEmpty(directory) && DynamicApis.DirectoryExists(directory) == false)
                {
                    DynamicApis.DirectoryCreateDirectory(directory);
                }

                var data = generator();

                data = data?.Replace("\r", "") ?? "";
                data = newLineBehavior == NewLineBehavior.Auto ? data.Replace("\n", Environment.NewLine) :
                       newLineBehavior == NewLineBehavior.CRLF ? data.Replace("\n", "\r\n") : data;

                if (!DynamicApis.FileExists(path) || DynamicApis.FileReadAllText(path) != data)
                {
                    DynamicApis.FileWriteAllText(path, data);

                    host?.WriteMessage("Code has been successfully written to file.\n");
                }
                else
                {
                    host?.WriteMessage("Code has been successfully generated but not written to file (no change detected).\n");
                }
                return(Task.FromResult(true));
            }
            return(Task.FromResult(false));
        }
예제 #7
0
        private static void SwitchToProjects(ReferenceSwitcherConfiguration configuration, IConsoleHost host)
        {
            var solution = SolutionFile.Parse(configuration.ActualSolution);

            foreach (var solutionProject in solution.ProjectsInOrder)
            {
                if (solutionProject.ProjectType != SolutionProjectType.SolutionFolder)
                {
                    try
                    {
                        using (var projectInformation = ProjectExtensions.LoadProject(solutionProject.AbsolutePath))
                        {
                            foreach (var mapping in configuration.Mappings)
                            {
                                var packageName  = mapping.Key;
                                var projectPaths = mapping.Value.Select(p => configuration.GetActualPath(p)).ToList();

                                var switchedProjects = SwitchToProject(configuration, solutionProject, projectInformation, packageName, projectPaths, host);
                                foreach (var s in switchedProjects)
                                {
                                    host.WriteMessage("Project " + Path.GetFileName(s.Key) + " packages:\n");
                                    host.WriteMessage("    " + packageName + " v" + s.Value + "\n    replaced by:\n");
                                    projectPaths.ForEach(p => host.WriteMessage("    " + Path.GetFileName(p) + "\n"));
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        host.WriteError("The project '" + solutionProject.AbsolutePath + "' could not be loaded: " +
                                        e.Message + "\n");
                    }
                }
            }
        }
예제 #8
0
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (!string.IsNullOrEmpty(File))
            {
                var document = await NSwagDocument.LoadWithTransformationsAsync(File, Variables);

                var command = (TypesToSwaggerCommand)document.SelectedSwaggerGenerator;

                AssemblyPaths  = command.AssemblyPaths;
                AssemblyConfig = command.AssemblyConfig;
                ReferencePaths = command.ReferencePaths;
            }

            var classNames = await RunIsolatedAsync(!string.IsNullOrEmpty(File)?Path.GetDirectoryName(File) : null);

            host.WriteMessage("\r\n");
            foreach (var className in classNames)
            {
                host.WriteMessage(className + "\r\n");
            }

            host.WriteMessage("\r\n");

            return(classNames);
        }
예제 #9
0
        private async Task ExecuteDocumentAsync(IConsoleHost host, string filePath)
        {
            host.WriteMessage("\nExecuting file '" + filePath + "'...\n");

            var document = await LoadDocumentAsync(filePath);
            await document.ExecuteAsync();

            host.WriteMessage("Done.\n");
        }
예제 #10
0
        public static async Task <int> RunAsync(
            string executable,
            IReadOnlyList <string> args,
            IConsoleHost console = null,
            TimeSpan?timeout     = null)
        {
            var arguments = ToArguments(args);

            var startInfo = new ProcessStartInfo
            {
                FileName               = executable,
                Arguments              = arguments,
                UseShellExecute        = false,
                RedirectStandardOutput = console != null,
                RedirectStandardError  = console != null,
            };

            console?.WriteMessage($"Executing {executable} {arguments}{Environment.NewLine}");
            using (var process = Process.Start(startInfo))
            {
                var tcs = new TaskCompletionSource <bool>();
                process.EnableRaisingEvents = true;
                process.Exited += (_, eventArgs) =>
                {
                    if (process.ExitCode == 0)
                    {
                        tcs.TrySetResult(true);
                    }
                    else
                    {
                        tcs.TrySetException(new Exception($"Process failed with non-zero exit code '{process.ExitCode}'."));
                    }
                };

                if (console != null)
                {
                    process.OutputDataReceived += (_, eventArgs) => console.WriteMessage(eventArgs.Data + Environment.NewLine);
                    process.ErrorDataReceived  += (_, eventArgs) => console.WriteError(eventArgs.Data + Environment.NewLine);

                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();
                }

                var result = await Task.WhenAny(tcs.Task, Task.Delay(timeout ?? TimeSpan.FromSeconds(60 * 5))).ConfigureAwait(false);

                if (result != tcs.Task)
                {
                    throw new InvalidOperationException($"Process {startInfo.FileName} timed out.");
                }
                else
                {
                    console?.WriteMessage($"Done executing command. Exit Code: {process.ExitCode}.{Environment.NewLine}");
                    return(process.ExitCode);
                }
            }
        }
예제 #11
0
 protected void WriteOutput(IConsoleHost host, string output)
 {
     if (string.IsNullOrEmpty(Output))
         host.WriteMessage(output);
     else
     {
         File.WriteAllText(Output, output, Encoding.UTF8);
         host.WriteMessage("Client code successfully written to file.");
     }
 }
예제 #12
0
        /// <summary>
        /// Read the command name using console host if it was not provided by call.
        /// </summary>
        /// <returns>Command name input by user</returns>
        private string ReadCommandNameInteractive()
        {
            _consoleHost.WriteMessage("Commands: \n");
            foreach (var command in Commands)
            {
                _consoleHost.WriteMessage("  " + command.Key + "\n");
            }

            return(_consoleHost.ReadValue("Command: "));
        }
예제 #13
0
        private async Task ExecuteDocumentAsync(IConsoleHost host, string filePath)
        {
            host.WriteMessage("\nExecuting file '" + filePath + "'...\n");

            var document = await LoadDocumentAsync(filePath);

            await document.ExecuteAsync();

            host.WriteMessage("Done.\n");
        }
예제 #14
0
        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            //Connect and create users collection for LiteDB.org
            //LiteDB connection
            LiteDatabase db = new LiteDatabase(@"UsersObjects.db");

            //Get users collection
            var col = db.GetCollection <Users>("users");

            //Create Scrypt Password
            ScryptEncoder encoder         = new ScryptEncoder();
            string        hashsedPassword = encoder.Encode(SecondValue);

            if (col.Count() == 0)
            {
                // Create your new customer instance
                var user = new Users
                {
                    UserName     = FirstValue,
                    UserPassword = hashsedPassword,
                    IsActive     = true
                };

                // Create unique index in Name field
                col.EnsureIndex(x => x.UserName, true);

                // Insert new customer document (Id will be auto-incremented)
                col.Insert(user);
                ShowInfo(host, hashsedPassword);
            }
            else
            {
                // Create your new customer instance
                var user = new Users
                {
                    UserName     = FirstValue,
                    UserPassword = hashsedPassword,
                    IsActive     = true
                };

                // Insert new customer document (Id will be auto-incremented)
                try
                {
                    col.Insert(user);
                    ShowInfo(host, hashsedPassword);
                }
                catch (LiteDB.LiteException e)
                {
                    host.WriteMessage("ERROR: " + e.Message);
                    host.WriteMessage("\n");
                }
            }
            return(null);
        }
예제 #15
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (Version.IndexOf(".") < 0)
            {
                host.WriteError("Version number must include at least two parts \n");
                return(Task.FromResult <object>(null));
            }

            bool isReplaceOnly = !ACTION_FORCE.Equals(Action, StringComparison.InvariantCultureIgnoreCase);

            var globalProperties = TryGetGlobalProperties();

            foreach (var projectPath in GetProjectPaths())
            {
                try
                {
                    using (var projectInformation = ProjectExtensions.LoadProject(projectPath, globalProperties))
                    {
                        bool projectHasVersion       = projectInformation.Project.HasVersion();
                        bool projectGeneratesPackage = projectInformation.Project.GeneratesPackage();

                        if (projectGeneratesPackage && (projectHasVersion || !isReplaceOnly))
                        {
                            var versions = ChangeVersion(projectInformation.Project, "Version");

                            if (!versions.Item1.Equals(versions.Item2))
                            {
                                host.WriteMessage($"[x] {(projectHasVersion ? "Replaced" : "Set")} version of {System.IO.Path.GetFileName(projectPath)}" +
                                                  " from " + versions.Item2 +
                                                  " to " + versions.Item1 + "\n");

                                if (!Simulate)
                                {
                                    projectInformation.Project.Save();
                                }
                            }
                            else
                            {
                                host.WriteMessage($"[ ] Skipping {System.IO.Path.GetFileName(projectPath)} is already set to {versions.Item1}\n");
                            }
                        }
                        else
                        {
                            host.WriteMessage($"[ ] Ignoring {System.IO.Path.GetFileName(projectPath)}: {( !projectGeneratesPackage ? "Not GeneratePackageOnBuild" : "No version in Project")}\n");
                        }
                    }
                }
                catch (Exception e)
                {
                    host.WriteError(e + "\n");
                }
            }

            return(Task.FromResult <object>(null));
        }
예제 #16
0
 protected void WriteOutput(IConsoleHost host, string output)
 {
     if (string.IsNullOrEmpty(OutputFilePath))
     {
         host.WriteMessage(output);
     }
     else
     {
         File.WriteAllText(OutputFilePath, output, Encoding.UTF8);
         host.WriteMessage("Code has been successfully written to file.\n");
     }
 }
예제 #17
0
        public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (!DynamicApis.FileExists("nswag.json"))
            {
                await CreateDocumentAsync("nswag.json");
                host.WriteMessage("nswag.json file created.");
            }
            else
                host.WriteMessage("nswag.json already exists.");

            return null; 
        }
예제 #18
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var globalProperties = TryGetGlobalProperties();

            foreach (var projectPath in GetProjectPaths())
            {
                try
                {
                    using (var projectInformation = ProjectExtensions.LoadProject(projectPath, globalProperties))
                    {
                        var project = projectInformation.Project;

                        var result = false;
                        switch (Action)
                        {
                        case "warnaserror":
                            result = EnableBooleanProperty(project, "TreatWarningsAsErrors");
                            break;

                        case "xmldocs":
                            result = EnableXmlDocs(project);
                            break;

                        default:
                            throw new ArgumentException("The feature " + Action + " is not available.");
                        }

                        if (result)
                        {
                            host.WriteMessage("[x] Enabled feature " + Action + " in project " + System.IO.Path.GetFileName(projectPath) + "\n");

                            if (!Simulate)
                            {
                                project.Save();
                            }
                        }
                        else
                        {
                            host.WriteMessage("[ ] Feature " + Action + " already enabled in project " + System.IO.Path.GetFileName(projectPath) + "\n");
                        }
                    }
                }
                catch (Exception e)
                {
                    host.WriteError(e + "\n");
                }
            }

            return(Task.FromResult <object>(null));
        }
예제 #19
0
        private void PrintCommand(IConsoleHost host, KeyValuePair<string, Type> pair)
        {
            var commandType = pair.Value;

            host.WriteMessage("---------------------\n");
            host.WriteMessage("Command: ");
            host.WriteMessage(pair.Key + "\n");

            var descriptionAttribute = commandType.GetCustomAttribute<DescriptionAttribute>();
            if (descriptionAttribute != null)
                host.WriteMessage("  " + descriptionAttribute.Description + "\n");

            host.WriteMessage("\nArguments: \n");
            foreach (var property in commandType.GetRuntimeProperties())
            {
                var argumentAttribute = property.GetCustomAttribute<ArgumentAttribute>();
                if (argumentAttribute != null)
                {
                    if (argumentAttribute.Position > 0)
                        host.WriteMessage("  Argument Position " + argumentAttribute.Position + "\n");
                    else
                        host.WriteMessage("  " + argumentAttribute.Name.ToLowerInvariant() + "\n");

                    var parameterDescriptionAttribute = property.GetCustomAttribute<DescriptionAttribute>();
                    if (parameterDescriptionAttribute != null)
                        host.WriteMessage("    " + parameterDescriptionAttribute.Description + "\n");
                }
            }
        }
예제 #20
0
        private void LoadProjects(IConsoleHost host, List <PackageReferenceInfo> packages)
        {
            host.WriteMessage($"Loading projects ");

            var globalProperties = TryGetGlobalProperties();

            foreach (var projectPath in GetProjectPaths())
            {
                try
                {
                    using (var projectInformation = ProjectExtensions.LoadProject(projectPath, globalProperties))
                    {
                        foreach (var item in projectInformation.Project.Items.Where(i => i.ItemType == "PackageReference").ToList())
                        {
                            var packageName    = item.EvaluatedInclude;
                            var packageVersion = item.Metadata.SingleOrDefault(m => m.Name == "Version")?.EvaluatedValue ?? "Latest";

                            if (packageName != "NETStandard.Library" &&
                                (!ExcludeSystem || !packageName.StartsWith("System.")) &&
                                (!ExcludeMicrosoft || !packageName.StartsWith("Microsoft.")))
                            {
                                var entry = packages.SingleOrDefault(p => p.Name == packageName &&
                                                                     p.Version == packageVersion);

                                if (entry == null)
                                {
                                    entry = new PackageReferenceInfo {
                                        Name = packageName, Version = packageVersion, Type = "t"
                                    };
                                    packages.Add(entry);
                                }
                                else
                                {
                                    entry.Count++;
                                }

                                host.WriteMessage(".");
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    host.WriteError(e + "\n");
                }
            }

            host.WriteMessage($"\n");
        }
예제 #21
0
        public async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (await DynamicApis.FileExistsAsync("nswag.json").ConfigureAwait(false) == false)
            {
                await CreateDocumentAsync("nswag.json");

                host.WriteMessage("nswag.json file created.");
            }
            else
            {
                host.WriteMessage("nswag.json already exists.");
            }

            return(null);
        }
예제 #22
0
        /// <summary>Gets the name of the command to execute.</summary>
        /// <param name="args">The arguments.</param>
        /// <returns>The command name.</returns>
        protected string GetCommandName(string[] args)
        {
            if (args.Length == 0 || args[0].Length == 0 || !char.IsLetter(args[0][0]))
            {
                _consoleHost.WriteMessage("Commands: \n");
                foreach (var command in Commands)
                {
                    _consoleHost.WriteMessage("  " + command.Key + "\n");
                }

                return(_consoleHost.ReadValue("Command: ").ToLowerInvariant());
            }

            return(args[0].ToLowerInvariant());
        }
예제 #23
0
        public async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (!string.IsNullOrEmpty(Input) && !Input.StartsWith("/") && !Input.StartsWith("-"))
            {
                await ExecuteDocumentAsync(host, Input);
            }
            else
            {
                var hasNSwagJson = DynamicApis.FileExists("nswag.json");
                if (hasNSwagJson)
                {
                    await ExecuteDocumentAsync(host, "nswag.json");
                }

                var currentDirectory = DynamicApis.DirectoryGetCurrentDirectory();
                var files            = DynamicApis.DirectoryGetFiles(currentDirectory, "*.nswag");
                if (files.Any())
                {
                    foreach (var file in files)
                    {
                        await ExecuteDocumentAsync(host, file);
                    }
                }
                else if (!hasNSwagJson)
                {
                    host.WriteMessage("Current directory does not contain any .nswag files.");
                }
            }
            return(null);
        }
예제 #24
0
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var packages = new List <PackageReferenceInfo>();

            LoadProjects(host, packages);
            await LoadAllDependenciesAsync(packages, host);
            await LoadLicensesAsync(packages, host);

            host.WriteMessage($"{"Package",-85} {"Version",-22} {"Type",-5} {"#",-3} {"License",-15} {"License URL"}\n");
            foreach (var entry in packages.OrderBy(p => p.Name).ThenBy(p => p.Version))
            {
                host.WriteMessage($"{entry.Name,-85} {entry.Version,-22} {entry.Type,-5} {entry.Count,-3} {entry.License,-15} {entry.LicenseUri,-10}\n");
            }

            return(Task.FromResult <object>(null));
        }
예제 #25
0
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            return(await Task.Run(async() =>
            {
                var generator = await CreateGeneratorAsync();
                var classNames = generator.GetExportedClassNames();

                host.WriteMessage("\r\n");
                foreach (var className in classNames)
                {
                    host.WriteMessage(className + "\r\n");
                }
                host.WriteMessage("\r\n");

                return classNames;
            }));
        }
예제 #26
0
        private void PrintCommand(IConsoleHost host, KeyValuePair <string, Type> pair)
        {
            var commandType = pair.Value;

            host.WriteMessage("\nCommand: ");
            host.WriteMessage(pair.Key + "\n");

            var commandAttribute = commandType.GetTypeInfo().GetCustomAttribute <CommandAttribute>();

            if (commandAttribute != null && !string.IsNullOrEmpty(commandAttribute.Description))
            {
                host.WriteMessage("  " + commandAttribute.Description + "\n");
            }
            else
            {
                dynamic descriptionAttribute = commandType.GetTypeInfo().GetCustomAttributes().SingleOrDefault(a => a.GetType().Name == "DescriptionAttribute");
                if (descriptionAttribute != null)
                {
                    host.WriteMessage("  " + descriptionAttribute.Description + "\n");
                }
            }

            host.WriteMessage("\nArguments: \n");
            foreach (var property in commandType.GetRuntimeProperties())
            {
                var argumentAttribute = property.GetCustomAttribute <ArgumentAttribute>();
                if (argumentAttribute != null && !string.IsNullOrEmpty(argumentAttribute.Name))
                {
                    if (argumentAttribute.Position > 0)
                    {
                        host.WriteMessage("  Argument Position " + argumentAttribute.Position + "\n");
                    }
                    else
                    {
                        host.WriteMessage("  " + argumentAttribute.Name + "\n");
                    }

                    if (!string.IsNullOrEmpty(argumentAttribute.Description))
                    {
                        host.WriteMessage("    " + argumentAttribute.Description + "\n");
                    }

                    dynamic parameterDescriptionAttribute = property.GetCustomAttributes().SingleOrDefault(a => a.GetType().Name == "DescriptionAttribute");
                    if (parameterDescriptionAttribute != null)
                    {
                        host.WriteMessage("    " + parameterDescriptionAttribute.Description + "\n");
                    }
                }
            }
        }
예제 #27
0
        private async Task LoadLicensesAsync(List <PackageReferenceInfo> packages, IConsoleHost host)
        {
            var resource = await CreatePackageMetadataResourceAsync();

            host.WriteMessage($"Loading licenses ");

            var httpClient = new HttpClient();
            var tasks      = new List <Task>();

            foreach (var entry in packages.ToList())
            {
                tasks.Add(LoadLicenseAsync(httpClient, entry, host));
            }

            await Task.WhenAll(tasks);

            host.WriteMessage($"\n\n");
        }
예제 #28
0
        private void SwitchToPackages(IConsoleHost host, ReferenceSwitcherConfiguration configuration)
        {
            var solution = SolutionFile.Parse(configuration.ActualSolution);

            foreach (var mapping in configuration.Mappings)
            {
                var projectPath    = mapping.Value.ActualPath;
                var packageName    = mapping.Key;
                var packageVersion = mapping.Value.Version;

                var switchedProjects = SwitchToPackage(solution, projectPath, packageName, packageVersion, host);
                foreach (var s in switchedProjects)
                {
                    host.WriteMessage(Path.GetFileName(s) + ": \n");
                    host.WriteMessage("   " + Path.GetFileName(projectPath) + " => " + packageName + " v" + packageVersion + "\n");
                }
            }
        }
예제 #29
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            foreach (var projectPath in GetProjectPaths())
            {
                ConsoleUtilities.WriteColor(System.IO.Path.GetFileName(projectPath) + ":\n", ConsoleColor.Green);
                host.WriteMessage(projectPath.Replace(Directory.GetCurrentDirectory(), "") + "\n");
            }

            return(Task.FromResult <object>(null));
        }
예제 #30
0
        public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            var globalProperties = TryGetGlobalProperties();

            foreach (var projectPath in GetProjectPaths())
            {
                try
                {
                    using (var projectInformation = ProjectExtensions.LoadProject(projectPath, globalProperties))
                    {
                        var project = projectInformation.Project;

                        foreach (var diagnosticsId in DiagnosticsIds.Split(';'))
                        {
                            var noWarnItem = project.Properties.FirstOrDefault(i => i.Name.ToLowerInvariant() == "nowarn");
                            if (noWarnItem == null || noWarnItem.IsImported)
                            {
                                noWarnItem = project.SetProperty("NoWarn", diagnosticsId);
                                host.WriteMessage($"[x] Added no warn '{diagnosticsId}' tag to project " + System.IO.Path.GetFileName(projectPath) + "\n");
                            }
                            else if (!noWarnItem.EvaluatedValue.Split(';').Contains(diagnosticsId))
                            {
                                noWarnItem.UnevaluatedValue = noWarnItem.EvaluatedValue + ";" + diagnosticsId;
                                host.WriteMessage($"[x] Added no warn '{diagnosticsId}' to existing tag to project " + System.IO.Path.GetFileName(projectPath) + "\n");
                            }
                            else
                            {
                                host.WriteMessage($"[ ] No warn '{diagnosticsId}' already exists in project " + System.IO.Path.GetFileName(projectPath) + "\n");
                            }
                        }

                        ProjectExtensions.SaveWithLineEndings(projectInformation);
                    }
                }
                catch (Exception e)
                {
                    host.WriteError(e + "\n");
                }
            }

            return(Task.FromResult <object>(null));
        }
예제 #31
0
        private static void SwitchToPackages(IConsoleHost host, ReferenceSwitcherConfiguration configuration)
        {
            var solution               = SolutionFile.Parse(configuration.ActualSolution);
            var globalProperties       = ProjectExtensions.GetGlobalProperties(Path.GetFullPath(configuration.ActualSolution));
            var mappedProjectFilePaths = configuration.Mappings.Values
                                         .SelectMany(x => x)
                                         .Select(p => Path.GetFileName(p))
                                         .ToList();

            foreach (var solutionProject in solution.ProjectsInOrder)
            {
                if (solutionProject.ProjectType != SolutionProjectType.SolutionFolder &&
                    ProjectExtensions.IsSupportedProject(solutionProject.AbsolutePath))
                {
                    try
                    {
                        using (var projectInformation = ProjectExtensions.LoadProject(solutionProject.AbsolutePath, globalProperties))
                        {
                            foreach (var mapping in configuration.Mappings)
                            {
                                var projectPaths = mapping.Value.Select(p => configuration.GetActualPath(p)).ToList();
                                var packageName  = mapping.Key;

                                var switchedProjects = SwitchToPackage(
                                    configuration, solutionProject, projectInformation, projectPaths, packageName, mappedProjectFilePaths, host);

                                if (switchedProjects.Count > 0)
                                {
                                    host.WriteMessage("Project " + solutionProject.ProjectName + " with project references:\n");
                                    projectPaths.ForEach(p => host.WriteMessage("    " + Path.GetFileName(p) + "\n"));
                                    host.WriteMessage("    replaced by package: " + packageName + " v" + switchedProjects.First().PackageVersion + "\n");
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        host.WriteError($"The project '{solutionProject.AbsolutePath}' could not be loaded: {e}\n");
                    }
                }
            }
        }
예제 #32
0
        protected void WriteOutput(IConsoleHost host, string output)
        {
            if (string.IsNullOrEmpty(OutputFilePath))
            {
                host.WriteMessage(output);
            }
            else
            {
                var file      = new FileInfo(OutputFilePath);
                var directory = file.Directory;

                if (!directory.Exists)
                {
                    directory.Create();
                }

                File.WriteAllText(OutputFilePath, output, Encoding.UTF8);
                host.WriteMessage("Code has been successfully written to file.\n");
            }
        }
예제 #33
0
 protected async Task ExecuteCommandAsync(string command, string arguments, IConsoleHost host)
 {
     if (Simulate)
     {
         host.WriteMessage("SIMULATE " + command);
     }
     else
     {
         await ProcessUtilities.ExecuteAsync(command, arguments, Verbose);
     }
 }
예제 #34
0
        /// <summary>Processes the command line arguments.</summary>
        /// <param name="args">The arguments.</param>
        /// <returns>The result.</returns>
        public int Process(string[] args)
        {
            _host.WriteMessage("toolchain v" + SwaggerDocument.ToolchainVersion +
                               " (NJsonSchema v" + JsonSchema4.ToolchainVersion + ")\n");
            _host.WriteMessage("Visit http://NSwag.org for more information.\n");

            WriteBinDirectory();

            if (args.Length == 0)
            {
                _host.WriteMessage("Execute the 'help' command to show a list of all the available commands.\n");
            }

            try
            {
                var processor = new CommandLineProcessor(_host);

                processor.RegisterCommandsFromAssembly(typeof(SwaggerToCSharpControllerCommand).GetTypeInfo().Assembly);

                var stopwatch = new Stopwatch();
                stopwatch.Start();
                processor.Process(args);
                stopwatch.Stop();

                _host.WriteMessage("\nDuration: " + stopwatch.Elapsed + "\n");
            }
            catch (Exception exception)
            {
                _host.WriteError(exception.ToString());
                return(-1);
            }

            WaitWhenDebuggerAttached();
            return(0);
        }
예제 #35
0
        public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            if (!string.IsNullOrEmpty(Input))
                await ExecuteDocumentAsync(host, Input);
            else
            {
                if (DynamicApis.FileExists("nswag.json"))
                    await ExecuteDocumentAsync(host, "nswag.json");

                var files = DynamicApis.DirectoryGetFiles(DynamicApis.DirectoryGetCurrentDirectory(), "*.nswag");
                if (files.Any())
                {
                    foreach (var file in files)
                        await ExecuteDocumentAsync(host, file);
                }
                else
                    host.WriteMessage("Current directory does not contain any .nswag files.");
            }
            return null; 
        }
예제 #36
0
        private void PrintCommand(IConsoleHost host, KeyValuePair<string, Type> pair)
        {
            var commandType = pair.Value;

            host.WriteMessage("\n");
            host.WriteMessage("USAGE\n");
            host.WriteMessage("=====\n");
            host.WriteMessage("myapp.exe myCommand /myParameter:myValue /mySecondParameter:myValue\n\n\n");

            host.WriteMessage("AVAILABLE COMMANDS\n");
            host.WriteMessage("==================\n\n");
            host.WriteMessage("Command: ");
            host.WriteMessage(pair.Key + "\n");

            var commandAttribute = commandType.GetTypeInfo().GetCustomAttribute<CommandAttribute>();
            if (commandAttribute != null && !string.IsNullOrEmpty(commandAttribute.Description))
                host.WriteMessage("  " + commandAttribute.Description + "\n");
            else
            {
                dynamic descriptionAttribute = commandType.GetTypeInfo().GetCustomAttributes().SingleOrDefault(a => a.GetType().Name == "DescriptionAttribute");
                if (descriptionAttribute != null)
                    host.WriteMessage("  " + descriptionAttribute.Description + "\n");
            }

            host.WriteMessage("\nArguments: \n");
            foreach (var property in commandType.GetRuntimeProperties())
            {
                var argumentAttribute = property.GetCustomAttribute<ArgumentAttribute>();
                if (argumentAttribute != null && !string.IsNullOrEmpty(argumentAttribute.Name))
                {
                    if (argumentAttribute.Position > 0)
                        host.WriteMessage("  Argument Position " + argumentAttribute.Position + "\n");
                    else
                        host.WriteMessage("  " + argumentAttribute.Name + "\n");

                    if (!string.IsNullOrEmpty(argumentAttribute.Description))
                        host.WriteMessage("    " + argumentAttribute.Description + "\n");

                    dynamic parameterDescriptionAttribute = property.GetCustomAttributes().SingleOrDefault(a => a.GetType().Name == "DescriptionAttribute");
                    if (parameterDescriptionAttribute != null)
                        host.WriteMessage("    " + parameterDescriptionAttribute.Description + "\n");
                }
            }
        }
예제 #37
0
 /// <summary>Runs the command.</summary>
 /// <param name="processor">The processor.</param>
 /// <param name="host">The host.</param>
 /// <returns>The output.</returns>
 public Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
 {
     host.WriteMessage("\nNSwag version: " + SwaggerDocument.ToolchainVersion + "\n");
     host.WriteMessage("NJsonSchema version: " + JsonSchema4.ToolchainVersion + "\n");
     return Task.FromResult<object>(null);
 }
예제 #38
0
 public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
 {
     host.WriteMessage(string.Format("Clone {{ Repository={0}, Quiet={1} }}", Repository, Quiet));
     return null; 
 }