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)); }
public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host) { var globalProperties = TryGetGlobalProperties(); var projects = GetProjectPaths().Select(p => ProjectExtensions.LoadProject(p, globalProperties)).ToList(); var projectNames = projects.Select(p => System.IO.Path.GetFileNameWithoutExtension(p.Project.FullPath)); foreach (var project in projects.Select(p => p.Project)) { try { using (var projectInformation = ProjectExtensions.LoadProject(project.FullPath, globalProperties)) { var newProjectsToReference = new List <Project>(); var assemblyReferencesToRemove = new List <ProjectItem>(); foreach (var reference in projectInformation.Project.Items .Where(r => r.ItemType == "Reference" && projectNames.Contains(r.UnevaluatedInclude.Split(',').First()))) { assemblyReferencesToRemove.Add(reference); var projectToReference = projects.First(p => System.IO.Path.GetFileNameWithoutExtension(p.Project.FullPath) == reference.EvaluatedInclude.Split(',').First()); newProjectsToReference.Add(projectToReference.Project); } foreach (var item in assemblyReferencesToRemove) { projectInformation.Project.RemoveItem(item); } foreach (var projectToReference in newProjectsToReference) { var refProjectDirectory = System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(projectToReference.FullPath)); var relativePath = PathUtilities.ToRelativePath(refProjectDirectory, System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(project.FullPath))); var path = System.IO.Path.Combine(relativePath, System.IO.Path.GetFileName(projectToReference.FullPath)); var metaData = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("Name", System.IO.Path.GetFileNameWithoutExtension(projectToReference.FullPath)) }; projectInformation.Project.AddItem("ProjectReference", path, metaData); } projectInformation.Project.Save(); } } catch (Exception e) { host.WriteError($"The project '{project.FullPath}' could not be loaded: {e}\n"); } } foreach (var project in projects) { project.Dispose(); } return(Task.FromResult <object>(null)); }
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)); }
public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host) { var version = Version; if (!string.IsNullOrWhiteSpace(version)) { if (EnforceRanges) { var segments = Version.Split('.'); version = segments.Length == 2 && segments[1] == "*" ? "[" + segments[0] + "," + (int.Parse(segments[0]) + 1) + ")" : segments.Length == 3 && segments[2] == "*" ? "[" + segments[0] + "." + segments[1] + "," + segments[0] + "," + (int.Parse(segments[1]) + 1) + ")" : Version; } version = " -v " + version; } await Task.WhenAll(GetProjectPaths() .Select(projectPath => Task.Run(async() => { try { await ExecuteCommandAsync("dotnet add \"" + projectPath + "\" package " + Package + version, host); } catch (Exception e) { host.WriteError(e + "\n"); } }))); return(null); }
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)); }
/// <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); }
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"); } } } }
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); } } }
/// <summary>Processes the command in the given command line arguments.</summary> /// <param name="args">The arguments.</param> /// <param name="input">The output from the previous command.</param> /// <returns>The exeucuted command.</returns> public IList <CommandResult> ProcessWithExceptionHandling(string[] args, object input = null) { try { return(ProcessAsync(args, input).GetAwaiter().GetResult()); } catch (Exception e) { _consoleHost.WriteError(e.ToString()); return(null); } }
private async Task LoadDependenciesAsync(PackageReferenceInfo entry, List <PackageReferenceInfo> packages, List <Task> tasks, IConsoleHost host) { var resource = await CreatePackageMetadataResourceAsync(); try { var identity = new PackageIdentity(entry.Name, NuGetVersion.Parse(entry.Version)); var result = await resource.GetMetadataAsync(identity, new NullLogger(), CancellationToken.None); if (result != null) { entry.LicenseUri = result.LicenseUrl; if (IncludeTransitiveDependencies) { foreach (var dependentPackage in result.DependencySets.SelectMany(s => s.Packages)) { lock (packages) { if (dependentPackage.Id != "NETStandard.Library" && (!ExcludeSystem || !dependentPackage.Id.StartsWith("System.")) && (!ExcludeMicrosoft || !dependentPackage.Id.StartsWith("Microsoft."))) { var subEntry = packages.SingleOrDefault(p => p.Name == dependentPackage.Id && p.Version == dependentPackage.VersionRange.MinVersion.ToFullString()); if (subEntry == null) { var package = new PackageReferenceInfo { Name = dependentPackage.Id, Version = dependentPackage.VersionRange.MinVersion.ToFullString() }; packages.Add(package); tasks.Add(LoadDependenciesAsync(package, packages, tasks, host)); } else { subEntry.Count++; } } } } } } host.WriteMessage("."); } catch (Exception e) { host.WriteError(e + "\n"); } }
public static ReferenceSwitcherConfiguration Load(string fileName, IConsoleHost host) { if (!File.Exists(fileName)) { host.WriteError($"File '{fileName}' not found."); return(null); } var c = JsonConvert.DeserializeObject <ReferenceSwitcherConfiguration>(File.ReadAllText(fileName)); c.Path = PathUtilities.ToAbsolutePath(fileName, Directory.GetCurrentDirectory()); return(c); }
private static void ReplaceAssemblyReferencesWithProjects(ProjectCollection projects, IConsoleHost host) { var projectNames = projects.LoadedProjects.Select(p => System.IO.Path.GetFileNameWithoutExtension(p.FullPath)); foreach (var project in projects.LoadedProjects) { try { using (var projectInformation = ProjectExtensions.LoadProject(project.FullPath)) { var newProjectsToReference = new List <Project>(); var assemblyReferencesToRemove = new List <ProjectItem>(); foreach (var reference in projectInformation.Project.Items .Where(r => r.ItemType == "Reference" && projectNames.Contains(r.UnevaluatedInclude.Split(',').First()))) { assemblyReferencesToRemove.Add(reference); var projectToReference = projects.LoadedProjects.First(p => System.IO.Path.GetFileNameWithoutExtension(p.FullPath) == reference.EvaluatedInclude.Split(',').First()); newProjectsToReference.Add(projectToReference); } foreach (var item in assemblyReferencesToRemove) { projectInformation.Project.RemoveItem(item); } foreach (var projectToReference in newProjectsToReference) { var refProjectDirectory = System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(projectToReference.FullPath)); var relativePath = PathUtilities.ToRelativePath(refProjectDirectory, System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(project.FullPath))); var path = System.IO.Path.Combine(relativePath, System.IO.Path.GetFileName(projectToReference.FullPath)); var metaData = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("Name", System.IO.Path.GetFileNameWithoutExtension(projectToReference.FullPath)) }; projectInformation.Project.AddItem("ProjectReference", path, metaData); } projectInformation.Project.Save(); } } catch (Exception e) { host.WriteError("The project '" + project.FullPath + "' could not be loaded: " + e.Message + "\n"); } } }
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)); }
/// <summary>Processes the command line arguments.</summary> /// <param name="args">The arguments.</param> /// <returns>The result.</returns> public int Process(string[] args) { var architecture = IntPtr.Size == 4 ? " (x86)" : " (x64)"; _host.WriteMessage("toolchain v" + SwaggerDocument.ToolchainVersion + " (NJsonSchema v" + JsonSchema4.ToolchainVersion + ")" + architecture + "\n"); _host.WriteMessage("Visit http://NSwag.org for more information.\n"); var binDirectory = DynamicApis.PathGetDirectoryName(((dynamic)typeof(NSwagCommandProcessor).GetTypeInfo().Assembly).CodeBase.Replace("file:///", string.Empty)); _host.WriteMessage("NSwag bin directory: " + binDirectory + "\n"); 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(_assemblyLoaderAssembly); processor.RegisterCommandsFromAssembly(typeof(SwaggerToCSharpControllerCommand).GetTypeInfo().Assembly); var stopwatch = new Stopwatch(); stopwatch.Start(); var results = processor.Process(args); stopwatch.Stop(); var output = results.Last()?.Output; var document = output as SwaggerDocument; if (document != null) { _host.WriteMessage(document.ToJson()); } else if (output != null) { _host.WriteMessage(output.ToString()); } _host.WriteMessage("\nDuration: " + stopwatch.Elapsed); } catch (Exception exception) { _host.WriteError(exception.ToString()); return(-1); } WaitWhenDebuggerAttached(); return(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"); }
private IReadOnlyList <string> SwitchToPackage(SolutionFile solution, string projectPath, string packageName, string packageVersion, IConsoleHost host) { var switchedProjects = new List <string>(); var absoluteProjectPath = PathUtilities.ToAbsolutePath(projectPath, Directory.GetCurrentDirectory()); foreach (var solutionProject in solution.ProjectsInOrder) { if (solutionProject.ProjectType != SolutionProjectType.SolutionFolder && solutionProject.AbsolutePath.EndsWith(".csproj")) { try { using (var collection = new ProjectCollection()) { var project = collection.LoadProject(solutionProject.AbsolutePath); var projectDirectory = Path.GetDirectoryName(solutionProject.AbsolutePath); var count = 0; foreach (var item in project.Items.Where(i => i.ItemType == "ProjectReference").ToList()) { var absoluteProjectReferencePath = PathUtilities.ToAbsolutePath(item.EvaluatedInclude, projectDirectory); if (absoluteProjectReferencePath == absoluteProjectPath) { project.RemoveItem(item); project.AddItem("PackageReference", packageName, new[] { new KeyValuePair <string, string>("Version", packageVersion) }); switchedProjects.Add(solutionProject.AbsolutePath); count++; } } if (count > 0) { project.Save(); } } } catch (Exception e) { host.WriteError("The project '" + solutionProject.AbsolutePath + "' could not be loaded: " + e.Message + "\n"); } } } return(switchedProjects); }
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)); }
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"); } } } }
private IReadOnlyDictionary <string, string> SwitchToProject(SolutionFile solution, string packageName, string projectPath, IConsoleHost host) { var switchedProjects = new Dictionary <string, string>(); foreach (var solutionProject in solution.ProjectsInOrder) { if (solutionProject.ProjectType != SolutionProjectType.SolutionFolder) { try { using (var collection = new ProjectCollection()) { var project = collection.LoadProject(solutionProject.AbsolutePath); var projectDirectory = Path.GetFullPath(Path.GetDirectoryName(solutionProject.AbsolutePath)); foreach (var item in project.Items.Where(i => i.ItemType == "PackageReference").ToList()) { var packageReference = item.EvaluatedInclude; if (packageReference == packageName) { project.RemoveItem(item); project.AddItem("ProjectReference", PathUtilities.ToRelativePath(projectPath, projectDirectory)); var version = item.Metadata.SingleOrDefault(m => m.Name == "Version")?.EvaluatedValue ?? "Any"; switchedProjects[solutionProject.AbsolutePath] = version; } } project.Save(); } } catch (Exception e) { host.WriteError("The project '" + solutionProject.AbsolutePath + "' could not be loaded: " + e.Message + "\n"); } } } return(switchedProjects); }
private static void SwitchToPackages(IConsoleHost host, ReferenceSwitcherConfiguration configuration) { var solution = SolutionFile.Parse(configuration.ActualSolution); var mappedProjectFilePaths = configuration.Mappings.Select(m => Path.GetFileName(m.Value)).ToList(); foreach (var solutionProject in solution.ProjectsInOrder) { if (solutionProject.ProjectType != SolutionProjectType.SolutionFolder && ProjectExtensions.IsSupportedProject(solutionProject.AbsolutePath)) { try { using (var projectInformation = ProjectExtensions.LoadProject(solutionProject.AbsolutePath)) { foreach (var mapping in configuration.Mappings) { var projectPath = configuration.GetActualPath(mapping.Value); var packageName = mapping.Key; var switchedProjects = SwitchToPackage( configuration, solutionProject, projectInformation, projectPath, packageName, mappedProjectFilePaths, host); foreach (var s in switchedProjects) { host.WriteMessage(Path.GetFileName(s.ProjectPath) + ": \n"); host.WriteMessage(" " + Path.GetFileName(projectPath) + " => " + packageName + " v" + s.PackageVersion + "\n"); } } } } catch (Exception e) { host.WriteError("The project '" + solutionProject.AbsolutePath + "' could not be loaded: " + e.Message + "\n"); } } } }
private async Task UpgradeProjectPackagesAsync(ProjectCollection projectCollection, IConsoleHost host, string projectPath, Regex packageRegex, string version) { try { var project = projectCollection.LoadProject(projectPath); var packages = project.Items .Where(i => i.ItemType == "PackageReference" && packageRegex.IsMatch(i.EvaluatedInclude) && i.EvaluatedInclude != "Microsoft.NETCore.App") .Select(i => i.EvaluatedInclude) .ToList(); foreach (var package in packages) { await ExecuteCommandAsync("dotnet add \"" + projectPath + "\" package \"" + package + "\"" + (version != null ? " -v " + version : ""), host); } } catch (Exception e) { host.WriteError(e + "\n"); } }
private async Task UpgradeProjectPackagesAsync(IConsoleHost host, string projectPath, Regex packageRegex, string version, IDictionary <string, string> globalProperties) { try { using (var projectInformation = ProjectExtensions.LoadProject(projectPath, globalProperties)) { var packages = projectInformation.Project.Items .Where(i => i.ItemType == "PackageReference" && packageRegex.IsMatch(i.EvaluatedInclude) && i.EvaluatedInclude != "Microsoft.NETCore.App") .Select(i => i.EvaluatedInclude) .ToList(); foreach (var package in packages) { await ExecuteCommandAsync("dotnet", "add \"" + projectPath + "\" package \"" + package + "\"" + (version != null ? " -v " + version : ""), host); } } } catch (Exception e) { host.WriteError(e + "\n"); } }
public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host) { if (string.IsNullOrEmpty(TargetFramework)) { return(Task.FromResult <object>(null)); } var collection = new ProjectCollection(); foreach (var projectPath in GetProjectPaths()) { try { var project = collection.LoadProject(projectPath); ProjectProperty targetFrameworksProperty = null; List <string> targetFrameworks = null; var targetFrameworkProperty = project.GetProperty("TargetFramework"); if (targetFrameworkProperty != null) { var value = targetFrameworkProperty.EvaluatedValue; if (!string.IsNullOrEmpty(value)) { targetFrameworks = new List <string> { targetFrameworkProperty.EvaluatedValue }; } project.RemoveProperty(targetFrameworkProperty); } else { targetFrameworksProperty = project.GetProperty("TargetFrameworks"); if (targetFrameworksProperty != null) { targetFrameworks = targetFrameworksProperty.EvaluatedValue .Split(';') .Where(f => !string.IsNullOrEmpty(f)) .ToList(); } } if (targetFrameworks != null) { if (!targetFrameworks.Contains(TargetFramework)) { targetFrameworks.Add(TargetFramework); if (targetFrameworksProperty != null) { targetFrameworksProperty.UnevaluatedValue = string.Join(";", targetFrameworks); } else { project.SetProperty("TargetFrameworks", string.Join(";", targetFrameworks)); } host.WriteMessage("[x] Added target framework " + TargetFramework + " to " + System.IO.Path.GetFileName(projectPath) + "\n"); } else { host.WriteMessage("[ ] Target framework " + TargetFramework + " already in project " + System.IO.Path.GetFileName(projectPath) + "\n"); } } else { host.WriteMessage("[ ] Could not add target framework " + TargetFramework + " to " + System.IO.Path.GetFileName(projectPath) + "\n"); } project.Save(); collection.UnloadProject(project); } catch (Exception e) { host.WriteError(e + "\n"); } } return(Task.FromResult <object>(null)); }
private static async Task LoadLicenseAsync(HttpClient httpClient, PackageReferenceInfo entry, IConsoleHost host) { try { if (entry.LicenseUri != null) { var licenseUri = entry.LicenseUri?.ToString(); if (licenseUri?.Contains("apache.org") == true) { entry.License = "Apache"; } if (licenseUri?.Contains("/LGPL-") == true) { entry.License = "LGPL"; } if (licenseUri?.Contains("/GPL-") == true) { entry.License = "GPL"; } else { var license = await httpClient.GetStringAsync(entry.LicenseUri); if (license.Contains("www.apache.org")) { entry.License = "Apache"; } else if (license.Contains("Lesser General Public License")) { entry.License = "LGPL"; } else if (license.Contains("General Public License")) { entry.License = "GPL"; } else { var n = ""; n = string.IsNullOrWhiteSpace(n) ? Regex.Matches(license, "^\\s*([^><*]{1,20}[a-zA-Z] License)", RegexOptions.Multiline) .OfType <Match>().FirstOrDefault(m => !m.Groups[1].Value.Contains("the License"))?.Groups[1].Value : n; n = string.IsNullOrWhiteSpace(n) ? Regex.Matches(license, ">\\s*([^><*]{1,20}[a-zA-Z] License)", RegexOptions.Multiline) .OfType <Match>().FirstOrDefault(m => !m.Groups[1].Value.Contains("the License"))?.Groups[1].Value : n; n = string.IsNullOrWhiteSpace(n) ? Regex.Matches(license, "\n\\s*([^><*]{1,20}[a-zA-Z] License)", RegexOptions.Multiline) .OfType <Match>().FirstOrDefault(m => !m.Groups[1].Value.Contains("the License"))?.Groups[1].Value : n; n = n ?? ""; entry.License = n .Trim('\r', '\n', ' ', '?') .Replace("The ", string.Empty) .Replace(" License", string.Empty); } } host.WriteMessage("."); } } catch (Exception e) { host.WriteError(e + "\n"); } }