From f9a30cda7219546604ec7ff801e90bb38ad0d923 Mon Sep 17 00:00:00 2001 From: Gary Ewan Park Date: Mon, 26 Sep 2016 13:34:22 +0100 Subject: [PATCH] (GH-19) First pass at adding StyleCop --- src/Adornments/AdornmentProvider.cs | 53 ++++++------- src/Adornments/LogoAdornment.cs | 7 +- src/Cake.VisualStudio.csproj | 10 +++ src/Cake.VisualStudio.ruleset | 77 +++++++++++++++++++ src/CakePackage.cs | 48 ++++++------ .../CakeClassificationDefinition.cs | 1 - src/Classifier/CakeClassifier.cs | 32 ++++---- src/Classifier/CakeClassifierProvider.cs | 4 - src/Classifier/Languages/BaseLanguage.cs | 9 ++- src/Classifier/Languages/CakeLanguage.cs | 5 +- src/Configuration/BindingParser.cs | 28 ++++++- src/Configuration/ConfigurationExtensions.cs | 26 ++++--- src/Configuration/ConfigurationParser.cs | 7 +- src/Helpers/Extensions.cs | 12 +-- src/Helpers/PathHelpers.cs | 2 + src/Helpers/ProjectHelpers.cs | 64 +++++++++------ src/Menus/InstallConfigFileCommand.cs | 8 +- src/Menus/MenuHelpers.cs | 41 +++++++--- src/TaskRunner/TaskRunner.cs | 46 +++++++++-- src/TaskRunner/TaskRunnerConfig.cs | 60 ++++++++------- src/packages.config | 1 + 21 files changed, 374 insertions(+), 167 deletions(-) create mode 100644 src/Cake.VisualStudio.ruleset diff --git a/src/Adornments/AdornmentProvider.cs b/src/Adornments/AdornmentProvider.cs index f5fa0dc..913b1e0 100644 --- a/src/Adornments/AdornmentProvider.cs +++ b/src/Adornments/AdornmentProvider.cs @@ -21,7 +21,8 @@ class AdornmentProvider : IWpfTextViewCreationListener private const string PropertyName = "ShowWatermark"; private const double InitOpacity = 0.4D; - private static bool _isVisible, _hasLoaded; + private static bool _isVisible; + private static bool _hasLoaded; private SettingsManager _settingsManager; [Import] @@ -30,6 +31,31 @@ class AdornmentProvider : IWpfTextViewCreationListener [Import] public SVsServiceProvider ServiceProvider { get; set; } + public void TextViewCreated(IWpfTextView textView) + { + ITextDocument document; + + if (!TextDocumentFactoryService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out document)) + { + return; + } + + LoadSettings(); + + var fileName = Path.GetFileName(document.FilePath).ToLowerInvariant(); + + // Check if filename is absolute because when debugging, script files are sometimes dynamically created. + if (string.IsNullOrEmpty(fileName) || !Path.IsPathRooted(document.FilePath)) + { + return; + } + + if (fileName.EndsWith(".cake")) + { + textView.Properties.GetOrCreateSingletonProperty(() => new LogoAdornment(textView, _isVisible, InitOpacity)); + } + } + private void LoadSettings() { if (_hasLoaded) @@ -59,30 +85,5 @@ private void AdornmentVisibilityChanged(object sender, bool isVisible) wstore.SetBoolean(Vsix.Name, PropertyName, isVisible); } - - public void TextViewCreated(IWpfTextView textView) - { - ITextDocument document; - - if (!TextDocumentFactoryService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out document)) - { - return; - } - - LoadSettings(); - - var fileName = Path.GetFileName(document.FilePath).ToLowerInvariant(); - - // Check if filename is absolute because when debugging, script files are sometimes dynamically created. - if (string.IsNullOrEmpty(fileName) || !Path.IsPathRooted(document.FilePath)) - { - return; - } - - if (fileName.EndsWith(".cake")) - { - textView.Properties.GetOrCreateSingletonProperty(() => new LogoAdornment(textView, _isVisible, InitOpacity)); - } - } } } \ No newline at end of file diff --git a/src/Adornments/LogoAdornment.cs b/src/Adornments/LogoAdornment.cs index a7784e2..d6a3a8e 100644 --- a/src/Adornments/LogoAdornment.cs +++ b/src/Adornments/LogoAdornment.cs @@ -14,12 +14,13 @@ namespace Cake.VisualStudio.Adornments { class LogoAdornment { + private readonly double _initOpacity; + private IAdornmentLayer _adornmentLayer; private Image _adornment; - private readonly double _initOpacity; private double _currentOpacity; - public LogoAdornment(IWpfTextView view, bool isVisible, double initOpacity) + public LogoAdornment(IWpfTextView view, bool isVisible, double initOpacity) { _adornmentLayer = view.GetAdornmentLayer(AdornmentLayer.LayerName); _currentOpacity = isVisible ? initOpacity : 0; @@ -62,7 +63,7 @@ private static ImageSource GetImage() var folder = Path.GetDirectoryName(assembly); var file = Path.Combine(folder, "Resources\\icon.png"); - var url = new Uri(file, UriKind.Absolute); + var url = new Uri(file, UriKind.Absolute); return BitmapFrame.Create(url); } diff --git a/src/Cake.VisualStudio.csproj b/src/Cake.VisualStudio.csproj index bf95ddd..b5a2a53 100644 --- a/src/Cake.VisualStudio.csproj +++ b/src/Cake.VisualStudio.csproj @@ -61,6 +61,8 @@ DEBUG;TRACE prompt 4 + Cake.VisualStudio.ruleset + bin\Debug\Cake.VisualStudio.XML pdbonly @@ -69,6 +71,8 @@ TRACE prompt 4 + Cake.VisualStudio.ruleset + bin\Release\Cake.VisualStudio.XML $([System.IO.Path]::GetFullPath( $(MSBuildProjectDirectory)\..\packages\TemplateBuilder.1.1.4.5-beta\tools\ligershark.templates.targets )) @@ -146,6 +150,7 @@ Designer + true @@ -433,6 +438,11 @@ TemplateProjectOutputGroup%3b + + + + + False diff --git a/src/Cake.VisualStudio.ruleset b/src/Cake.VisualStudio.ruleset new file mode 100644 index 0000000..f92522a --- /dev/null +++ b/src/Cake.VisualStudio.ruleset @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/CakePackage.cs b/src/CakePackage.cs index 3394404..4ace1cf 100644 --- a/src/CakePackage.cs +++ b/src/CakePackage.cs @@ -25,27 +25,14 @@ namespace Cake.VisualStudio public sealed partial class CakePackage : Package, IVsShellPropertyEvents { private static DTE2 _dte; - internal static DTE2 Dte => _dte ?? (_dte = (DTE2) GetGlobalService(typeof(DTE))); - internal static IVsUIShell Shell => _shell ?? (_shell = (IVsUIShell) GetGlobalService(typeof(IVsUIShell))); - uint _cookie; - private static IVsUIShell _shell; + internal static DTE2 Dte => _dte ?? (_dte = (DTE2)GetGlobalService(typeof(DTE))); - protected override void Initialize() - { - Logger.Initialize(this, Vsix.Name); - base.Initialize(); - var shellService = GetService(typeof(SVsShell)) as IVsShell; + internal static IVsUIShell Shell => _shell ?? (_shell = (IVsUIShell)GetGlobalService(typeof(IVsUIShell))); - if (shellService != null) - { - ErrorHandler.ThrowOnFailure(shellService.AdviseShellPropertyChanges(this, out _cookie)); - } + uint _cookie; - Menus.InstallBootstrapperCommand.Initialize(this); - Menus.InstallShellBootstrapperCommand.Initialize(this); - Menus.InstallConfigFileCommand.Initialize(this); - } + private static IVsUIShell _shell; public static bool IsDocumentDirty(string documentPath, out IVsPersistDocData persistDocData) { @@ -69,20 +56,21 @@ public static bool IsDocumentDirty(string documentPath, out IVsPersistDocData pe public int OnShellPropertyChange(int propid, object var) { // when zombie state changes to false, finish package initialization - if ((int)__VSSPROPID.VSSPROPID_Zombie == propid) + if (propid == (int)__VSSPROPID.VSSPROPID_Zombie) { if ((bool)var == false) { - // zombie state dependent code + //// zombie state dependent code - // Dte = (DTE2)GetService(typeof(DTE)); - // eventlistener no longer needed + //// Dte = (DTE2)GetService(typeof(DTE)); + //// eventlistener no longer needed var shellService = GetService(typeof(SVsShell)) as IVsShell; if (shellService != null) - + { ErrorHandler.ThrowOnFailure(shellService.UnadviseShellPropertyChanges(_cookie)); + } _cookie = 0; } @@ -90,5 +78,21 @@ public int OnShellPropertyChange(int propid, object var) return VSConstants.S_OK; } + + protected override void Initialize() + { + Logger.Initialize(this, Vsix.Name); + base.Initialize(); + var shellService = GetService(typeof(SVsShell)) as IVsShell; + + if (shellService != null) + { + ErrorHandler.ThrowOnFailure(shellService.AdviseShellPropertyChanges(this, out _cookie)); + } + + Menus.InstallBootstrapperCommand.Initialize(this); + Menus.InstallShellBootstrapperCommand.Initialize(this); + Menus.InstallConfigFileCommand.Initialize(this); + } } } \ No newline at end of file diff --git a/src/Classifier/CakeClassificationDefinition.cs b/src/Classifier/CakeClassificationDefinition.cs index 1ac622a..17fcd12 100644 --- a/src/Classifier/CakeClassificationDefinition.cs +++ b/src/Classifier/CakeClassificationDefinition.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; diff --git a/src/Classifier/CakeClassifier.cs b/src/Classifier/CakeClassifier.cs index fded41f..58e2971 100644 --- a/src/Classifier/CakeClassifier.cs +++ b/src/Classifier/CakeClassifier.cs @@ -45,8 +45,6 @@ internal CakeClassifier(IClassificationTypeRegistryService registry) }; } - #region IClassifier - #pragma warning disable 67 /// @@ -79,7 +77,7 @@ public IList GetClassificationSpans(SnapshotSpan span) return result; */ - //create a list to hold the results + // create a list to hold the results List classifications = new List(); var current = span.GetText(); @@ -115,18 +113,24 @@ public IList GetClassificationSpans(SnapshotSpan span) { Classify(classifications, current, span, predefinedType.Key, predefinedType.Value); } - //Classify(classifications, current, span, _brightScriptLanguage.Quoted, - // _stringType); - //Classify(classifications, current, span, _brightScriptLanguage.KeyWords, - // _keywordType); - //Classify(classifications, current, span, _brightScriptLanguage.IdentifierTypes, - // _identifierType); - //Classify(classifications, current, span, _brightScriptLanguage.Numeric, - // _numericType); + + ////Classify(classifications, current, span, _brightScriptLanguage.Quoted, + //// _stringType); + ////Classify(classifications, current, span, _brightScriptLanguage.KeyWords, + //// _keywordType); + ////Classify(classifications, current, span, _brightScriptLanguage.IdentifierTypes, + //// _identifierType); + ////Classify(classifications, current, span, _brightScriptLanguage.Numeric, + //// _numericType); return classifications; } - private void Classify(List classifications, string current, - SnapshotSpan span, List matchList, IClassificationType classificationType) + + private void Classify( + List classifications, + string current, + SnapshotSpan span, + List matchList, + IClassificationType classificationType) { foreach (var item in matchList) { @@ -142,7 +146,5 @@ private void Classify(List classifications, string current, } } } - - #endregion } } \ No newline at end of file diff --git a/src/Classifier/CakeClassifierProvider.cs b/src/Classifier/CakeClassifierProvider.cs index 7e6cd47..4d9daf9 100644 --- a/src/Classifier/CakeClassifierProvider.cs +++ b/src/Classifier/CakeClassifierProvider.cs @@ -29,8 +29,6 @@ internal class CakeClassifierProvider : IClassifierProvider #pragma warning restore 649 - #region IClassifierProvider - /// /// Gets a classifier for the given text buffer. /// @@ -40,7 +38,5 @@ public IClassifier GetClassifier(ITextBuffer buffer) { return buffer.Properties.GetOrCreateSingletonProperty(creator: () => new CakeClassifier(_classificationRegistry)); } - - #endregion } } \ No newline at end of file diff --git a/src/Classifier/Languages/BaseLanguage.cs b/src/Classifier/Languages/BaseLanguage.cs index a3d5611..ec0556c 100644 --- a/src/Classifier/Languages/BaseLanguage.cs +++ b/src/Classifier/Languages/BaseLanguage.cs @@ -8,8 +8,9 @@ namespace Cake.VisualStudio.Classifier.Languages { static class BaseLanguage { - public static List Comments => new List {@"//"}; - public static List Quoted => new List {@"([""'])(?:\\\1|.)*?\1"}; + public static List Comments => new List { @"//" }; + + public static List Quoted => new List { @"([""'])(?:\\\1|.)*?\1" }; public static List Identifiers => @@ -39,10 +40,10 @@ public static List Identifiers }; public static List Operators - => new List {@"\b(new|is|as|using|checked|unchecked|typeof|sizeof|override|readonly|stackalloc)\b"}; + => new List { @"\b(new|is|as|using|checked|unchecked|typeof|sizeof|override|readonly|stackalloc)\b" }; public static List OtherKeywords - => new List {@"\b(event|delegate|fixed|add|remove|set|get|value)\b"}; + => new List { @"\b(event|delegate|fixed|add|remove|set|get|value)\b" }; public static List Linq => diff --git a/src/Classifier/Languages/CakeLanguage.cs b/src/Classifier/Languages/CakeLanguage.cs index d9dc8c9..742d0c7 100644 --- a/src/Classifier/Languages/CakeLanguage.cs +++ b/src/Classifier/Languages/CakeLanguage.cs @@ -9,10 +9,9 @@ namespace Cake.VisualStudio.Classifier.Languages static class CakeLanguage { public static List SpecialKeywords - => new List {@"\bRunTarget\([\w\""]+\)", @"\bSetup\b", @"\bTeardown\b"}; - - public static List Preprocessors => new List {@"^[#]{1}(load|r|addin|tool)"}; + => new List { @"\bRunTarget\([\w\""]+\)", @"\bSetup\b", @"\bTeardown\b" }; + public static List Preprocessors => new List { @"^[#]{1}(load|r|addin|tool)" }; public static List Keywords => diff --git a/src/Configuration/BindingParser.cs b/src/Configuration/BindingParser.cs index ea9bbe6..a031195 100644 --- a/src/Configuration/BindingParser.cs +++ b/src/Configuration/BindingParser.cs @@ -12,18 +12,38 @@ namespace Cake.VisualStudio.Configuration internal class TaskBinding { public IEnumerable BeforeBuild { get; set; } = new List(); + public IEnumerable AfterBuild { get; set; } = new List(); + public IEnumerable Clean { get; set; } = new List(); + public IEnumerable Open { get; set; } = new List(); internal string ToXml() { var sb = new StringBuilder(); sb.Append(""); return sb.ToString(); } diff --git a/src/Configuration/ConfigurationExtensions.cs b/src/Configuration/ConfigurationExtensions.cs index 8447eeb..91afc8a 100644 --- a/src/Configuration/ConfigurationExtensions.cs +++ b/src/Configuration/ConfigurationExtensions.cs @@ -13,7 +13,11 @@ internal static class ConfigurationExtensions { internal static void UpdateBindings(this IniData data, TaskBinding binding, string sectionName = "TaskRunnerBindings") { - if (data.Sections.ContainsSection(sectionName)) data.Sections.RemoveSection(sectionName); + if (data.Sections.ContainsSection(sectionName)) + { + data.Sections.RemoveSection(sectionName); + } + data.Sections.AddSection(sectionName); data[sectionName].AddIfAny(BindingTargets.BeforeBuild, binding.BeforeBuild); data[sectionName].AddIfAny(BindingTargets.AfterBuild, binding.AfterBuild); @@ -28,18 +32,13 @@ internal static IEnumerable GetTasksForTarget(this XElement element, str : element.Attribute(target).Value.Split(',').Select(s => s.Trim()); } - private static void AddIfAny(this KeyDataCollection collection, string target, IEnumerable data) + internal static IEnumerable ReadValues(this KeyDataCollection collection, string target) { - var values = data as IList ?? data.ToList(); - if (values.Any()) + if (collection == null) { - collection[target] = string.Join(",", values).Trim(','); + return new List(); } - } - internal static IEnumerable ReadValues(this KeyDataCollection collection, string target) - { - if (collection == null) return new List(); try { var raw = collection[target]; @@ -50,5 +49,14 @@ internal static IEnumerable ReadValues(this KeyDataCollection collection return new List(); } } + + private static void AddIfAny(this KeyDataCollection collection, string target, IEnumerable data) + { + var values = data as IList ?? data.ToList(); + if (values.Any()) + { + collection[target] = string.Join(",", values).Trim(','); + } + } } } \ No newline at end of file diff --git a/src/Configuration/ConfigurationParser.cs b/src/Configuration/ConfigurationParser.cs index 846df5e..810d69e 100644 --- a/src/Configuration/ConfigurationParser.cs +++ b/src/Configuration/ConfigurationParser.cs @@ -10,14 +10,17 @@ namespace Cake.VisualStudio.Configuration { internal sealed class ConfigurationParser { - private static IniDataParser Parser => new IniDataParser(new IniParserConfiguration {AssigmentSpacer = ""}); - internal string SectionName { get; set; } = "TaskRunnerBindings"; public ConfigurationParser(string filePath) { FilePath = filePath; } + internal string SectionName { get; set; } = "TaskRunnerBindings"; + + private static IniDataParser Parser => new IniDataParser(new IniParserConfiguration { AssigmentSpacer = string.Empty }); + private string FilePath { get; set; } + internal void SaveBinding(TaskBinding binding) { var parser = new FileIniDataParser(Parser); diff --git a/src/Helpers/Extensions.cs b/src/Helpers/Extensions.cs index b2e850d..380056b 100644 --- a/src/Helpers/Extensions.cs +++ b/src/Helpers/Extensions.cs @@ -13,8 +13,7 @@ namespace Cake.VisualStudio.Helpers { internal static class Extensions { - internal static void ShowMessageBox(this IServiceProvider provider, string message, - string title = "Cake Installer") + internal static void ShowMessageBox(this IServiceProvider provider, string message, string title = "Cake Installer") { VsShellUtilities.ShowMessageBox( provider, @@ -25,8 +24,7 @@ internal static void ShowMessageBox(this IServiceProvider provider, string messa OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } - internal static void ShowErrorMessage(this IServiceProvider provider, string message, - string title = "Error during Cake installation") + internal static void ShowErrorMessage(this IServiceProvider provider, string message, string title = "Error during Cake installation") { VsShellUtilities.LogError("Cake.VisualStudio", message); VsShellUtilities.ShowMessageBox( @@ -40,7 +38,11 @@ internal static void ShowErrorMessage(this IServiceProvider provider, string mes internal static void ShowStatusBarText(this DTE2 dte, string text) { - if (dte?.StatusBar == null) return; + if (dte?.StatusBar == null) + { + return; + } + dte.StatusBar.Text = text; } diff --git a/src/Helpers/PathHelpers.cs b/src/Helpers/PathHelpers.cs index 9ec6791..b8c751d 100644 --- a/src/Helpers/PathHelpers.cs +++ b/src/Helpers/PathHelpers.cs @@ -18,7 +18,9 @@ internal static bool ExistsOnPath(string fileName) internal static string GetFullPath(string fileName) { if (File.Exists(fileName)) + { return Path.GetFullPath(fileName); + } var values = Environment.GetEnvironmentVariable("PATH"); return values?.Split(';').Select(path => Path.Combine(path, fileName)).FirstOrDefault(File.Exists); diff --git a/src/Helpers/ProjectHelpers.cs b/src/Helpers/ProjectHelpers.cs index 77fa79d..a8a01ea 100644 --- a/src/Helpers/ProjectHelpers.cs +++ b/src/Helpers/ProjectHelpers.cs @@ -21,10 +21,14 @@ public static class ProjectHelpers public static void CheckFileOutOfSourceControl(string file) { if (!File.Exists(file) || _dte.Solution.FindProjectItem(file) == null) + { return; + } if (_dte.SourceControl.IsItemUnderSCC(file) && !_dte.SourceControl.IsItemCheckedOut(file)) + { _dte.SourceControl.CheckOutItem(file); + } var info = new FileInfo(file); info.IsReadOnly = false; @@ -33,7 +37,9 @@ public static void CheckFileOutOfSourceControl(string file) public static void AddFileToProject(this Project project, string file, string itemType = null) { if (project.IsKind(ProjectTypes.ASPNET_5)) + { return; + } try { @@ -44,7 +50,9 @@ public static void AddFileToProject(this Project project, string file, string it if (string.IsNullOrEmpty(itemType) || project.IsKind(ProjectTypes.WEBSITE_PROJECT) || project.IsKind(ProjectTypes.UNIVERSAL_APP)) + { return; + } item.Properties.Item("ItemType").Value = "None"; } @@ -64,7 +72,9 @@ public static void AddNestedFile(string parentFile, string newFile) if (item == null || item.ContainingProject == null || item.ContainingProject.IsKind(ProjectTypes.ASPNET_5)) + { return; + } if (item.ProjectItems == null || item.ContainingProject.IsKind(ProjectTypes.UNIVERSAL_APP)) { @@ -91,7 +101,10 @@ public static void DeleteFileFromProject(string file) var item = _dte.Solution.FindProjectItem(file); if (item == null) + { return; + } + try { item.Delete(); @@ -102,27 +115,6 @@ public static void DeleteFileFromProject(string file) } } - private static IEnumerable GetChildProjects(Project parent) - { - try - { - if (!parent.IsKind(ProjectKinds.vsProjectKindSolutionFolder) && parent.Collection == null) // Unloaded - return Enumerable.Empty(); - - if (!string.IsNullOrEmpty(parent.FullName)) - return new[] { parent }; - } - catch (COMException) - { - return Enumerable.Empty(); - } - - return parent.ProjectItems - .Cast() - .Where(p => p.SubProject != null) - .SelectMany(p => GetChildProjects(p.SubProject)); - } - internal static Project GetSolutionItemsProject(DTE2 dte) { var solItems = @@ -134,7 +126,8 @@ internal static Project GetSolutionItemsProject(DTE2 dte) { var sol2 = (Solution2)dte.Solution; solItems = sol2.AddSolutionFolder("Solution Items"); - VsShellUtilities.LogMessage(Constants.PackageName, + VsShellUtilities.LogMessage( + Constants.PackageName, $"Created Solution Items project for solution {dte.Solution.FullName}", __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); } @@ -143,8 +136,35 @@ internal static Project GetSolutionItemsProject(DTE2 dte) // ignored } } + return solItems; } + + private static IEnumerable GetChildProjects(Project parent) + { + try + { + // Unloaded + if (!parent.IsKind(ProjectKinds.vsProjectKindSolutionFolder) && parent.Collection == null) + { + return Enumerable.Empty(); + } + + if (!string.IsNullOrEmpty(parent.FullName)) + { + return new[] { parent }; + } + } + catch (COMException) + { + return Enumerable.Empty(); + } + + return parent.ProjectItems + .Cast() + .Where(p => p.SubProject != null) + .SelectMany(p => GetChildProjects(p.SubProject)); + } } public static class ProjectTypes diff --git a/src/Menus/InstallConfigFileCommand.cs b/src/Menus/InstallConfigFileCommand.cs index 758268a..8f1fe30 100644 --- a/src/Menus/InstallConfigFileCommand.cs +++ b/src/Menus/InstallConfigFileCommand.cs @@ -105,11 +105,13 @@ private void MenuItemCallback(object sender, EventArgs e) } else { - if (MenuHelpers.DownloadFileToProject(Constants.ConfigTemplatePath, Constants.ConfigFileName, - MenuHelpers.ProjectInstallCommand)) + if (MenuHelpers.DownloadFileToProject(Constants.ConfigTemplatePath, Constants.ConfigFileName, MenuHelpers.ProjectInstallCommand)) { - VsShellUtilities.LogMessage(Constants.PackageName, "Cake configuration file installed into solution", + VsShellUtilities.LogMessage( + Constants.PackageName, + "Cake configuration file installed into solution", __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); + ServiceProvider.ShowMessageBox("Cake configuration file successfully downloaded."); } } diff --git a/src/Menus/MenuHelpers.cs b/src/Menus/MenuHelpers.cs index 1c2625b..43977fd 100644 --- a/src/Menus/MenuHelpers.cs +++ b/src/Menus/MenuHelpers.cs @@ -14,7 +14,6 @@ namespace Cake.VisualStudio.Menus { internal static class MenuHelpers { - internal static bool DownloadFileToProject(string downloadPath, string targetFileName) { var dte = CakePackage.Dte; @@ -22,15 +21,18 @@ internal static bool DownloadFileToProject(string downloadPath, string targetFil { var solItems = ProjectHelpers.GetSolutionItemsProject(dte); solItems?.AddFileToProject(targetPath); + if (solItems != null) - VsShellUtilities.LogMessage(Constants.PackageName, + { + VsShellUtilities.LogMessage( + Constants.PackageName, $"New file added to Solution Items for solution {dte.Solution.FullName}", __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); + } }); } - internal static bool DownloadFileToProject(string downloadPath, string targetFileName, - Action installCallback) + internal static bool DownloadFileToProject(string downloadPath, string targetFileName, Action installCallback) { var dte = CakePackage.Dte; try @@ -39,12 +41,21 @@ internal static bool DownloadFileToProject(string downloadPath, string targetFil var cakeScriptPath = dte.Solution.FindProjectItem(Constants.ScriptFileName)?.FileNames[1]; var targetPath = Path.Combine(new FileInfo(string.IsNullOrWhiteSpace(cakeScriptPath) ? slnFilePath : cakeScriptPath).Directory.FullName, targetFileName); bool confirm = true; + if (File.Exists(targetPath)) { - confirm = VsShellUtilities.PromptYesNo("File already exists. Overwrite?", $"Downloading {targetFileName}", - OLEMSGICON.OLEMSGICON_QUERY, CakePackage.Shell); + confirm = VsShellUtilities.PromptYesNo( + "File already exists. Overwrite?", + $"Downloading {targetFileName}", + OLEMSGICON.OLEMSGICON_QUERY, + CakePackage.Shell); + } + + if (!confirm) + { + return true; } - if (!confirm) return true; + try { ProjectHelpers.CheckFileOutOfSourceControl(targetPath); @@ -53,14 +64,18 @@ internal static bool DownloadFileToProject(string downloadPath, string targetFil { // ignored } + using (var wc = new WebClient()) { wc.DownloadFile(downloadPath, targetPath); - VsShellUtilities.LogMessage(Constants.PackageName, + VsShellUtilities.LogMessage( + Constants.PackageName, $"File downloaded from '{downloadPath}' to '{targetPath}'", __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); + installCallback.Invoke(targetPath); } + return true; } catch @@ -83,9 +98,15 @@ internal static bool DownloadFileToProject(string downloadPath, string targetFil { proj = ProjectHelpers.GetSolutionItemsProject(dte); } - if (proj == null) return; + + if (proj == null) + { + return; + } + proj.AddFileToProject(s); - VsShellUtilities.LogMessage(Constants.PackageName, + VsShellUtilities.LogMessage( + Constants.PackageName, $"New file added to {proj.Name} for solution {dte.Solution.FullName}", __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); }; diff --git a/src/TaskRunner/TaskRunner.cs b/src/TaskRunner/TaskRunner.cs index d816f61..4c5fb2f 100644 --- a/src/TaskRunner/TaskRunner.cs +++ b/src/TaskRunner/TaskRunner.cs @@ -35,11 +35,31 @@ private void InitializeCakeRunnerOptions() { _options = new List { - new TaskRunnerOption("Verbose", PackageIds.cmdVerbose, PackageGuids.guidCakePackageCmdSet, false, + new TaskRunnerOption( + "Verbose", + PackageIds.cmdVerbose, + PackageGuids.GuidCakePackageCmdSet, + false, "-Verbosity=\"Diagnostic\""), - new TaskRunnerOption("Debug", PackageIds.cmdDebug, PackageGuids.guidCakePackageCmdSet, false, "-debug"), - new TaskRunnerOption("Dry Run", PackageIds.cmdDryRun, PackageGuids.guidCakePackageCmdSet, false, "-dryrun"), - new TaskRunnerOption("Experimental", PackageIds.cmdExperimental, PackageGuids.guidCakePackageCmdSet, false, "-experimental") + new TaskRunnerOption( + "Debug", + PackageIds.cmdDebug, + PackageGuids.GuidCakePackageCmdSet, + false, + "-debug"), + new TaskRunnerOption( + "Dry Run", + PackageIds.cmdDryRun, + PackageGuids.GuidCakePackageCmdSet, + false, + "-dryrun"), + new TaskRunnerOption( + "Experimental", + PackageIds.cmdExperimental, + PackageGuids.GuidCakePackageCmdSet, + false, + "-experimental") + }; } @@ -110,8 +130,12 @@ private ITaskRunnerNode LoadHierarchy(string configPath) var commands = tasks.Select( t => - CreateTask(cwd, t.Key, $"Runs {configFileName} with the \"{t.Key}\" target", + CreateTask( + cwd, + t.Key, + $"Runs {configFileName} with the \"{t.Key}\" target", buildDev.Command.Args + $" {t.Value}")); + var nodes = commands as IList ?? commands.ToList(); buildDev.Children.AddRange(nodes); root.Children.Add(buildDev); @@ -127,7 +151,7 @@ private TaskRunnerNode CreateTask(string cwd, string name, string desc, string a Command = GetCommand(cwd, args) }; - //ApplyOverrides(task); + //// ApplyOverrides(task); return task; } @@ -141,16 +165,22 @@ private ITaskRunnerCommand GetCommand(string cwd, string arguments) private static string GetCakePath(string cwd) { - var knownPaths = new[] {"tools/Cake/Cake.exe", "Cake/Cake.exe", "Cake.exe"}; + var knownPaths = new[] { "tools/Cake/Cake.exe", "Cake/Cake.exe", "Cake.exe" }; foreach (var path in knownPaths) { var fullPath = Path.Combine(cwd, path); - if (File.Exists(fullPath)) return fullPath; + + if (File.Exists(fullPath)) + { + return fullPath; + } } + if (PathHelpers.ExistsOnPath("cake.exe") || PathHelpers.ExistsOnPath("cake")) { return "cake"; // assume PATH } + return null; } diff --git a/src/TaskRunner/TaskRunnerConfig.cs b/src/TaskRunner/TaskRunnerConfig.cs index 5444d97..e5771c2 100644 --- a/src/TaskRunner/TaskRunnerConfig.cs +++ b/src/TaskRunner/TaskRunnerConfig.cs @@ -40,32 +40,6 @@ public string LoadBindings(string configPath) return File.Exists(bindingPath) ? new ConfigurationParser(bindingPath).LoadBinding().ToXml() : ""; } - private string GetBindingPath(string configPath, bool create = false) - { - string bindingPath; - var path = CakePackage.Dte.Solution?.FindProjectItem(Constants.ConfigFileName); - if (path != null && path.FileCount == 1) - { - bindingPath = path.FileNames[1]; - } - else - { - var cpath = Path.Combine(Path.GetDirectoryName(configPath), Constants.ConfigFileName); - try - { - - if (!File.Exists(cpath) && create) File.Create(cpath).Close(); - if (File.Exists(cpath)) ProjectHelpers.GetSolutionItemsProject(CakePackage.Dte).AddFileToProject(cpath); - } - catch - { - // ignored - } - bindingPath = cpath; - } - return string.IsNullOrWhiteSpace(bindingPath) ? null : bindingPath; // remove the empty string scenario - } - public bool SaveBindings(string configPath, string bindingsXml) { string bindingPath = GetBindingPath(configPath, true) ?? configPath + ".bindings"; @@ -104,5 +78,39 @@ public bool SaveBindings(string configPath, string bindingsXml) return false; } } + + private string GetBindingPath(string configPath, bool create = false) + { + string bindingPath; + var path = CakePackage.Dte.Solution?.FindProjectItem(Constants.ConfigFileName); + if (path != null && path.FileCount == 1) + { + bindingPath = path.FileNames[1]; + } + else + { + var cpath = Path.Combine(Path.GetDirectoryName(configPath), Constants.ConfigFileName); + try + { + if (!File.Exists(cpath) && create) + { + File.Create(cpath).Close(); + } + + if (File.Exists(cpath)) + { + ProjectHelpers.GetSolutionItemsProject(CakePackage.Dte).AddFileToProject(cpath); + } + } + catch + { + // ignored + } + + bindingPath = cpath; + } + + return string.IsNullOrWhiteSpace(bindingPath) ? null : bindingPath; // remove the empty string scenario + } } } \ No newline at end of file diff --git a/src/packages.config b/src/packages.config index 25e3245..a9c2cb6 100644 --- a/src/packages.config +++ b/src/packages.config @@ -26,6 +26,7 @@ +