logic: update Visual Studio plugin to support Visual Studio 2017

* changed description text of Visual Studio plugin
* changed plugin install targets to include VS 2017
* add license file with MIT license
* updated vsix for deployment

* implement wrapper for all used classes of VCProjectEngine.dll since you cannot just use the oldest version of this
  assembly (see https://stackoverflow.com/questions/44288050/typecast-fails-when-visual-studio-extension-uses-reference-to-older-assembly).
* improved serialization and deserialization of compile commands and compilation databases.
* updated used JSON package
* rename CommandObject to CompileCommand
* changed implementation to keep non-existent file paths in cdb
* made methods of SolutionParser non-static
* replace spaces with tabs

* added IntegrationTests project
* configured tests to simulate a new instance of VisualStudio
* added cinder as test project for integration tests
* remove all absolute paths from expected output of integration tests

fortune cookie message = A stranger will bring great meaning to your life.
This commit is contained in:
malte_langkabel
2017-06-02 14:48:29 +02:00
parent aaca8618e2
commit 7010b9a6fb
289 changed files with 293635 additions and 22692 deletions
@@ -0,0 +1,23 @@
using CoatiSoftware.SourcetrailPlugin.Utility;
using VCProjectEngineWrapper;
namespace CoatiSoftware.SourcetrailPlugin.IntegrationTests.Helpers
{
class TestPathResolver : IPathResolver
{
public override string GetCompilationDatabaseFilePath()
{
return "<CompilationDatabaseFilePath>";
}
protected override string DoGetAsAbsoluteCanonicalPath(string path, IVCProjectWrapper project)
{
return "<ProjectBaseDirectory>/" + path;
}
protected override string ResolveVsMacro(string potentialMacro, IVCConfigurationWrapper vcProjectConfig)
{
return "<Macro " + potentialMacro + ">";
}
}
}
@@ -0,0 +1,30 @@
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VSSDK.Tools.VsIdeTesting;
using System;
namespace CoatiSoftware.SourcetrailPlugin.IntegrationTests.Helpers
{
public static class TestUtility
{
public static void OpenSolution(string solutionFilePath)
{
IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution));
int ret = solutionService.OpenSolutionFile((uint)__VSSLNOPENOPTIONS.SLNOPENOPT_DontConvertSLN, solutionFilePath);
DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE));
Console.WriteLine("opened solution contains " + dte.Solution.Projects.Count.ToString() + " projects");
Assert.AreEqual(VSConstants.S_OK, ret);
}
public static void CloseCurrentSolution()
{
IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution));
int ret = solutionService.CloseSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_NoSave, null, 0);
Assert.AreEqual(VSConstants.S_OK, ret);
}
}
}
@@ -0,0 +1,130 @@
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VSSDK.Tools.VsIdeTesting;
using Microsoft.VisualStudio.Shell.Interop;
using EnvDTE;
using CoatiSoftware.SourcetrailPlugin.SolutionParser;
using System.IO;
using CoatiSoftware.SourcetrailPlugin.IntegrationTests.Helpers;
using System.Collections.Generic;
namespace CoatiSoftware.SourcetrailPlugin.IntegrationTests
{
[TestClass]
public class CreateCdbTests
{
private bool _updateExpectedOutput = false;
[TestMethod]
[HostType("VS IDE")]
public void TestSourcetrailPluginPackageGetsLoaded()
{
UIThreadInvoker.Invoke(new Action(() =>
{
// Load the package into the shell.
Assert.IsNotNull(VsIdeTestHostContext.ServiceProvider);
IVsShell shellService = (IVsShell)VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell));
Guid packageGuid = new Guid(GuidList.guidSourcetrailPluginPkgString);
IVsPackage package;
shellService.IsPackageLoaded(ref packageGuid, out package);
if (package == null)
{
shellService.LoadPackage(ref packageGuid, out package);
}
Assert.IsTrue(package is SourcetrailPluginPackage);
}));
}
[TestMethod]
[HostType("VS IDE")]
public void TestCompilationDatabaseCreationForCinderSolution()
{
UIThreadInvoker.Initialize();
UIThreadInvoker.Invoke(new Action(() =>
{
TestCompilationDatabaseForSolution("../../../SourcetrailPlugin.IntegrationTests/bin/data/cinder/cinder.sln");
}));
}
[TestMethod]
[HostType("VS IDE")]
public void TestCompilationDatabaseCreationForAllFilesInSameFolder()
{
UIThreadInvoker.Initialize();
UIThreadInvoker.Invoke(new Action(() =>
{
TestCompilationDatabaseForSolution("../../../SourcetrailPlugin.IntegrationTests/bin/data/all_in_same_folder/test.sln");
}));
}
private void TestCompilationDatabaseForSolution(string solutionPath)
{
Console.WriteLine("opening solution: " + solutionPath);
Helpers.TestUtility.OpenSolution(solutionPath);
Console.WriteLine("creating compilation database");
CompilationDatabase output = null;
try
{
output = CreateCompilationDatabaseForCurrentSolution();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
Console.WriteLine("Stack Trace: " + e.StackTrace);
Assert.Fail("Caught and exception while creating compilation database.");
}
Assert.IsNotNull(output);
string cdbPath = Path.ChangeExtension(solutionPath, "json");
if (_updateExpectedOutput)
{
Console.WriteLine("writing compilation database to file: " + cdbPath);
File.WriteAllText(cdbPath, output.SerializeToJson());
Assert.IsTrue(File.Exists(cdbPath));
}
else
{
Console.WriteLine("reading compilation database from file: " + cdbPath);
CompilationDatabase expectedOutput = CompilationDatabase.LoadFromFile(cdbPath);
Assert.IsNotNull(expectedOutput);
Console.WriteLine("comparing generated compilation database to expected output");
Assert.IsTrue(output == expectedOutput, "The created compilation database differs from the expected output");
}
Console.WriteLine("closing solution");
Helpers.TestUtility.CloseCurrentSolution();
}
private static CompilationDatabase CreateCompilationDatabaseForCurrentSolution()
{
DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE));
Assert.IsNotNull(dte);
CompilationDatabase cdb = new CompilationDatabase();
foreach (Project project in dte.Solution.Projects)
{
List<string> configurationNames = Utility.SolutionUtility.GetConfigurationNames(dte);
Assert.IsTrue(configurationNames.Count > 0, "No target configurations found in loaded solution.");
List<string> platformNames = Utility.SolutionUtility.GetPlatformNames(dte);
Assert.IsTrue(platformNames.Count > 0, "No target platforms found in loaded solution.");
SolutionParser.SolutionParser solutionParser = new SolutionParser.SolutionParser(new TestPathResolver());
foreach (SolutionParser.CompileCommand command in solutionParser.CreateCompileCommands(
project, configurationNames[0], platformNames[0], "c11"
))
{
cdb.AddCommandObject(command);
}
}
return cdb;
}
}
}
@@ -0,0 +1,20 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SourcetrailPlugin.IntegrationTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("SourcetrailPlugin.IntegrationTests")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("9de8c188-0f0e-4f5d-b3c4-ecf9cfb23e0d")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,122 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.props')" />
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VisualStudioYear>2015</VisualStudioYear>
<VisualStudioYear Condition="'$(VisualStudioVersion)' &gt;= '15.0'">2017</VisualStudioYear>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<PropertyGroup Condition="'$(VisualStudioVersion)' &gt;= '11.0'">
<MinimumVisualStudioVersion>$(VisualStudioVersion)</MinimumVisualStudioVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(VisualStudioVersion)' &gt;= '12.0'">
<OldToolsVersion>4.0</OldToolsVersion>
</PropertyGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9DE8C188-0F0E-4F5D-B3C4-ECF9CFB23E0D}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CoatiSoftware.SourcetrailPlugin.IntegrationTests</RootNamespace>
<AssemblyName>SourcetrailPlugin.IntegrationTests</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' &gt;= '15'">
<ItemGroup>
<Reference Include="Microsoft.VSSDK.TestHostFramework, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.VCProjectEngine, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VSSDK.TestHostFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</Otherwise>
</Choose>
<ItemGroup>
<Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>False</EmbedInteropTypes>
<Private>True</Private>
</Reference>
<Reference Include="EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>False</EmbedInteropTypes>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.OLE.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="Microsoft.VisualStudio.Shell.11.0, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.11.0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop.9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="Helpers\TestPathResolver.cs" />
<Compile Include="IntegrationTests\CreateCdbTests.cs" />
<Compile Include="Helpers\TestUtility.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UnitTests\CompilationDatabaseTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SourcetrailPlugin\SourcetrailPlugin.csproj">
<Project>{a585a530-e120-4c74-934e-d57ed12a7da9}</Project>
<Name>SourcetrailPlugin</Name>
</ProjectReference>
<ProjectReference Include="..\VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj">
<Project>{F592DB46-0C77-470B-AAF8-80C51F44380E}</Project>
<Name>VCProjectEngineWrapperInterfaces</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.props'))" />
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.targets'))" />
</Target>
<Import Project="..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\packages\MSTest.TestAdapter.1.1.11\build\net45\MSTest.TestAdapter.targets')" />
</Project>
@@ -0,0 +1,60 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CoatiSoftware.SourcetrailPlugin.SolutionParser;
namespace CoatiSoftware.SourcetrailPlugin.IntegrationTests.UnitTests
{
[TestClass]
public class CompilationDatabaseTests
{
[TestMethod]
public void TestComparingCompileCommandWithSelfByValueWorks()
{
CompileCommand command1 = new CompileCommand();
command1.File = "test.cpp";
command1.Directory = "./";
command1.Command = "D test test.cpp";
CompileCommand command2 = new CompileCommand();
command2.File = "test.cpp";
command2.Directory = "./";
command2.Command = "D test test.cpp";
Assert.IsTrue(command1 == command2);
}
[TestMethod]
public void TestComparingCompilationDatabaseWithSelfByValueWorks()
{
CompileCommand command = new CompileCommand();
command.File = "test.cpp";
command.Directory = "./";
command.Command = "D test test.cpp";
CompilationDatabase cdb1 = new CompilationDatabase();
cdb1.AddCommandObject(command);
CompilationDatabase cdb2 = new CompilationDatabase();
cdb2.AddCommandObject(command);
Assert.IsTrue(cdb1 == cdb2);
}
[TestMethod]
public void TestCompilationDatabaseRetainsEscapedQuotesWhenDeserializedAfterSerialization()
{
CompileCommand command = new CompileCommand();
command.File = "test.cpp";
command.Directory = "./";
command.Command = "D DEFINE=\"value\" test.cpp";
CompilationDatabase originalCompilationDatabase = new CompilationDatabase();
originalCompilationDatabase.AddCommandObject(command);
string serialized = originalCompilationDatabase.SerializeToJson();
CompilationDatabase deserializedCompilationDatabase = new CompilationDatabase();
deserializedCompilationDatabase.DeserializeFromJson(serialized);
Assert.IsTrue(deserializedCompilationDatabase == originalCompilationDatabase);
}
}
}
@@ -0,0 +1,7 @@
[
{
"directory": "<CompilationDatabaseFilePath>",
"command": "clang-tool -fms-extensions -fms-compatibility -fms-compatibility-version=19 -isystem '<Macro $(VC_IncludePath)>' -isystem '<Macro $(WindowsSDK_IncludePath)>' -D WIN32 -D _DEBUG -D _CONSOLE -std=c++14 '<ProjectBaseDirectory>/main.cpp'",
"file": "<ProjectBaseDirectory>/main.cpp"
}
]
@@ -0,0 +1,39 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BR9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test", "test.vcxproj", "{03CDC311-12CE-4B5A-B1D6-DEE68194163D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
MinSizeRel|x64 = MinSizeRel|x64
MinSizeRel|x86 = MinSizeRel|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
RelWithDebInfo|x64 = RelWithDebInfo|x64
RelWithDebInfo|x86 = RelWithDebInfo|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Debug|x64.ActiveCfg = Debug|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Debug|x64.Build.0 = Debug|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Debug|x86.ActiveCfg = Debug|Win32
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Debug|x86.Build.0 = Debug|Win32
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.MinSizeRel|x64.ActiveCfg = Release|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.MinSizeRel|x64.Build.0 = Release|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.MinSizeRel|x86.ActiveCfg = Release|Win32
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.MinSizeRel|x86.Build.0 = Release|Win32
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Release|x64.ActiveCfg = Release|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Release|x64.Build.0 = Release|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Release|x86.ActiveCfg = Release|Win32
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.Release|x86.Build.0 = Release|Win32
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.RelWithDebInfo|x64.ActiveCfg = Release|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.RelWithDebInfo|x64.Build.0 = Release|x64
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.RelWithDebInfo|x86.ActiveCfg = Release|Win32
{03CDC311-12CE-4B5A-B1D6-DEE68194163D}.RelWithDebInfo|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{03CDC311-12CE-4B5A-B1D6-DEE68194163D}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>testtest</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup>
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<GenerateDebugInformation>Debug</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,51 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
Project("{8CC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ALL_BUILD", "ALL_BUILD.vcxproj", "{77DB15F6-B3BF-32CA-B434-F11CCD83B9C9}"
ProjectSection(ProjectDependencies) = postProject
{33039C50-EF04-3EAA-BDC7-703712A3249F} = {33039C50-EF04-3EAA-BDC7-703712A3249F}
{C9438973-99BC-3461-A610-4C65A2403BF5} = {C9438973-99BC-3461-A610-4C65A2403BF5}
EndProjectSection
EndProject
Project("{8CC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZERO_CHECK", "ZERO_CHECK.vcxproj", "{33039C50-EF04-3EAA-BDC7-703712A3249F}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8CC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cinder", "cinder.vcxproj", "{C9438973-99BC-3461-A610-4C65A2403BF5}"
ProjectSection(ProjectDependencies) = postProject
{33039C50-EF04-3EAA-BDC7-703712A3249F} = {33039C50-EF04-3EAA-BDC7-703712A3249F}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
MinSizeRel|Win32 = MinSizeRel|Win32
RelWithDebInfo|Win32 = RelWithDebInfo|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{77DB15F6-B3BF-32CA-B434-F11CCD83B9C9}.Debug|Win32.ActiveCfg = Debug|Win32
{77DB15F6-B3BF-32CA-B434-F11CCD83B9C9}.Release|Win32.ActiveCfg = Release|Win32
{77DB15F6-B3BF-32CA-B434-F11CCD83B9C9}.MinSizeRel|Win32.ActiveCfg = MinSizeRel|Win32
{77DB15F6-B3BF-32CA-B434-F11CCD83B9C9}.RelWithDebInfo|Win32.ActiveCfg = RelWithDebInfo|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.Debug|Win32.ActiveCfg = Debug|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.Debug|Win32.Build.0 = Debug|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.Release|Win32.ActiveCfg = Release|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.Release|Win32.Build.0 = Release|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.MinSizeRel|Win32.ActiveCfg = MinSizeRel|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.MinSizeRel|Win32.Build.0 = MinSizeRel|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.RelWithDebInfo|Win32.ActiveCfg = RelWithDebInfo|Win32
{33039C50-EF04-3EAA-BDC7-703712A3249F}.RelWithDebInfo|Win32.Build.0 = RelWithDebInfo|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.Debug|Win32.ActiveCfg = Debug|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.Debug|Win32.Build.0 = Debug|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.Release|Win32.ActiveCfg = Release|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.Release|Win32.Build.0 = Release|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.MinSizeRel|Win32.ActiveCfg = MinSizeRel|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.MinSizeRel|Win32.Build.0 = MinSizeRel|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.RelWithDebInfo|Win32.ActiveCfg = RelWithDebInfo|Win32
{C9438973-99BC-3461-A610-4C65A2403BF5}.RelWithDebInfo|Win32.Build.0 = RelWithDebInfo|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
File diff suppressed because one or more lines are too long
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MSTest.TestAdapter" version="1.1.11" targetFramework="net461" />
<package id="MSTest.TestFramework" version="1.1.11" targetFramework="net461" />
</packages>
@@ -1,9 +1,31 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
# Visual Studio 15
VisualStudioVersion = 15.0.26403.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourcetrailPlugin", "SourcetrailPlugin\SourcetrailPlugin.csproj", "{A585A530-E120-4C74-934E-D57ED12A7DA9}"
ProjectSection(ProjectDependencies) = postProject
{F592DB46-0C77-470B-AAF8-80C51F44380E} = {F592DB46-0C77-470B-AAF8-80C51F44380E}
{8188D64D-E880-490C-B267-B493A2171BE3} = {8188D64D-E880-490C-B267-B493A2171BE3}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourcetrailPlugin.IntegrationTests", "SourcetrailPlugin.IntegrationTests\SourcetrailPlugin.IntegrationTests.csproj", "{9DE8C188-0F0E-4F5D-B3C4-ECF9CFB23E0D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VCProjectEngineWrapperInterfaces", "VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj", "{F592DB46-0C77-470B-AAF8-80C51F44380E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VCProjectEngineWrapperVs2013", "VCProjectEngineWrapper\VCProjectEngineWrapperVs2013.csproj", "{8718929C-5270-4E5A-8998-48AC7CE19DC2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VCProjectEngineWrapperFactories", "VCProjectEngineWrapperFactories\VCProjectEngineWrapperFactories.csproj", "{8188D64D-E880-490C-B267-B493A2171BE3}"
ProjectSection(ProjectDependencies) = postProject
{1C139999-9592-4891-AA62-2C8A16430D0A} = {1C139999-9592-4891-AA62-2C8A16430D0A}
{8718929C-5270-4E5A-8998-48AC7CE19DC2} = {8718929C-5270-4E5A-8998-48AC7CE19DC2}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VCProjectEngineWrapperVs2015", "VCProjectEngineWrapper\VCProjectEngineWrapperVs2015.csproj", "{1C139999-9592-4891-AA62-2C8A16430D0A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VCProjectEngineWrapperVs2017", "VCProjectEngineWrapper\VCProjectEngineWrapperVs2017.csproj", "{B49207F9-89A3-42D8-BC04-8BF77ED2E295}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VCProjectEngineWrapperVs2012", "VCProjectEngineWrapper\VCProjectEngineWrapperVs2012.csproj", "{C5439B90-42E7-414D-8C3F-BDCABB0592E2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -15,6 +37,34 @@ Global
{A585A530-E120-4C74-934E-D57ED12A7DA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A585A530-E120-4C74-934E-D57ED12A7DA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A585A530-E120-4C74-934E-D57ED12A7DA9}.Release|Any CPU.Build.0 = Release|Any CPU
{9DE8C188-0F0E-4F5D-B3C4-ECF9CFB23E0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9DE8C188-0F0E-4F5D-B3C4-ECF9CFB23E0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9DE8C188-0F0E-4F5D-B3C4-ECF9CFB23E0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9DE8C188-0F0E-4F5D-B3C4-ECF9CFB23E0D}.Release|Any CPU.Build.0 = Release|Any CPU
{F592DB46-0C77-470B-AAF8-80C51F44380E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F592DB46-0C77-470B-AAF8-80C51F44380E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F592DB46-0C77-470B-AAF8-80C51F44380E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F592DB46-0C77-470B-AAF8-80C51F44380E}.Release|Any CPU.Build.0 = Release|Any CPU
{8718929C-5270-4E5A-8998-48AC7CE19DC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8718929C-5270-4E5A-8998-48AC7CE19DC2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8718929C-5270-4E5A-8998-48AC7CE19DC2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8718929C-5270-4E5A-8998-48AC7CE19DC2}.Release|Any CPU.Build.0 = Release|Any CPU
{8188D64D-E880-490C-B267-B493A2171BE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8188D64D-E880-490C-B267-B493A2171BE3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8188D64D-E880-490C-B267-B493A2171BE3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8188D64D-E880-490C-B267-B493A2171BE3}.Release|Any CPU.Build.0 = Release|Any CPU
{1C139999-9592-4891-AA62-2C8A16430D0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1C139999-9592-4891-AA62-2C8A16430D0A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1C139999-9592-4891-AA62-2C8A16430D0A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1C139999-9592-4891-AA62-2C8A16430D0A}.Release|Any CPU.Build.0 = Release|Any CPU
{B49207F9-89A3-42D8-BC04-8BF77ED2E295}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B49207F9-89A3-42D8-BC04-8BF77ED2E295}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B49207F9-89A3-42D8-BC04-8BF77ED2E295}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B49207F9-89A3-42D8-BC04-8BF77ED2E295}.Release|Any CPU.Build.0 = Release|Any CPU
{C5439B90-42E7-414D-8C3F-BDCABB0592E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C5439B90-42E7-414D-8C3F-BDCABB0592E2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C5439B90-42E7-414D-8C3F-BDCABB0592E2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C5439B90-42E7-414D-8C3F-BDCABB0592E2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -0,0 +1,110 @@
using System;
using System.Runtime.InteropServices;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace ComUtils
{
public class ComHelper
{
/// <summary>
/// Returns a string value representing the type name of the specified COM object.
/// </summary>
/// <param name="comObj">A COM object the type name of which to return.</param>
/// <returns>A string containing the type name.</returns>
public static string GetTypeName(object comObj)
{
if (comObj == null)
return String.Empty;
if (!Marshal.IsComObject(comObj))
//The specified object is not a COM object
return String.Empty;
IDispatch dispatch = comObj as IDispatch;
if (dispatch == null)
//The specified COM object doesn't support getting type information
return String.Empty;
ComTypes.ITypeInfo typeInfo = null;
try
{
try
{
// obtain the ITypeInfo interface from the object
dispatch.GetTypeInfo(0, 0, out typeInfo);
}
catch (Exception ex)
{
//Cannot get the ITypeInfo interface for the specified COM object
return String.Empty;
}
string typeName = "";
string documentation, helpFile;
int helpContext = -1;
try
{
//retrieves the documentation string for the specified type description
typeInfo.GetDocumentation(-1, out typeName, out documentation,
out helpContext, out helpFile);
}
catch (Exception ex)
{
// Cannot extract ITypeInfo information
return String.Empty;
}
return typeName;
}
catch (Exception ex)
{
// Unexpected error
return String.Empty;
}
finally
{
if (typeInfo != null) Marshal.ReleaseComObject(typeInfo);
}
}
}
/// <summary>
/// Exposes objects, methods and properties to programming tools and other
/// applications that support Automation.
/// </summary>
[ComImport()]
[Guid("00020400-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IDispatch
{
[PreserveSig]
int GetTypeInfoCount(out int Count);
[PreserveSig]
int GetTypeInfo(
[MarshalAs(UnmanagedType.U4)] int iTInfo,
[MarshalAs(UnmanagedType.U4)] int lcid,
out ComTypes.ITypeInfo typeInfo);
[PreserveSig]
int GetIDsOfNames(
ref Guid riid,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)]
string[] rgsNames,
int cNames,
int lcid,
[MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);
[PreserveSig]
int Invoke(
int dispIdMember,
ref Guid riid,
uint lcid,
ushort wFlags,
ref ComTypes.DISPPARAMS pDispParams,
out object pVarResult,
ref ComTypes.EXCEPINFO pExcepInfo,
IntPtr[] pArgErr);
}
}
@@ -4,11 +4,11 @@ using System;
namespace CoatiSoftware.SourcetrailPlugin
{
static class GuidList
{
public const string guidSourcetrailPluginPkgString = "acf15780-03b5-440e-a41e-db79b7043fc2";
public const string guidSourcetrailPluginCmdSetString = "0efb005b-715c-4a62-8a9b-1e5a870e6c34";
public static class GuidList
{
public const string guidSourcetrailPluginPkgString = "acf15780-03b5-440e-a41e-db79b7043fc2";
public const string guidSourcetrailPluginCmdSetString = "0efb005b-715c-4a62-8a9b-1e5a870e6c34";
public static readonly Guid guidSourcetrailPluginCmdSet = new Guid(guidSourcetrailPluginCmdSetString);
};
public static readonly Guid guidSourcetrailPluginCmdSet = new Guid(guidSourcetrailPluginCmdSetString);
};
}
@@ -0,0 +1,19 @@
Copyright (c) 2017 Coati Software OG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -3,65 +3,65 @@ using System.Collections.Generic;
namespace CoatiSoftware.SourcetrailPlugin.Logging
{
class FileLogger : ILogger
{
private static string _directory = "";
private static string _fileNamePrefix = "Log_SourcetrailPlugin_";
private static string _fileNameSufix = ".txt";
class FileLogger : ILogger
{
private static string _directory = "";
private static string _fileNamePrefix = "Log_SourcetrailPlugin_";
private static string _fileNameSufix = ".txt";
private string _fileName = "";
private string _fileName = "";
private Queue<string> _messageBacklog = new Queue<string>(); // stores messages if the log file was in use at original logging time
private Queue<string> _messageBacklog = new Queue<string>(); // stores messages if the log file was in use at original logging time
public FileLogger()
{
DateTime time = DateTime.Now;
public FileLogger()
{
DateTime time = DateTime.Now;
string dateString = "";
dateString += time.Year.ToString() + "-" + time.Month.ToString() + "-" + time.Day.ToString() + "_";
dateString += time.Hour.ToString() + "-" + time.Minute.ToString() + "-" + time.Second.ToString();
string dateString = "";
dateString += time.Year.ToString() + "-" + time.Month.ToString() + "-" + time.Day.ToString() + "_";
dateString += time.Hour.ToString() + "-" + time.Minute.ToString() + "-" + time.Second.ToString();
_fileName = _fileNamePrefix + dateString + _fileNameSufix;
_fileName = _fileNamePrefix + dateString + _fileNameSufix;
_directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_directory += "\\Coati Software\\Plugins\\VS\\";
_directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_directory += "\\Coati Software\\Plugins\\VS\\";
if(System.IO.Directory.Exists(_directory) == false)
{
System.IO.Directory.CreateDirectory(_directory);
}
}
if(System.IO.Directory.Exists(_directory) == false)
{
System.IO.Directory.CreateDirectory(_directory);
}
}
public void LogMessage(LogMessage message)
{
System.IO.StreamWriter writer = null;
public void LogMessage(LogMessage message)
{
System.IO.StreamWriter writer = null;
try
{
writer = System.IO.File.AppendText(_directory + _fileName);
try
{
writer = System.IO.File.AppendText(_directory + _fileName);
// write backlog to file first
while(_messageBacklog.Count > 0)
{
string bm = _messageBacklog.Dequeue();
writer.WriteLine(bm);
}
// write backlog to file first
while(_messageBacklog.Count > 0)
{
string bm = _messageBacklog.Dequeue();
writer.WriteLine(bm);
}
writer.WriteLine(message.ToString());
writer.Close();
}
catch(Exception e)
{
// well...file is still in use
_messageBacklog.Enqueue(message.ToString());
}
finally
{
if(writer != null)
{
writer.Close();
}
}
}
}
writer.WriteLine(message.ToString());
writer.Close();
}
catch(Exception e)
{
// well...file is still in use
_messageBacklog.Enqueue(message.ToString());
}
finally
{
if(writer != null)
{
writer.Close();
}
}
}
}
}
@@ -6,8 +6,8 @@ using System.Threading.Tasks;
namespace CoatiSoftware.SourcetrailPlugin.Logging
{
public interface ILogger
{
void LogMessage(LogMessage message);
}
public interface ILogger
{
void LogMessage(LogMessage message);
}
}
@@ -6,89 +6,89 @@ using System.Threading.Tasks;
namespace CoatiSoftware.SourcetrailPlugin.Logging
{
public class LogManager
{
private static LogManager _instance = null;
public class LogManager
{
private static LogManager _instance = null;
private List<ILogger> _loggers = new List<ILogger>();
private List<ILogger> _loggers = new List<ILogger>();
private bool _loggingEnabled = false;
private bool _loggingEnabled = false;
public List<ILogger> Loggers
{
get { return _loggers; }
set { _loggers = value; }
}
public List<ILogger> Loggers
{
get { return _loggers; }
set { _loggers = value; }
}
public bool LoggingEnabled
{
get { return _loggingEnabled; }
set { _loggingEnabled = value; }
}
public bool LoggingEnabled
{
get { return _loggingEnabled; }
set { _loggingEnabled = value; }
}
private LogManager()
{
}
private LogManager()
{
}
public static LogManager GetInstance()
{
if(_instance == null)
{
_instance = new LogManager();
}
public static LogManager GetInstance()
{
if(_instance == null)
{
_instance = new LogManager();
}
return _instance;
}
return _instance;
}
public void LogInfo(string message, string sourceFile, string callingFunction, int lineNumber)
{
LogMessage logMessage = new LogMessage();
logMessage.Message = message;
logMessage.MessageType = LogMessage.LogMessageType.INFO;
logMessage.Time = DateTime.Now;
logMessage.SourceFile = sourceFile;
logMessage.CallingFunction = callingFunction;
logMessage.LineNumber = lineNumber;
public void LogInfo(string message, string sourceFile, string callingFunction, int lineNumber)
{
LogMessage logMessage = new LogMessage();
logMessage.Message = message;
logMessage.MessageType = LogMessage.LogMessageType.INFO;
logMessage.Time = DateTime.Now;
logMessage.SourceFile = sourceFile;
logMessage.CallingFunction = callingFunction;
logMessage.LineNumber = lineNumber;
Log(logMessage);
}
Log(logMessage);
}
public void LogWarning(string message, string sourceFile, string callingFunction, int lineNumber)
{
LogMessage logMessage = new LogMessage();
logMessage.Message = message;
logMessage.MessageType = LogMessage.LogMessageType.WARNING;
logMessage.Time = DateTime.Now;
logMessage.SourceFile = sourceFile;
logMessage.CallingFunction = callingFunction;
logMessage.LineNumber = lineNumber;
public void LogWarning(string message, string sourceFile, string callingFunction, int lineNumber)
{
LogMessage logMessage = new LogMessage();
logMessage.Message = message;
logMessage.MessageType = LogMessage.LogMessageType.WARNING;
logMessage.Time = DateTime.Now;
logMessage.SourceFile = sourceFile;
logMessage.CallingFunction = callingFunction;
logMessage.LineNumber = lineNumber;
Log(logMessage);
}
Log(logMessage);
}
public void LogError(string message, string sourceFile, string callingFunction, int lineNumber)
{
LogMessage logMessage = new LogMessage();
logMessage.Message = message;
logMessage.MessageType = LogMessage.LogMessageType.ERROR;
logMessage.Time = DateTime.Now;
logMessage.SourceFile = sourceFile;
logMessage.CallingFunction = callingFunction;
logMessage.LineNumber = lineNumber;
public void LogError(string message, string sourceFile, string callingFunction, int lineNumber)
{
LogMessage logMessage = new LogMessage();
logMessage.Message = message;
logMessage.MessageType = LogMessage.LogMessageType.ERROR;
logMessage.Time = DateTime.Now;
logMessage.SourceFile = sourceFile;
logMessage.CallingFunction = callingFunction;
logMessage.LineNumber = lineNumber;
Log(logMessage);
}
Log(logMessage);
}
private void Log(LogMessage message)
{
if(_loggingEnabled == true)
{
foreach (ILogger logger in _loggers)
{
logger.LogMessage(message);
}
}
}
}
private void Log(LogMessage message)
{
if(_loggingEnabled == true)
{
foreach (ILogger logger in _loggers)
{
logger.LogMessage(message);
}
}
}
}
}
@@ -6,85 +6,85 @@ using System.Threading.Tasks;
namespace CoatiSoftware.SourcetrailPlugin.Logging
{
public class LogMessage
{
public enum LogMessageType
{
UNKNOWN = 0,
INFO,
WARNING,
ERROR
}
public class LogMessage
{
public enum LogMessageType
{
UNKNOWN = 0,
INFO,
WARNING,
ERROR
}
private string _message = "";
private DateTime _time = new DateTime();
private LogMessageType _messageType = LogMessageType.UNKNOWN;
private string _message = "";
private DateTime _time = new DateTime();
private LogMessageType _messageType = LogMessageType.UNKNOWN;
private string _sourceFile = "";
private string _callingFunction = "";
private int _lineNumber = -1;
private string _sourceFile = "";
private string _callingFunction = "";
private int _lineNumber = -1;
public string Message
{
get { return _message; }
set { _message = value; }
}
public string Message
{
get { return _message; }
set { _message = value; }
}
public DateTime Time
{
get { return _time; }
set { _time = value; }
}
public DateTime Time
{
get { return _time; }
set { _time = value; }
}
public LogMessageType MessageType
{
get { return _messageType; }
set { _messageType = value; }
}
public LogMessageType MessageType
{
get { return _messageType; }
set { _messageType = value; }
}
public string SourceFile
{
get { return _sourceFile; }
set { _sourceFile = value; }
}
public string SourceFile
{
get { return _sourceFile; }
set { _sourceFile = value; }
}
public string CallingFunction
{
get { return _callingFunction; }
set { _callingFunction = value; }
}
public string CallingFunction
{
get { return _callingFunction; }
set { _callingFunction = value; }
}
public int LineNumber
{
get { return _lineNumber; }
set { _lineNumber = value; }
}
public int LineNumber
{
get { return _lineNumber; }
set { _lineNumber = value; }
}
public override string ToString()
{
string result = "";
public override string ToString()
{
string result = "";
result += _time.Hour.ToString() + ":" + _time.Minute.ToString() + ":"+ _time.Second.ToString();
result += _time.Hour.ToString() + ":" + _time.Minute.ToString() + ":"+ _time.Second.ToString();
result += "\t";
result += "\t";
result += _messageType.ToString();
result += "\t";
result += _messageType.ToString();
result += "\t";
result += _sourceFile + ":" + _lineNumber.ToString();
result += _sourceFile + ":" + _lineNumber.ToString();
result += " (";
result += " (";
result += _callingFunction;
result += _callingFunction;
result += ")";
result += ")";
result += "\t\t";
result += "\t\t";
result += _message;
result += _message;
return result;
}
}
return result;
}
}
}
@@ -7,39 +7,39 @@ using System.Runtime.CompilerServices;
namespace CoatiSoftware.SourcetrailPlugin.Logging
{
public class Logging
{
public static void LogInfo(string message, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)
{
int idx = file.LastIndexOf('\\');
if(idx > -1)
{
file = file.Substring(idx + 1);
}
public class Logging
{
public static void LogInfo(string message, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)
{
int idx = file.LastIndexOf('\\');
if(idx > -1)
{
file = file.Substring(idx + 1);
}
LogManager.GetInstance().LogInfo(message, file, member, line);
}
LogManager.GetInstance().LogInfo(message, file, member, line);
}
public static void LogWarning(string message, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)
{
int idx = file.LastIndexOf('\\');
if (idx > -1)
{
file = file.Substring(idx + 1);
}
public static void LogWarning(string message, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)
{
int idx = file.LastIndexOf('\\');
if (idx > -1)
{
file = file.Substring(idx + 1);
}
LogManager.GetInstance().LogWarning(message, file, member, line);
}
LogManager.GetInstance().LogWarning(message, file, member, line);
}
public static void LogError(string message, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)
{
int idx = file.LastIndexOf('\\');
if (idx > -1)
{
file = file.Substring(idx + 1);
}
public static void LogError(string message, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0)
{
int idx = file.LastIndexOf('\\');
if (idx > -1)
{
file = file.Substring(idx + 1);
}
LogManager.GetInstance().LogError(message, file, member, line);
}
}
LogManager.GetInstance().LogError(message, file, member, line);
}
}
}
@@ -3,131 +3,131 @@ using System.Collections.Generic;
namespace CoatiSoftware.SourcetrailPlugin.Logging.Obfuscation
{
class NameObfuscator
{
private static NameObfuscator _instance = null;
class NameObfuscator
{
private static NameObfuscator _instance = null;
private Dictionary<string, string> _dictionary = new Dictionary<string, string>();
private bool _enabled = false;
private Dictionary<string, string> _dictionary = new Dictionary<string, string>();
private bool _enabled = false;
char _currentChar = 'a';
int _currentInt = 0;
char _currentChar = 'a';
int _currentInt = 0;
private static string _directory = "";
private static string _fileNamePrefix = "Dictionary_SourcetrailPlugin_";
private static string _fileNameSufix = ".txt";
private static string _directory = "";
private static string _fileNamePrefix = "Dictionary_SourcetrailPlugin_";
private static string _fileNameSufix = ".txt";
private string _fileName = "";
private string _fileName = "";
private Queue<string> _messageBacklog = new Queue<string>(); // stores messages if the log file was in use at original logging time
private Queue<string> _messageBacklog = new Queue<string>(); // stores messages if the log file was in use at original logging time
private NameObfuscator()
{
DateTime time = DateTime.Now;
private NameObfuscator()
{
DateTime time = DateTime.Now;
string dateString = "";
dateString += time.Year.ToString() + "-" + time.Month.ToString() + "-" + time.Day.ToString() + "_";
dateString += time.Hour.ToString() + "-" + time.Minute.ToString() + "-" + time.Second.ToString();
string dateString = "";
dateString += time.Year.ToString() + "-" + time.Month.ToString() + "-" + time.Day.ToString() + "_";
dateString += time.Hour.ToString() + "-" + time.Minute.ToString() + "-" + time.Second.ToString();
_fileName = _fileNamePrefix + dateString + _fileNameSufix;
_fileName = _fileNamePrefix + dateString + _fileNameSufix;
_directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_directory += "\\Coati Software\\Plugins\\VS\\";
_directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_directory += "\\Coati Software\\Plugins\\VS\\";
if (System.IO.Directory.Exists(_directory) == false)
{
System.IO.Directory.CreateDirectory(_directory);
}
}
if (System.IO.Directory.Exists(_directory) == false)
{
System.IO.Directory.CreateDirectory(_directory);
}
}
private static void CreateInstance()
{
if (_instance == null)
{
_instance = new NameObfuscator();
}
}
private static void CreateInstance()
{
if (_instance == null)
{
_instance = new NameObfuscator();
}
}
public static string GetObfuscatedName(string originalName)
{
CreateInstance();
public static string GetObfuscatedName(string originalName)
{
CreateInstance();
if (_instance._enabled)
{
if (_instance._dictionary.ContainsKey(originalName))
{
return _instance._dictionary[originalName];
}
else
{
string newName = _instance.GetNewName();
_instance._dictionary[originalName] = newName;
if (_instance._enabled)
{
if (_instance._dictionary.ContainsKey(originalName))
{
return _instance._dictionary[originalName];
}
else
{
string newName = _instance.GetNewName();
_instance._dictionary[originalName] = newName;
_instance.WriteDictionaryEntryToFile(newName, originalName); // key and value reversed because that's the way the dictionary file is to be used...
return newName;
}
}
else
{
return originalName;
}
}
_instance.WriteDictionaryEntryToFile(newName, originalName); // key and value reversed because that's the way the dictionary file is to be used...
return newName;
}
}
else
{
return originalName;
}
}
public static void Enabled(bool enabled)
{
CreateInstance();
public static void Enabled(bool enabled)
{
CreateInstance();
_instance._enabled = enabled;
}
_instance._enabled = enabled;
}
private string GetNewName()
{
string name = "";
private string GetNewName()
{
string name = "";
name = _currentChar.ToString() + _currentInt.ToString();
name = _currentChar.ToString() + _currentInt.ToString();
++_currentChar;
++_currentChar;
if((int)_currentChar > 122)
{
_currentChar = 'a';
++_currentInt;
}
if((int)_currentChar > 122)
{
_currentChar = 'a';
++_currentInt;
}
return name;
}
return name;
}
private void WriteDictionaryEntryToFile(string key, string value)
{
System.IO.StreamWriter writer = null;
string message = key + " - " + value;
private void WriteDictionaryEntryToFile(string key, string value)
{
System.IO.StreamWriter writer = null;
string message = key + " - " + value;
try
{
writer = System.IO.File.AppendText(_directory + _fileName);
try
{
writer = System.IO.File.AppendText(_directory + _fileName);
// write backlog to file first
while (_messageBacklog.Count > 0)
{
string bm = _messageBacklog.Dequeue();
writer.WriteLine(bm);
}
// write backlog to file first
while (_messageBacklog.Count > 0)
{
string bm = _messageBacklog.Dequeue();
writer.WriteLine(bm);
}
writer.WriteLine(message.ToString());
writer.Close();
}
catch (Exception e)
{
// well...file is still in use
_messageBacklog.Enqueue(message.ToString());
}
finally
{
if (writer != null)
{
writer.Close();
}
}
}
}
writer.WriteLine(message.ToString());
writer.Close();
}
catch (Exception e)
{
// well...file is still in use
_messageBacklog.Enqueue(message.ToString());
}
finally
{
if (writer != null)
{
writer.Close();
}
}
}
}
}
@@ -7,74 +7,74 @@ using System.Diagnostics;
namespace CoatiSoftware.SourcetrailPlugin.Logging
{
class VSOutputLogger : ILogger
{
private EnvDTE.DTE _dte = null;
private OutputWindowPane _pane = null;
class VSOutputLogger : ILogger
{
private EnvDTE.DTE _dte = null;
private OutputWindowPane _pane = null;
public VSOutputLogger(EnvDTE.DTE dte)
{
_dte = dte;
}
public VSOutputLogger(EnvDTE.DTE dte)
{
_dte = dte;
}
public void LogMessage(LogMessage message)
{
if (message.MessageType == SourcetrailPlugin.Logging.LogMessage.LogMessageType.INFO)
{
Debug.WriteLine(message.Message, "Info");
WriteToOutputWindow("Info: " + message.Message);
}
if (message.MessageType == SourcetrailPlugin.Logging.LogMessage.LogMessageType.WARNING)
{
Debug.WriteLine(message.Message, "Warning");
WriteToOutputWindow("Warning: " + message.Message);
}
if (message.MessageType == SourcetrailPlugin.Logging.LogMessage.LogMessageType.ERROR)
{
Debug.WriteLine(message.Message, "Error");
WriteToOutputWindow("Error: " + message.Message);
}
}
public void LogMessage(LogMessage message)
{
if (message.MessageType == SourcetrailPlugin.Logging.LogMessage.LogMessageType.INFO)
{
Debug.WriteLine(message.Message, "Info");
WriteToOutputWindow("Info: " + message.Message);
}
if (message.MessageType == SourcetrailPlugin.Logging.LogMessage.LogMessageType.WARNING)
{
Debug.WriteLine(message.Message, "Warning");
WriteToOutputWindow("Warning: " + message.Message);
}
if (message.MessageType == SourcetrailPlugin.Logging.LogMessage.LogMessageType.ERROR)
{
Debug.WriteLine(message.Message, "Error");
WriteToOutputWindow("Error: " + message.Message);
}
}
private void WriteToOutputWindow(string message)
{
string paneName = "Sourcetrail Log";
private void WriteToOutputWindow(string message)
{
string paneName = "Sourcetrail Log";
if (_dte.Windows.Count > 0)
{
Window window = _dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);
OutputWindow outputWindow = (OutputWindow)window.Object;
if (_dte.Windows.Count > 0)
{
Window window = _dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);
OutputWindow outputWindow = (OutputWindow)window.Object;
OutputWindowPanes panes = outputWindow.OutputWindowPanes;
OutputWindowPanes panes = outputWindow.OutputWindowPanes;
if(_pane == null)
{
try
{
for (int i = 0; i < panes.Count; i++)
{
OutputWindowPane pane = panes.Item(i);
if(_pane == null)
{
try
{
for (int i = 0; i < panes.Count; i++)
{
OutputWindowPane pane = panes.Item(i);
if (pane.Name.Equals(paneName, StringComparison.CurrentCultureIgnoreCase))
{
_pane = outputWindow.OutputWindowPanes.Item(i);
break;
}
}
}
catch (Exception e)
{
if (pane.Name.Equals(paneName, StringComparison.CurrentCultureIgnoreCase))
{
_pane = outputWindow.OutputWindowPanes.Item(i);
break;
}
}
}
catch (Exception e)
{
}
}
}
}
if (_pane == null)
{
_pane = outputWindow.OutputWindowPanes.Add(paneName);
}
if (_pane == null)
{
_pane = outputWindow.OutputWindowPanes.Add(paneName);
}
_pane.OutputString(message + '\n');
}
}
}
_pane.OutputString(message + '\n');
}
}
}
}
@@ -9,130 +9,130 @@ using System.Threading.Tasks;
namespace CoatiSoftware.SourcetrailPlugin.Multitasking
{
class LimitedThreadsTaskScheduler : TaskScheduler
{
[ThreadStatic]
private static bool _currentThreadIsProcessingItems;
class LimitedThreadsTaskScheduler : TaskScheduler
{
[ThreadStatic]
private static bool _currentThreadIsProcessingItems;
private readonly LinkedList<Task> _tasks = new LinkedList<Task>();
private readonly LinkedList<Task> _tasks = new LinkedList<Task>();
private readonly int _maxNumberOfRunningThreads = 0;
private readonly int _maxNumberOfRunningThreads = 0;
private int _delegatesQueuedOrRunning = 0;
private int _delegatesQueuedOrRunning = 0;
public LimitedThreadsTaskScheduler(int maxNumberOfRunningThreads)
{
if (maxNumberOfRunningThreads < 1)
{
maxNumberOfRunningThreads = 1;
}
public LimitedThreadsTaskScheduler(int maxNumberOfRunningThreads)
{
if (maxNumberOfRunningThreads < 1)
{
maxNumberOfRunningThreads = 1;
}
_maxNumberOfRunningThreads = maxNumberOfRunningThreads;
}
_maxNumberOfRunningThreads = maxNumberOfRunningThreads;
}
protected override IEnumerable<Task> GetScheduledTasks()
{
bool lockTaken = false;
protected override IEnumerable<Task> GetScheduledTasks()
{
bool lockTaken = false;
try
{
Monitor.TryEnter(_tasks, ref lockTaken);
if(lockTaken)
{
return _tasks;
}
else
{
throw new NotSupportedException();
}
}
finally
{
if (lockTaken)
{
Monitor.Exit(_tasks);
}
}
}
try
{
Monitor.TryEnter(_tasks, ref lockTaken);
if(lockTaken)
{
return _tasks;
}
else
{
throw new NotSupportedException();
}
}
finally
{
if (lockTaken)
{
Monitor.Exit(_tasks);
}
}
}
protected override void QueueTask(Task task)
{
lock(_tasks)
{
_tasks.AddLast(task);
if(_delegatesQueuedOrRunning < _maxNumberOfRunningThreads)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
}
protected override void QueueTask(Task task)
{
lock(_tasks)
{
_tasks.AddLast(task);
if(_delegatesQueuedOrRunning < _maxNumberOfRunningThreads)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if(!_currentThreadIsProcessingItems)
{
return false;
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if(!_currentThreadIsProcessingItems)
{
return false;
}
if(taskWasPreviouslyQueued)
{
if(TryDequeue(task))
{
return base.TryExecuteTask(task);
}
else
{
return false;
}
}
else
{
return base.TryExecuteTask(task);
}
}
if(taskWasPreviouslyQueued)
{
if(TryDequeue(task))
{
return base.TryExecuteTask(task);
}
else
{
return false;
}
}
else
{
return base.TryExecuteTask(task);
}
}
private void NotifyThreadPoolOfPendingWork()
{
ThreadPool.UnsafeQueueUserWorkItem(_ =>
{
_currentThreadIsProcessingItems = true;
try
{
while(true)
{
Task item;
private void NotifyThreadPoolOfPendingWork()
{
ThreadPool.UnsafeQueueUserWorkItem(_ =>
{
_currentThreadIsProcessingItems = true;
try
{
while(true)
{
Task item;
lock(_tasks)
{
if(_tasks.Count <= 0)
{
--_delegatesQueuedOrRunning;
break;
}
lock(_tasks)
{
if(_tasks.Count <= 0)
{
--_delegatesQueuedOrRunning;
break;
}
item = _tasks.First.Value;
_tasks.RemoveFirst();
}
item = _tasks.First.Value;
_tasks.RemoveFirst();
}
base.TryExecuteTask(item);
}
}
finally
{
_currentThreadIsProcessingItems = false;
}
base.TryExecuteTask(item);
}
}
finally
{
_currentThreadIsProcessingItems = false;
}
}, null);
}
}, null);
}
protected sealed override bool TryDequeue(Task task)
{
lock(_tasks)
{
return _tasks.Remove(task);
}
}
}
protected sealed override bool TryDequeue(Task task)
{
lock(_tasks)
{
return _tasks.Remove(task);
}
}
}
}
@@ -4,12 +4,12 @@ using System;
namespace CoatiSoftware.SourcetrailPlugin
{
static class PkgCmdIDList
{
public const uint cmdidSourcetrailSetActiveToken = 0x104;
public const uint cmdidSourcetrailCreateProject = 0x105;
public const uint cmdidSourcetrailCreateCDB = 0x106;
public const uint cmdidSourcetrailOpenLogFolder = 0x107;
};
static class PkgCmdIDList
{
public const uint cmdidSourcetrailSetActiveToken = 0x104;
public const uint cmdidSourcetrailCreateProject = 0x105;
public const uint cmdidSourcetrailCreateCDB = 0x106;
public const uint cmdidSourcetrailOpenLogFolder = 0x107;
};
}
@@ -12,19 +12,19 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("SourcetrailPlugin")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
@@ -1,53 +1,85 @@
using Newtonsoft.Json;
namespace CoatiSoftware.SourcetrailPlugin.SolutionParser
{
public class CommandObject
{
private string _file = "";
private string _directory = "";
private string _command = "";
public class CompileCommand
{
private string _directory = "";
private string _command = "";
private string _file = "";
public string File
{
get { return _file; }
set
{
_file = value;
//_file = _file.Replace('"', '\'');
//_file = _file.Replace('\"', '\'');
//_file = _file.Replace("\\\"", "'");
}
}
[JsonProperty(propertyName: "directory")]
public string Directory
{
get { return _directory; }
set { _directory = value; }
}
public string Directory
{
get { return _directory; }
set { _directory = value; }
}
[JsonProperty(propertyName: "command")]
public string Command
{
get { return _command; }
set
{
_command = value;
//_command = _command.Replace('"', '\'');
//_command = _command.Replace("\"", "'");
//_command = _command.Replace("\\\"", "'");
}
}
public string Command
{
get { return _command; }
set
{
_command = value;
//_command = _command.Replace('"', '\'');
//_command = _command.Replace("\"", "'");
//_command = _command.Replace("\\\"", "'");
}
}
[JsonProperty(propertyName: "file")]
public string File
{
get { return _file; }
set
{
_file = value;
//_file = _file.Replace('"', '\'');
//_file = _file.Replace('\"', '\'');
//_file = _file.Replace("\\\"", "'");
}
}
public string SerializeJSON()
{
string result = "\t{\n";
public static bool operator ==(CompileCommand a, CompileCommand b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
result += "\t\t\"directory\": \"" + Directory + "\",\n";
result += "\t\t\"command\": \"" + Command + "\",\n";
result += "\t\t\"file\": \"" + File + "\"\n";
if (((object)a == null) || ((object)b == null))
{
return false;
}
result += "\t}";
if (a.File != b.File || a.Command != b.Command || a.Directory != b.Directory)
{
return false;
}
return result;
}
}
return true;
}
public static bool operator !=(CompileCommand a, CompileCommand b)
{
return !(a == b);
}
public string SerializeToJson()
{
return JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
public static CompileCommand DeserializeFromJson(string serialized)
{
CompileCommand command = null;
if (serialized.Length > 0)
{
command = JsonConvert.DeserializeObject<CompileCommand>(serialized);
}
return command;
}
}
}
@@ -5,347 +5,368 @@ using Newtonsoft.Json.Linq;
using System.IO;
using System.Threading;
using System;
using Newtonsoft.Json;
namespace CoatiSoftware.SourcetrailPlugin.SolutionParser
{
public class CompilationDatabase
{
private List<CommandObject> _commandObjects = new List<CommandObject>();
// meta data
private string _name = "";
private string _sourceProject = "";
private string _directory = "";
private System.DateTime _lastUpdated = new System.DateTime();
private List<string> _includedProjects = new List<string>();
private string _configurationName = "";
private string _platformName = "";
public string Name
{
get { return _name; }
set { _name = value; }
}
public string SourceProject
{
get { return _sourceProject; }
set { _sourceProject = value; }
}
public string Directory
{
get { return _directory; }
set { _directory = value; }
}
public System.DateTime LastUpdated
{
get { return _lastUpdated; }
set { _lastUpdated = value; }
}
public List<string> IncludedProjects
{
get { return _includedProjects; }
set { _includedProjects = value; }
}
public string ConfigurationName
{
get { return _configurationName; }
set { _configurationName = value; }
}
public string PlatformName
{
get { return _platformName; }
set { _platformName = value; }
}
public int CommandObjectCount
{
get { return _commandObjects.Count; }
}
public void AddOrUpdateCommandObject(CommandObject commandObject, bool saveImmediatly = false)
{
_commandObjects.Add(commandObject); // updating is not efficient as it is
}
// remove commandObjects for removed files
public void Clean()
{
for (int i = 0; i < _commandObjects.Count; i++)
{
if (System.IO.File.Exists(_commandObjects[i].File) == false)
{
_commandObjects.RemoveAt(i);
i--;
}
}
}
public void ClearCommandObjects()
{
_commandObjects.Clear();
}
public bool CheckCDBExists()
{
if (_directory.Length > 0 && _name.Length > 0)
{
string path = GetFilePath();
if(System.IO.File.Exists(path) == false)
{
_lastUpdated = System.DateTime.MinValue; // if file is missing, set date way back so it doesn't interfere with re-building
return false;
}
else
{
return true;
}
}
else
{
Logging.Logging.LogWarning("Can't check cdb data, directory and/or name has not been set: directory - '" + _directory + "', name - '" + _name + "'");
}
return false;
}
public bool TryLoadData()
{
if(_directory.Length > 0 && _name.Length > 0)
{
string path = GetFilePath();
if(System.IO.File.Exists(path))
{
string data = "";
using (System.IO.StreamReader file = new System.IO.StreamReader(path))
{
string line = "";
while ((line = file.ReadLine()) != null)
{
data += line;
}
}
DeserializeJSON(data);
return true;
}
else
{
_lastUpdated = System.DateTime.MinValue; // if file is missing, set date way back so it doesn't interfere with re-building
Logging.Logging.LogError("The cdb file '" + path + "' does not exist.");
}
}
else
{
Logging.Logging.LogWarning("Can't load cdb data, directory and/or name has not been set: directory - '" + _directory + "', name - '" + _name + "'");
}
return false;
}
public void UnloadData()
{
_commandObjects.Clear();
}
public string SerializeJSON()
{
string result = "[\n";
foreach(CommandObject cm in _commandObjects)
{
result += cm.SerializeJSON() + ",";
}
result += "\n]";
return result;
}
private void DeserializeJSON(string jsonCDB)
{
if(jsonCDB.Length > 0)
{
JArray commandObjects = JArray.Parse(jsonCDB);
_commandObjects.Clear();
foreach (JObject o in commandObjects.Children<JObject>())
{
CommandObject co = new CommandObject();
string directory = o.Property("directory").Value.ToString();
string command = o.Property("command").Value.ToString();
string file = o.Property("file").Value.ToString();
co.Directory = directory;
co.Command = command;
co.File = file;
_commandObjects.Add(co);
}
}
}
public XmlNode GetMetaDataXML(XmlDocument doc)
{
// XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("cdb");
XmlElement name = doc.CreateElement("name");
name.InnerText = _name;
XmlElement sourceProject = doc.CreateElement("sourceProject");
sourceProject.InnerText = _sourceProject;
XmlElement directory = doc.CreateElement("directory");
directory.InnerText = _directory;
XmlElement lastUpdated = doc.CreateElement("lastUpdated");
lastUpdated.InnerText = _lastUpdated.ToString();
XmlElement includedProjects = doc.CreateElement("includedProjects");
foreach (string project in _includedProjects)
{
XmlElement includedProject = doc.CreateElement("includedProject");
includedProject.InnerText = project;
includedProjects.AppendChild(includedProject);
}
XmlElement configuration = doc.CreateElement("configuration");
configuration.InnerText = _configurationName;
XmlElement platform = doc.CreateElement("platform");
platform.InnerText = _platformName;
root.AppendChild(name);
root.AppendChild(sourceProject);
root.AppendChild(directory);
root.AppendChild(lastUpdated);
root.AppendChild(includedProjects);
root.AppendChild(configuration);
root.AppendChild(platform);
return root;
}
public string SerializeMetaDataXML()
{
XmlDocument doc = new XmlDocument();
XmlNode root = GetMetaDataXML(doc);
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlSerializer serializer = new XmlSerializer(typeof(XmlElement));
serializer.Serialize(writer, root);
return writer.ToString();
}
public static List<CompilationDatabase> ParseCDBsMetaData(string data)
{
List<CompilationDatabase> cdbs = new List<CompilationDatabase>();
if(data.Length > 0)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNode root = doc.SelectSingleNode("cdbs");
XmlNodeList nodes = root.SelectNodes("cdb");
foreach (XmlNode node in nodes)
{
cdbs.Add(ParseCDBMetaData(node));
}
}
return cdbs;
}
public static CompilationDatabase ParseCDBMetaData(XmlNode node)
{
CompilationDatabase cdb = new CompilationDatabase();
XmlNode nameNode = node.SelectSingleNode("name");
string name = nameNode.InnerText;
XmlNode sourceNode = node.SelectSingleNode("sourceProject");
string source = sourceNode.InnerText;
XmlNode directoryNode = node.SelectSingleNode("directory");
string directory = directoryNode.InnerText;
XmlNode updatedNode = node.SelectSingleNode("lastUpdated");
string updated = updatedNode.InnerText;
System.DateTime updatedDate;
if(System.DateTime.TryParse(updated, out updatedDate) == false)
{
updatedDate = System.DateTime.MinValue;
}
XmlNode includedProjects = node.SelectSingleNode("includedProjects");
XmlNodeList includedProjectNodes = includedProjects.SelectNodes("includedProject");
List<string> includedProjectsList = new List<string>();
foreach(XmlNode p in includedProjectNodes)
{
includedProjectsList.Add(p.InnerText);
}
XmlNode configurationNode = node.SelectSingleNode("configuration");
string configuration = configurationNode.InnerText;
XmlNode platformNode = node.SelectSingleNode("platform");
string platform = platformNode.InnerText;
// if cdb file is not there anymore, set the modified date back so that a full update will be performed
if(System.IO.File.Exists(directory + "\\" + name + ".json") == false)
{
updatedDate = System.DateTime.MinValue;
}
cdb.Name = name;
cdb.SourceProject = source;
cdb.Directory = directory;
cdb.LastUpdated = updatedDate;
cdb.IncludedProjects = includedProjectsList;
cdb.ConfigurationName = configuration;
cdb.PlatformName = platform;
return cdb;
}
private bool TryUpdateCommandObject(CommandObject co)
{
CommandObject old = _commandObjects.Find(x => x.File == co.File);
if(old != null)
{
_commandObjects.Remove(old);
_commandObjects.Add(co);
return true;
}
return false;
}
private string GetFilePath()
{
return _directory + "\\" + _name + ".json";
}
}
public class CompilationDatabase
{
private List<CompileCommand> _compileCommands = new List<CompileCommand>();
// meta data
private string _name = "";
private string _sourceProject = "";
private string _directory = "";
private System.DateTime _lastUpdated = new System.DateTime();
private List<string> _includedProjects = new List<string>();
private string _configurationName = "";
private string _platformName = "";
public string Name
{
get { return _name; }
set { _name = value; }
}
public string SourceProject
{
get { return _sourceProject; }
set { _sourceProject = value; }
}
public string Directory
{
get { return _directory; }
set { _directory = value; }
}
public System.DateTime LastUpdated
{
get { return _lastUpdated; }
set { _lastUpdated = value; }
}
public List<string> IncludedProjects
{
get { return _includedProjects; }
set { _includedProjects = value; }
}
public string ConfigurationName
{
get { return _configurationName; }
set { _configurationName = value; }
}
public string PlatformName
{
get { return _platformName; }
set { _platformName = value; }
}
public int CompileCommandCount
{
get { return _compileCommands.Count; }
}
public static CompilationDatabase LoadFromFile(string filePath)
{
CompilationDatabase cdb = new CompilationDatabase();
cdb.Name = Path.GetFileNameWithoutExtension(filePath);
cdb.Directory = Path.GetDirectoryName(filePath);
bool success = cdb.TryLoadData();
return cdb;
}
public static bool operator ==(CompilationDatabase a, CompilationDatabase b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if (((object)a == null) || ((object)b == null))
{
return false;
}
if (a.CompileCommandCount != b.CompileCommandCount)
{
return false;
}
foreach (CompileCommand aCommand in a._compileCommands)
{
CompileCommand bCommand = b._compileCommands.Find(x => x == aCommand);
if (bCommand == null || aCommand.File != bCommand.File)
{
return false;
}
}
return true;
}
public static bool operator !=(CompilationDatabase a, CompilationDatabase b)
{
return !(a == b);
}
public void AddCommandObject(CompileCommand commandObject)
{
_compileCommands.Add(commandObject); // updating is not efficient as it is
}
// remove commandObjects for removed files
public void Clean()
{
for (int i = 0; i < _compileCommands.Count; i++)
{
if (System.IO.File.Exists(_compileCommands[i].File) == false)
{
_compileCommands.RemoveAt(i);
i--;
}
}
}
public void ClearCommandObjects()
{
_compileCommands.Clear();
}
public bool CheckCDBExists()
{
if (_directory.Length > 0 && _name.Length > 0)
{
string path = GetFilePath();
if(System.IO.File.Exists(path) == false)
{
_lastUpdated = System.DateTime.MinValue; // if file is missing, set date way back so it doesn't interfere with re-building
return false;
}
else
{
return true;
}
}
else
{
Logging.Logging.LogWarning("Can't check cdb data, directory and/or name has not been set: directory - '" + _directory + "', name - '" + _name + "'");
}
return false;
}
public bool TryLoadData()
{
if(_directory.Length > 0 && _name.Length > 0)
{
string path = GetFilePath();
if(System.IO.File.Exists(path))
{
string data = "";
using (System.IO.StreamReader file = new System.IO.StreamReader(path))
{
string line = "";
while ((line = file.ReadLine()) != null)
{
data += line;
}
}
DeserializeFromJson(data);
return true;
}
else
{
_lastUpdated = System.DateTime.MinValue; // if file is missing, set date way back so it doesn't interfere with re-building
Logging.Logging.LogError("The cdb file '" + path + "' does not exist.");
}
}
else
{
Logging.Logging.LogWarning("Can't load cdb data, directory and/or name has not been set: directory - '" + _directory + "', name - '" + _name + "'");
}
return false;
}
public void UnloadData()
{
_compileCommands.Clear();
}
public string SerializeToJson()
{
return JsonConvert.SerializeObject(_compileCommands, Newtonsoft.Json.Formatting.Indented);
}
public void DeserializeFromJson(string serialized)
{
_compileCommands.Clear();
if (serialized.Length > 0)
{
_compileCommands = JsonConvert.DeserializeObject<List<CompileCommand>>(serialized);
}
}
public XmlNode GetMetaDataXML(XmlDocument doc)
{
// XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("cdb");
XmlElement name = doc.CreateElement("name");
name.InnerText = _name;
XmlElement sourceProject = doc.CreateElement("sourceProject");
sourceProject.InnerText = _sourceProject;
XmlElement directory = doc.CreateElement("directory");
directory.InnerText = _directory;
XmlElement lastUpdated = doc.CreateElement("lastUpdated");
lastUpdated.InnerText = _lastUpdated.ToString();
XmlElement includedProjects = doc.CreateElement("includedProjects");
foreach (string project in _includedProjects)
{
XmlElement includedProject = doc.CreateElement("includedProject");
includedProject.InnerText = project;
includedProjects.AppendChild(includedProject);
}
XmlElement configuration = doc.CreateElement("configuration");
configuration.InnerText = _configurationName;
XmlElement platform = doc.CreateElement("platform");
platform.InnerText = _platformName;
root.AppendChild(name);
root.AppendChild(sourceProject);
root.AppendChild(directory);
root.AppendChild(lastUpdated);
root.AppendChild(includedProjects);
root.AppendChild(configuration);
root.AppendChild(platform);
return root;
}
public string SerializeMetaDataXML()
{
XmlDocument doc = new XmlDocument();
XmlNode root = GetMetaDataXML(doc);
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlSerializer serializer = new XmlSerializer(typeof(XmlElement));
serializer.Serialize(writer, root);
return writer.ToString();
}
public static List<CompilationDatabase> ParseCDBsMetaData(string data)
{
List<CompilationDatabase> cdbs = new List<CompilationDatabase>();
if(data.Length > 0)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNode root = doc.SelectSingleNode("cdbs");
XmlNodeList nodes = root.SelectNodes("cdb");
foreach (XmlNode node in nodes)
{
cdbs.Add(ParseCDBMetaData(node));
}
}
return cdbs;
}
public static CompilationDatabase ParseCDBMetaData(XmlNode node)
{
CompilationDatabase cdb = new CompilationDatabase();
XmlNode nameNode = node.SelectSingleNode("name");
string name = nameNode.InnerText;
XmlNode sourceNode = node.SelectSingleNode("sourceProject");
string source = sourceNode.InnerText;
XmlNode directoryNode = node.SelectSingleNode("directory");
string directory = directoryNode.InnerText;
XmlNode updatedNode = node.SelectSingleNode("lastUpdated");
string updated = updatedNode.InnerText;
System.DateTime updatedDate;
if(System.DateTime.TryParse(updated, out updatedDate) == false)
{
updatedDate = System.DateTime.MinValue;
}
XmlNode includedProjects = node.SelectSingleNode("includedProjects");
XmlNodeList includedProjectNodes = includedProjects.SelectNodes("includedProject");
List<string> includedProjectsList = new List<string>();
foreach(XmlNode p in includedProjectNodes)
{
includedProjectsList.Add(p.InnerText);
}
XmlNode configurationNode = node.SelectSingleNode("configuration");
string configuration = configurationNode.InnerText;
XmlNode platformNode = node.SelectSingleNode("platform");
string platform = platformNode.InnerText;
// if cdb file is not there anymore, set the modified date back so that a full update will be performed
if(System.IO.File.Exists(directory + "\\" + name + ".json") == false)
{
updatedDate = System.DateTime.MinValue;
}
cdb.Name = name;
cdb.SourceProject = source;
cdb.Directory = directory;
cdb.LastUpdated = updatedDate;
cdb.IncludedProjects = includedProjectsList;
cdb.ConfigurationName = configuration;
cdb.PlatformName = platform;
return cdb;
}
private bool TryUpdateCommandObject(CompileCommand co)
{
CompileCommand old = _compileCommands.Find(x => x.File == co.File);
if(old != null)
{
_compileCommands.Remove(old);
_compileCommands.Add(co);
return true;
}
return false;
}
private string GetFilePath()
{
return _directory + "\\" + _name + ".json";
}
}
}
@@ -0,0 +1,32 @@
using System;
using CoatiSoftware.SourcetrailPlugin.Utility;
using VCProjectEngineWrapper;
namespace CoatiSoftware.SourcetrailPlugin.SolutionParser
{
public class VsPathResolver : IPathResolver
{
private string _compilationDatabaseFilePath = "";
public VsPathResolver(string compilationDatabaseFilePath)
{
_compilationDatabaseFilePath = compilationDatabaseFilePath.Replace('\\', '/');
}
public override string GetCompilationDatabaseFilePath()
{
return _compilationDatabaseFilePath;
}
protected override string DoGetAsAbsoluteCanonicalPath(string path, IVCProjectWrapper project)
{
string absolutePath = project.GetProjectDirectory() + path;
return new Uri(absolutePath).LocalPath;
}
protected override string ResolveVsMacro(string potentialMacro, IVCConfigurationWrapper vcProjectConfig)
{
return vcProjectConfig.EvaluateMacro(potentialMacro);
}
}
}
@@ -1,13 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">11.0</VisualStudioVersion>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VisualStudioYear>2015</VisualStudioYear>
<VisualStudioYear Condition="'$(VisualStudioVersion)' &gt;= '15.0'">2017</VisualStudioYear>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
</PropertyGroup>
<PropertyGroup Condition="'$(VisualStudioVersion)' &gt;= '11.0'">
<MinimumVisualStudioVersion>$(VisualStudioVersion)</MinimumVisualStudioVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(VisualStudioVersion)' &gt;= '12.0'">
<OldToolsVersion>4.0</OldToolsVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
@@ -20,10 +22,10 @@
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CoatiSoftware.SourcetrailPlugin</RootNamespace>
<AssemblyName>sourcetrail_plugin_vs</AssemblyName>
<AssemblyName>sourcetrail_plugin</AssemblyName>
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>Key.snk</AssemblyOriginatorKeyFile>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -43,27 +45,60 @@
<WarningLevel>4</WarningLevel>
<RunCodeAnalysis>true</RunCodeAnalysis>
</PropertyGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' &gt;= '15'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.Shell.Framework, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise>
</Otherwise>
</Choose>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.VisualStudio.OLE.Interop" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop.8.0" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop.9.0" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop.10.0" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop.11.0">
<EmbedInteropTypes>true</EmbedInteropTypes>
<Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>False</EmbedInteropTypes>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TemplateWizardInterface, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="Microsoft.VisualStudio.TextManager.Interop" />
<Reference Include="Microsoft.VisualStudio.Shell.11.0" />
<Reference Include="Microsoft.VisualStudio.Shell.Immutable.10.0" />
<Reference Include="Microsoft.VisualStudio.Shell.Immutable.11.0" />
<Reference Include="Microsoft.VisualStudio.VCProjectEngine, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<Reference Include="EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>False</EmbedInteropTypes>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.VisualStudio.OLE.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.11.0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Immutable.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Immutable.11.0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.11.0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.VisualStudio.TemplateWizardInterface, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="Microsoft.VisualStudio.TextManager.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
@@ -74,45 +109,14 @@
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
<Reference Include="WindowsBase">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="Microsoft.VisualStudio.Package.LanguageService.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
</Reference>
</ItemGroup>
<ItemGroup>
<COMReference Include="EnvDTE">
<Guid>{80CC9F66-E7D8-4DDD-85B6-D9E6CD0E93E2}</Guid>
<VersionMajor>8</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
<COMReference Include="EnvDTE100">
<Guid>{26AD1324-4B7C-44BC-84F8-B86AED45729F}</Guid>
<VersionMajor>10</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
<COMReference Include="EnvDTE80">
<Guid>{1A31287A-4D7D-413E-8E32-3B374931BD89}</Guid>
<VersionMajor>8</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
<COMReference Include="EnvDTE90">
<Guid>{2CE2370E-D744-4936-A090-3FFFE667B0E1}</Guid>
<VersionMajor>9</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
<COMReference Include="Microsoft.VisualStudio.CommandBars">
<Guid>{1CBA492E-7263-47BB-87FE-639000619B15}</Guid>
<VersionMajor>8</VersionMajor>
@@ -133,6 +137,7 @@
</COMReference>
</ItemGroup>
<ItemGroup>
<Compile Include="ComUtils.cs" />
<Compile Include="Logging\FileLogger.cs" />
<Compile Include="Logging\ILogger.cs" />
<Compile Include="Logging\Logging.cs" />
@@ -141,6 +146,8 @@
<Compile Include="Logging\Obfuscation\NameObfuscator.cs" />
<Compile Include="Logging\VSOutputLogger.cs" />
<Compile Include="Multitasking\LimitedThreadsTaskScheduler.cs" />
<Compile Include="Utility\IPathResolver.cs" />
<Compile Include="SolutionParser\VsPathResolver.cs" />
<Compile Include="Utility\CompilationDatabaseList.cs" />
<Compile Include="Utility\DataUtility.cs" />
<Compile Include="Utility\FileUtility.cs" />
@@ -217,12 +224,12 @@
<DependentUpon>WindowMessage.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="source.extension.vsixmanifest">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="source.extension.vsixmanifest">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<None Include="Key.snk" />
</ItemGroup>
@@ -236,12 +243,24 @@
<Resource Include="Resources\favicon_16x16.png" />
</ItemGroup>
<ItemGroup>
<Content Include="LICENSE.txt">
<IncludeInVSIX>true</IncludeInVSIX>
</Content>
<Content Include="sourcetrail.ico">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<IncludeInVSIX>true</IncludeInVSIX>
</Content>
</ItemGroup>
<ItemGroup />
<ItemGroup>
<ProjectReference Include="..\VCProjectEngineWrapperFactories\VCProjectEngineWrapperFactories.csproj">
<Project>{8188d64d-e880-490c-b267-b493a2171be3}</Project>
<Name>VCProjectEngineWrapperFactories</Name>
</ProjectReference>
<ProjectReference Include="..\VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj">
<Project>{f592db46-0c77-470b-aaf8-80c51f44380e}</Project>
<Name>VCProjectEngineWrapperInterfaces</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup>
<UseCodebase>true</UseCodebase>
</PropertyGroup>
@@ -2,12 +2,16 @@
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartAction>Program</StartAction>
<StartProgram>C:\Program Files %28x86%29\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe</StartProgram>
<StartProgram>D:\programme\Microsoft Visual Studio\2017\Community\Common7\IDE\devenv.exe</StartProgram>
<StartArguments>/rootsuffix Exp</StartArguments>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<StartAction>Program</StartAction>
<StartProgram>C:\Program Files %28x86%29\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe</StartProgram>
<StartProgram>D:\programme\Microsoft Visual Studio14\Common7\IDE\devenv.exe</StartProgram>
<StartArguments>/rootsuffix Exp</StartArguments>
</PropertyGroup>
<PropertyGroup>
<ProjectView>ProjectFiles</ProjectView>
</PropertyGroup>
</Project>
File diff suppressed because it is too large Load Diff
@@ -5,155 +5,155 @@ using System.Xml.Serialization;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
class CompilationDatabaseList
{
private List<SolutionParser.CompilationDatabase> _cdbs = new List<SolutionParser.CompilationDatabase>();
class CompilationDatabaseList
{
private List<SolutionParser.CompilationDatabase> _cdbs = new List<SolutionParser.CompilationDatabase>();
public List<SolutionParser.CompilationDatabase> CDBs
{
get { return _cdbs; }
// set { _cdbs = value; }
}
public List<SolutionParser.CompilationDatabase> CDBs
{
get { return _cdbs; }
// set { _cdbs = value; }
}
public CompilationDatabaseList()
{
Refresh();
}
public CompilationDatabaseList()
{
Refresh();
}
public void AppendOrUpdate(SolutionParser.CompilationDatabase cdb)
{
if(_cdbs.Exists(item => item.Name == cdb.Name && item.Directory == cdb.Directory) == false)
{
_cdbs.Add(cdb);
}
else
{
int idx = _cdbs.FindIndex(item => item.Name == cdb.Name && item.Directory == cdb.Directory);
_cdbs[idx] = cdb;
}
}
public void AppendOrUpdate(SolutionParser.CompilationDatabase cdb)
{
if(_cdbs.Exists(item => item.Name == cdb.Name && item.Directory == cdb.Directory) == false)
{
_cdbs.Add(cdb);
}
else
{
int idx = _cdbs.FindIndex(item => item.Name == cdb.Name && item.Directory == cdb.Directory);
_cdbs[idx] = cdb;
}
}
public void Refresh()
{
List<SolutionParser.CompilationDatabase> cdbs = new List<SolutionParser.CompilationDatabase>();
public void Refresh()
{
List<SolutionParser.CompilationDatabase> cdbs = new List<SolutionParser.CompilationDatabase>();
try
{
string data = Utility.DataUtility.GetInstance().GetData();
cdbs = SolutionParser.CompilationDatabase.ParseCDBsMetaData(data);
try
{
string data = Utility.DataUtility.GetInstance().GetData();
cdbs = SolutionParser.CompilationDatabase.ParseCDBsMetaData(data);
foreach (SolutionParser.CompilationDatabase cdb in cdbs)
{
cdb.CheckCDBExists();
}
}
catch (Exception e)
{
Logging.Logging.LogError("Failed to aquire data: " + e.Message);
}
foreach (SolutionParser.CompilationDatabase cdb in cdbs)
{
cdb.CheckCDBExists();
}
}
catch (Exception e)
{
Logging.Logging.LogError("Failed to aquire data: " + e.Message);
}
_cdbs = cdbs;
}
_cdbs = cdbs;
}
public List<SolutionParser.CompilationDatabase> GetCDBsForSolution(string solutionPath)
{
return _cdbs.FindAll(item => item.SourceProject == solutionPath);
}
public List<SolutionParser.CompilationDatabase> GetCDBsForSolution(string solutionPath)
{
return _cdbs.FindAll(item => item.SourceProject == solutionPath);
}
public SolutionParser.CompilationDatabase GetCDBForSolution(string solutionPath)
{
return _cdbs.Find(item => item.SourceProject == solutionPath);
}
public SolutionParser.CompilationDatabase GetCDBForSolution(string solutionPath)
{
return _cdbs.Find(item => item.SourceProject == solutionPath);
}
public SolutionParser.CompilationDatabase GetMostCurrentCDBForSolution(string solutionPath)
{
SolutionParser.CompilationDatabase result = null;
public SolutionParser.CompilationDatabase GetMostCurrentCDBForSolution(string solutionPath)
{
SolutionParser.CompilationDatabase result = null;
try
{
List<SolutionParser.CompilationDatabase> candidates = GetCDBsForSolution(solutionPath);
try
{
List<SolutionParser.CompilationDatabase> candidates = GetCDBsForSolution(solutionPath);
System.DateTime youngest = System.DateTime.MinValue;
foreach (SolutionParser.CompilationDatabase cdb in candidates)
{
if (cdb.LastUpdated >= youngest)
{
youngest = cdb.LastUpdated;
result = cdb;
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to find cdb: " + e.Message);
}
System.DateTime youngest = System.DateTime.MinValue;
foreach (SolutionParser.CompilationDatabase cdb in candidates)
{
if (cdb.LastUpdated >= youngest)
{
youngest = cdb.LastUpdated;
result = cdb;
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to find cdb: " + e.Message);
}
return result;
}
return result;
}
public SolutionParser.CompilationDatabase GetCDBForSolution(string solutionPath, string cdbPath)
{
return _cdbs.Find(item => item.SourceProject == solutionPath && (item.Directory + "\\" + item.Name + ".json") == cdbPath);
}
public SolutionParser.CompilationDatabase GetCDBForSolution(string solutionPath, string cdbPath)
{
return _cdbs.Find(item => item.SourceProject == solutionPath && (item.Directory + "\\" + item.Name + ".json") == cdbPath);
}
public bool CheckCDBForSolutionExists(string solutionPath)
{
try
{
SolutionParser.CompilationDatabase cdb = GetCDBForSolution(solutionPath);
if (cdb != null && System.IO.File.Exists(cdb.Directory + "\\" + cdb.Name + ".json"))
{
return true;
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to check cdb: " + e.Message);
}
public bool CheckCDBForSolutionExists(string solutionPath)
{
try
{
SolutionParser.CompilationDatabase cdb = GetCDBForSolution(solutionPath);
if (cdb != null && System.IO.File.Exists(cdb.Directory + "\\" + cdb.Name + ".json"))
{
return true;
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to check cdb: " + e.Message);
}
return false;
}
return false;
}
public void SaveMetaData()
{
try
{
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("cdbs");
public void SaveMetaData()
{
try
{
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("cdbs");
foreach (SolutionParser.CompilationDatabase cdb in _cdbs)
{
XmlNode metaData = cdb.GetMetaDataXML(doc);
foreach (SolutionParser.CompilationDatabase cdb in _cdbs)
{
XmlNode metaData = cdb.GetMetaDataXML(doc);
root.AppendChild(metaData);
}
root.AppendChild(metaData);
}
System.IO.StringWriter writer = new System.IO.StringWriter();
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlSerializer serializer = new XmlSerializer(typeof(XmlElement));
serializer.Serialize(writer, root);
XmlSerializer serializer = new XmlSerializer(typeof(XmlElement));
serializer.Serialize(writer, root);
DataUtility.GetInstance().ClearData();
DataUtility.GetInstance().AppendData(writer.ToString());
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to save meta data: " + e.Message);
}
}
DataUtility.GetInstance().ClearData();
DataUtility.GetInstance().AppendData(writer.ToString());
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to save meta data: " + e.Message);
}
}
public void UnloadCDBs()
{
if(_cdbs == null)
{
Logging.Logging.LogWarning("Member '_cdbs' is null, aborting.");
return;
}
public void UnloadCDBs()
{
if(_cdbs == null)
{
Logging.Logging.LogWarning("Member '_cdbs' is null, aborting.");
return;
}
foreach(SolutionParser.CompilationDatabase cdb in _cdbs)
{
cdb.ClearCommandObjects();
}
}
}
foreach(SolutionParser.CompilationDatabase cdb in _cdbs)
{
cdb.ClearCommandObjects();
}
}
}
}
@@ -2,129 +2,129 @@
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
class DataUtility
{
static private string _standardFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Coati Software\\Plugins\\VS\\";
static private string _standardFileName = "cdbs.sourcetraildata";
class DataUtility
{
static private string _standardFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Coati Software\\Plugins\\VS\\";
static private string _standardFileName = "cdbs.sourcetraildata";
static private DataUtility _instance = null;
static private DataUtility _instance = null;
static private bool _valid = true; // stores if a file system operation failed, indicating that there is something wrong
static private bool _valid = true; // stores if a file system operation failed, indicating that there is something wrong
static public string GetStandardFolderDirectory()
{
return _standardFolder;
}
static public string GetStandardFolderDirectory()
{
return _standardFolder;
}
static bool Valid
{
get { return _valid; }
}
static bool Valid
{
get { return _valid; }
}
static public DataUtility GetInstance()
{
if(_instance == null)
{
_instance = new DataUtility();
}
static public DataUtility GetInstance()
{
if(_instance == null)
{
_instance = new DataUtility();
}
return _instance;
}
return _instance;
}
private DataUtility()
{
CreateStandardFolderIfNotExists();
CreateStandardFileIfNotExists();
}
private DataUtility()
{
CreateStandardFolderIfNotExists();
CreateStandardFileIfNotExists();
}
public void AppendData(string data)
{
try
{
using (System.IO.StreamWriter file = System.IO.File.AppendText(_standardFolder + _standardFileName))
{
file.WriteLine(data);
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to write data to file '" + _standardFolder + _standardFileName + "':" + e.Message);
_valid = false;
}
}
public void AppendData(string data)
{
try
{
using (System.IO.StreamWriter file = System.IO.File.AppendText(_standardFolder + _standardFileName))
{
file.WriteLine(data);
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to write data to file '" + _standardFolder + _standardFileName + "':" + e.Message);
_valid = false;
}
}
public string GetData()
{
string result = "";
public string GetData()
{
string result = "";
try
{
string data = "";
if (System.IO.File.Exists(_standardFolder + _standardFileName))
{
using (System.IO.StreamReader file = new System.IO.StreamReader(_standardFolder + _standardFileName))
{
string line = "";
try
{
string data = "";
if (System.IO.File.Exists(_standardFolder + _standardFileName))
{
using (System.IO.StreamReader file = new System.IO.StreamReader(_standardFolder + _standardFileName))
{
string line = "";
while ((line = file.ReadLine()) != null)
{
data += line;
}
}
}
result = data;
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to read data from file '" + _standardFolder + _standardFileName + "':" + e.Message);
_valid = false;
}
while ((line = file.ReadLine()) != null)
{
data += line;
}
}
}
result = data;
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to read data from file '" + _standardFolder + _standardFileName + "':" + e.Message);
_valid = false;
}
return result;
}
return result;
}
public void ClearData()
{
try
{
System.IO.File.WriteAllText(_standardFolder + _standardFileName, "");
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to clear data: " + e.Message);
}
}
public void ClearData()
{
try
{
System.IO.File.WriteAllText(_standardFolder + _standardFileName, "");
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to clear data: " + e.Message);
}
}
private void CreateStandardFolderIfNotExists()
{
try
{
if (System.IO.Directory.Exists(_standardFolder) == false)
{
System.IO.Directory.CreateDirectory(_standardFolder);
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create folder: " + e.Message);
_valid = false;
}
}
private void CreateStandardFolderIfNotExists()
{
try
{
if (System.IO.Directory.Exists(_standardFolder) == false)
{
System.IO.Directory.CreateDirectory(_standardFolder);
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create folder: " + e.Message);
_valid = false;
}
}
private void CreateStandardFileIfNotExists()
{
try
{
if (System.IO.File.Exists(_standardFolder + _standardFileName) == false)
{
System.IO.File.Create(_standardFolder + _standardFileName);
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create file: " + e.Message);
_valid = false;
}
}
}
private void CreateStandardFileIfNotExists()
{
try
{
if (System.IO.File.Exists(_standardFolder + _standardFileName) == false)
{
System.IO.File.Create(_standardFolder + _standardFileName);
}
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create file: " + e.Message);
_valid = false;
}
}
}
}
@@ -3,76 +3,76 @@ using EnvDTE;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
class FileUtility
{
public delegate void ErrorCallback(string message);
class FileUtility
{
public delegate void ErrorCallback(string message);
public static ErrorCallback _errorCallback = null;
public static ErrorCallback _errorCallback = null;
/**
* Returns true when file was found, false otherwise
*/
public static bool OpenSourceFile(DTE dte, string fileName)
{
try
{
dte.ItemOperations.OpenFile(fileName);
return true;
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
/**
* Returns true when file was found, false otherwise
*/
public static bool OpenSourceFile(DTE dte, string fileName)
{
try
{
dte.ItemOperations.OpenFile(fileName);
return true;
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
if (_errorCallback != null)
{
_errorCallback("Failed to open file at " + fileName);
}
if (_errorCallback != null)
{
_errorCallback("Failed to open file at " + fileName);
}
string message = "Failed to open file at " + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(fileName);
Logging.Logging.LogError(message);
string message = "Failed to open file at " + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(fileName);
Logging.Logging.LogError(message);
return false;
}
}
return false;
}
}
public static void GoToLine(DTE dte, int lineNumber, int columnNumber)
{
try
{
((EnvDTE.TextSelection)dte.ActiveDocument.Selection).MoveToLineAndOffset(lineNumber, columnNumber);
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
public static void GoToLine(DTE dte, int lineNumber, int columnNumber)
{
try
{
((EnvDTE.TextSelection)dte.ActiveDocument.Selection).MoveToLineAndOffset(lineNumber, columnNumber);
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
if (_errorCallback != null)
{
_errorCallback("Failed to set cursor to position [" + lineNumber.ToString() + "," + columnNumber.ToString() + "]");
if (_errorCallback != null)
{
_errorCallback("Failed to set cursor to position [" + lineNumber.ToString() + "," + columnNumber.ToString() + "]");
string message = "Failed to set cursor to position [" + lineNumber.ToString() + "," + columnNumber.ToString() + "]";
Logging.Logging.LogError(message);
}
}
}
string message = "Failed to set cursor to position [" + lineNumber.ToString() + "," + columnNumber.ToString() + "]";
Logging.Logging.LogError(message);
}
}
}
public static string GetActiveDocumentName(DTE dte)
{
return dte.ActiveDocument.Name;
}
public static string GetActiveDocumentName(DTE dte)
{
return dte.ActiveDocument.Name;
}
public static string GetActiveDocumentPath(DTE dte)
{
return dte.ActiveDocument.Path;
}
public static string GetActiveDocumentPath(DTE dte)
{
return dte.ActiveDocument.Path;
}
public static int GetActiveLineNumber(DTE dte)
{
return ((EnvDTE.TextSelection)dte.ActiveDocument.Selection).ActivePoint.Line;
}
public static int GetActiveLineNumber(DTE dte)
{
return ((EnvDTE.TextSelection)dte.ActiveDocument.Selection).ActivePoint.Line;
}
public static int GetActiveColumnNumber(DTE dte)
{
return ((EnvDTE.TextSelection)dte.ActiveDocument.Selection).ActivePoint.LineCharOffset;
}
}
public static int GetActiveColumnNumber(DTE dte)
{
return ((EnvDTE.TextSelection)dte.ActiveDocument.Selection).ActivePoint.LineCharOffset;
}
}
}
@@ -0,0 +1,48 @@
using System;
using VCProjectEngineWrapper;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
public abstract class IPathResolver
{
public string ResolveVsMacroInPath(string path, IVCConfigurationWrapper vcProjectConfig)
{
string result = path;
try
{
Tuple<int, int> potentialMacroPosition = Utility.StringUtility.FindFirstRange(path, "$(", ")");
if (potentialMacroPosition != null)
{
string potentialMacro = path.Substring(potentialMacroPosition.Item1, potentialMacroPosition.Item2 - potentialMacroPosition.Item1 + 1);
string resolvedMacro = ResolveVsMacro(potentialMacro, vcProjectConfig);
result = path.Substring(0, potentialMacroPosition.Item1) + resolvedMacro + path.Substring(potentialMacroPosition.Item2 + 1);
}
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
return result;
}
public string GetAsAbsoluteCanonicalPath(string path, IVCProjectWrapper project)
{
if (path.Length > 0 && !System.IO.Path.IsPathRooted(path))
{
path = DoGetAsAbsoluteCanonicalPath(path, project);
}
return path;
}
public abstract string GetCompilationDatabaseFilePath();
protected abstract string DoGetAsAbsoluteCanonicalPath(string path, IVCProjectWrapper project);
protected abstract string ResolveVsMacro(string potentialMacro, IVCConfigurationWrapper vcProjectConfig);
}
}
@@ -6,296 +6,296 @@ using System.Threading.Tasks;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
class NetworkProtocolUtility
{
private static string s_divider = ">>";
private static string s_setActiveTokenPrefix = "setActiveToken";
private static string s_moveCursorPrefix = "moveCursor";
private static string s_endOfMessageToken = "<EOM>";
class NetworkProtocolUtility
{
private static string s_divider = ">>";
private static string s_setActiveTokenPrefix = "setActiveToken";
private static string s_moveCursorPrefix = "moveCursor";
private static string s_endOfMessageToken = "<EOM>";
private static string s_createProjectPrefix = "createProject"; // deprecate
private static string s_createCDBProjectPrefix = "createCDBProject";
private static string s_ideId = "vs";
private static string s_createProjectPrefix = "createProject"; // deprecate
private static string s_createCDBProjectPrefix = "createCDBProject";
private static string s_ideId = "vs";
private static string s_createCDBPrefix = "createCDB";
private static string s_createCDBPrefix = "createCDB";
private static string s_pingPrefix = "ping";
private static string s_pingPrefix = "ping";
public enum MESSAGE_TYPE
{
UNKNOWN = 0,
MOVE_CURSOR,
CREATE_CDB,
PING
}
public enum MESSAGE_TYPE
{
UNKNOWN = 0,
MOVE_CURSOR,
CREATE_CDB,
PING
}
public class CursorPosition
{
private string _filePath = "";
private int _lineNumber = 0;
private int _columnNumber = 0;
private bool _valid = false;
public class CursorPosition
{
private string _filePath = "";
private int _lineNumber = 0;
private int _columnNumber = 0;
private bool _valid = false;
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
public int LineNumber
{
get { return _lineNumber; }
set { _lineNumber = value; }
}
public int LineNumber
{
get { return _lineNumber; }
set { _lineNumber = value; }
}
public int ColumnNumber
{
get { return _columnNumber; }
set { _columnNumber = value; }
}
public int ColumnNumber
{
get { return _columnNumber; }
set { _columnNumber = value; }
}
public bool Valid
{
get { return _valid; }
set { _valid = value; }
}
}
public bool Valid
{
get { return _valid; }
set { _valid = value; }
}
}
public class Ping
{
private string _id = "";
private bool _valid = false;
public string Id
{
get { return _id; }
set { _id = value; }
}
public class Ping
{
private string _id = "";
private bool _valid = false;
public string Id
{
get { return _id; }
set { _id = value; }
}
public bool Valid
{
get { return _valid; }
set { _valid = value; }
}
}
public bool Valid
{
get { return _valid; }
set { _valid = value; }
}
}
public static string CreateActivateTokenMessage(string filePath, int lineNumber, int columnNumber)
{
string message = s_setActiveTokenPrefix;
public static string CreateActivateTokenMessage(string filePath, int lineNumber, int columnNumber)
{
string message = s_setActiveTokenPrefix;
message += s_divider;
message += s_divider;
message += filePath;
message += filePath;
message += s_divider;
message += s_divider;
message += lineNumber.ToString();
message += lineNumber.ToString();
message += s_divider;
message += s_divider;
message += columnNumber.ToString();
message += columnNumber.ToString();
message += s_endOfMessageToken;
message += s_endOfMessageToken;
return message;
}
return message;
}
public static string CreateCreateProjectMessage(string solutionPath)
{
string message = s_createProjectPrefix;
public static string CreateCreateProjectMessage(string solutionPath)
{
string message = s_createProjectPrefix;
message += s_divider;
message += s_divider;
message += solutionPath;
message += solutionPath;
message += s_divider;
message += s_divider;
message += s_ideId;
message += s_ideId;
message += s_endOfMessageToken;
return message;
}
message += s_endOfMessageToken;
return message;
}
public static string CreateCreateProjectMessage(string cdbPath, List<string> headerPaths)
{
string message = s_createCDBProjectPrefix;
message += s_divider;
message += cdbPath;
message += s_divider;
foreach(string path in headerPaths)
{
message += path;
message += s_divider;
}
message += s_ideId;
message += s_endOfMessageToken;
return message;
}
public static string CreatePingMessage()
{
string message = s_pingPrefix;
message += s_divider;
message += s_ideId;
message += s_endOfMessageToken;
return message;
}
public static string CreateCreateProjectMessage(string cdbPath, List<string> headerPaths)
{
string message = s_createCDBProjectPrefix;
message += s_divider;
message += cdbPath;
message += s_divider;
foreach(string path in headerPaths)
{
message += path;
message += s_divider;
}
message += s_ideId;
message += s_endOfMessageToken;
return message;
}
public static string CreatePingMessage()
{
string message = s_pingPrefix;
message += s_divider;
message += s_ideId;
message += s_endOfMessageToken;
return message;
}
public static MESSAGE_TYPE GetMessageType(string message)
{
List<string> tokens = GetMessageTokens(message);
public static MESSAGE_TYPE GetMessageType(string message)
{
List<string> tokens = GetMessageTokens(message);
if (tokens.Count > 0)
{
if (tokens[0] == s_createCDBPrefix)
{
return MESSAGE_TYPE.CREATE_CDB;
}
else if (tokens[0] == s_moveCursorPrefix)
{
return MESSAGE_TYPE.MOVE_CURSOR;
}
else if (tokens[0] == s_pingPrefix)
{
return MESSAGE_TYPE.PING;
}
else
{
return MESSAGE_TYPE.UNKNOWN;
}
}
if (tokens.Count > 0)
{
if (tokens[0] == s_createCDBPrefix)
{
return MESSAGE_TYPE.CREATE_CDB;
}
else if (tokens[0] == s_moveCursorPrefix)
{
return MESSAGE_TYPE.MOVE_CURSOR;
}
else if (tokens[0] == s_pingPrefix)
{
return MESSAGE_TYPE.PING;
}
else
{
return MESSAGE_TYPE.UNKNOWN;
}
}
return MESSAGE_TYPE.UNKNOWN;
}
return MESSAGE_TYPE.UNKNOWN;
}
public static CursorPosition ParseSetCursorMessage(string message)
{
CursorPosition result = new CursorPosition();
public static CursorPosition ParseSetCursorMessage(string message)
{
CursorPosition result = new CursorPosition();
List<string> tokens = GetMessageTokens(message);
List<string> tokens = GetMessageTokens(message);
if(tokens.Count != 4)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid token count for 'move cursor' message. Expected 4, but got " + tokens.Count.ToString());
return result;
}
if(tokens[0] != s_moveCursorPrefix)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid message type. Expected '" + s_moveCursorPrefix + "' but got '" + tokens[0] + "'");
return result;
}
result.FilePath = tokens[1];
int lineNumber = 0;
if(int.TryParse(tokens[2], out lineNumber))
{
result.LineNumber = lineNumber;
}
else
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Failed to parse line number");
return result;
}
int columnNumber = 0;
if(int.TryParse(tokens[3], out columnNumber))
{
result.ColumnNumber = columnNumber;
}
else
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Failed to parse column number");
return result;
}
result.Valid = true;
return result;
}
public static Ping ParsePingMessage(string message)
{
Ping result = new Ping();
List<string> tokens = GetMessageTokens(message);
if(tokens.Count != 2)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid token count for 'ping' message. Expected 2, but got " + tokens.Count.ToString());
return result;
}
if (tokens[0] != s_pingPrefix)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid message type. Expected '" + s_pingPrefix + "' but got '" + tokens[0] + "'");
return result;
}
result.Id = tokens[1];
result.Valid = true;
return result;
}
private static List<string> GetMessageTokens(string message)
{
List<string> tokens = new List<string>();
if(RemoveEOMString(ref message))
{
tokens = message.Split(s_divider.ToCharArray()).ToList();
// removing empty strings
List<string> cleanTokens = new List<string>();
foreach(string token in tokens)
{
if(token.Length > 0)
{
cleanTokens.Add(token);
}
}
tokens = cleanTokens;
}
else
{
Logging.Logging.LogError("");
}
return tokens;
}
// returns false if no EOM string was found
private static bool RemoveEOMString(ref string message)
{
if (message.IndexOf(s_endOfMessageToken) > -1)
{
message = message.Substring(0, message.IndexOf(s_endOfMessageToken));
return true;
}
return false;
}
}
if(tokens.Count != 4)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid token count for 'move cursor' message. Expected 4, but got " + tokens.Count.ToString());
return result;
}
if(tokens[0] != s_moveCursorPrefix)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid message type. Expected '" + s_moveCursorPrefix + "' but got '" + tokens[0] + "'");
return result;
}
result.FilePath = tokens[1];
int lineNumber = 0;
if(int.TryParse(tokens[2], out lineNumber))
{
result.LineNumber = lineNumber;
}
else
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Failed to parse line number");
return result;
}
int columnNumber = 0;
if(int.TryParse(tokens[3], out columnNumber))
{
result.ColumnNumber = columnNumber;
}
else
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Failed to parse column number");
return result;
}
result.Valid = true;
return result;
}
public static Ping ParsePingMessage(string message)
{
Ping result = new Ping();
List<string> tokens = GetMessageTokens(message);
if(tokens.Count != 2)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid token count for 'ping' message. Expected 2, but got " + tokens.Count.ToString());
return result;
}
if (tokens[0] != s_pingPrefix)
{
Logging.Logging.LogError("Invalid message: " + message);
Logging.Logging.LogError("Invalid message type. Expected '" + s_pingPrefix + "' but got '" + tokens[0] + "'");
return result;
}
result.Id = tokens[1];
result.Valid = true;
return result;
}
private static List<string> GetMessageTokens(string message)
{
List<string> tokens = new List<string>();
if(RemoveEOMString(ref message))
{
tokens = message.Split(s_divider.ToCharArray()).ToList();
// removing empty strings
List<string> cleanTokens = new List<string>();
foreach(string token in tokens)
{
if(token.Length > 0)
{
cleanTokens.Add(token);
}
}
tokens = cleanTokens;
}
else
{
Logging.Logging.LogError("");
}
return tokens;
}
// returns false if no EOM string was found
private static bool RemoveEOMString(ref string message)
{
if (message.IndexOf(s_endOfMessageToken) > -1)
{
message = message.Substring(0, message.IndexOf(s_endOfMessageToken));
return true;
}
return false;
}
}
}
@@ -7,271 +7,271 @@ using System.Net;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
public class StateObject
{
public Socket _workSocket = null;
public const int _bufferSize = 1024;
public byte[] _buffer = new byte[_bufferSize];
public StringBuilder _stringBuilder = new StringBuilder();
}
public class StateObject
{
public Socket _workSocket = null;
public const int _bufferSize = 1024;
public byte[] _buffer = new byte[_bufferSize];
public StringBuilder _stringBuilder = new StringBuilder();
}
public class AsynchronousSocketListener
{
public static ManualResetEvent _allDone = new ManualResetEvent(false);
public class AsynchronousSocketListener
{
public static ManualResetEvent _allDone = new ManualResetEvent(false);
public delegate void OnReadCallback(string message);
public delegate void OnReadCallback(string message);
public static OnReadCallback _onReadCallback = null;
public static OnReadCallback _onErrorCallback = null;
public static OnReadCallback _onReadCallback = null;
public static OnReadCallback _onErrorCallback = null;
private static string _endOfMessageToken = "<EOM>";
private static string _endOfMessageToken = "<EOM>";
public static uint _port = 6666;
public AsynchronousSocketListener()
{
}
public static uint _port = 6666;
public AsynchronousSocketListener()
{
}
public void DoWork()
{
StartListening();
}
public void DoWork()
{
StartListening();
}
public static void StartListening()
{
const string ipAddressString = "127.0.0.1";
public static void StartListening()
{
const string ipAddressString = "127.0.0.1";
byte[] bytes = new Byte[1024];
byte[] bytes = new Byte[1024];
IPAddress ipAddress = IPAddress.Parse(ipAddressString);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, (int)_port);
IPAddress ipAddress = IPAddress.Parse(ipAddressString);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, (int)_port);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
_allDone.Reset();
while (true)
{
_allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
_allDone.WaitOne();
}
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
_allDone.WaitOne();
}
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
public static void AcceptCallback(IAsyncResult ar)
{
try
{
_allDone.Set();
public static void AcceptCallback(IAsyncResult ar)
{
try
{
_allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state._workSocket = handler;
handler.BeginReceive(state._buffer, 0, StateObject._bufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
StateObject state = new StateObject();
state._workSocket = handler;
handler.BeginReceive(state._buffer, 0, StateObject._bufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
public static void ReadCallback(IAsyncResult ar)
{
try
{
string content = String.Empty;
public static void ReadCallback(IAsyncResult ar)
{
try
{
string content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state._workSocket;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state._workSocket;
int bytesRead = handler.EndReceive(ar);
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state._stringBuilder.Append(Encoding.ASCII.GetString(state._buffer, 0, bytesRead));
if (bytesRead > 0)
{
state._stringBuilder.Append(Encoding.ASCII.GetString(state._buffer, 0, bytesRead));
content = state._stringBuilder.ToString();
if (content.IndexOf(_endOfMessageToken) > -1)
{
if (_onReadCallback != null)
{
_onReadCallback(content);
}
}
else
{
handler.BeginReceive(state._buffer, 0, StateObject._bufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
}
}
content = state._stringBuilder.ToString();
if (content.IndexOf(_endOfMessageToken) > -1)
{
if (_onReadCallback != null)
{
_onReadCallback(content);
}
}
else
{
handler.BeginReceive(state._buffer, 0, StateObject._bufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
}
}
private static void Send(Socket handler, String data)
{
try
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
catch(Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
}
}
private static void Send(Socket handler, String data)
{
try
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
catch(Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
Logging.Logging.LogInfo("Sent " + bytesSent.ToString() + " bytes to client.");
}
catch (Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
int bytesSent = handler.EndSend(ar);
Logging.Logging.LogInfo("Sent " + bytesSent.ToString() + " bytes to client.");
}
catch (Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
if (_onErrorCallback != null)
{
_onErrorCallback(e.ToString());
}
}
}
}
if (_onErrorCallback != null)
{
_onErrorCallback(e.ToString());
}
}
}
}
public class AsynchronousClient
{
public static uint _port = 6667;
public class AsynchronousClient
{
public static uint _port = 6667;
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static String response = String.Empty;
private static String response = String.Empty;
public static AsynchronousSocketListener.OnReadCallback _onErrorCallback = null;
public static AsynchronousSocketListener.OnReadCallback _onErrorCallback = null;
public static void Send(string message)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, (int)_port);
public static void Send(string message)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, (int)_port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IAsyncResult ar = client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
if (!connectDone.WaitOne(2000))
{
client.EndConnect(ar);
client.Shutdown(SocketShutdown.Both);
client.Close();
try
{
IAsyncResult ar = client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
if (!connectDone.WaitOne(2000))
{
client.EndConnect(ar);
client.Shutdown(SocketShutdown.Both);
client.Close();
Logging.Logging.LogWarning("Connection timed out, message was not sent");
Logging.Logging.LogWarning("Connection timed out, message was not sent");
return;
}
return;
}
Send(client, message);
sendDone.WaitOne();
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
finally
{
if(client.Connected)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
}
Send(client, message);
sendDone.WaitOne();
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
finally
{
if(client.Connected)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
if (client.Connected == false)
{
return;
}
if (client.Connected == false)
{
return;
}
client.EndConnect(ar);
client.EndConnect(ar);
connectDone.Set();
}
catch (Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
connectDone.Set();
}
catch (Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
if (_onErrorCallback != null)
{
_onErrorCallback(e.ToString());
}
}
}
if (_onErrorCallback != null)
{
_onErrorCallback(e.ToString());
}
}
}
private static void Send(Socket client, String data)
{
try
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
private static void Send(Socket client, String data)
{
try
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
int bytesSent = client.EndSend(ar);
sendDone.Set();
}
catch (Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
sendDone.Set();
}
catch (Exception e)
{
Logging.Logging.LogError("Excpetion: " + e.Message);
if (_onErrorCallback != null)
{
if (e is ObjectDisposedException)
{
// get this exception every once in a while
// doesn't seem to do much, no idea yet why it's there to begin with
}
else
{
if (_onErrorCallback != null)
{
if (e is ObjectDisposedException)
{
// get this exception every once in a while
// doesn't seem to do much, no idea yet why it's there to begin with
}
else
{
_onErrorCallback(e.ToString());
}
}
}
}
}
_onErrorCallback(e.ToString());
}
}
}
}
}
}
@@ -5,162 +5,352 @@ using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using VCProjectEngineWrapper;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
public class ProjectUtility
{
public static bool ContainsCFiles(Project project)
{
List<ProjectItem> projectItems = GetProjectItems(project);
public class ProjectUtility
{
public static List<string> GetPropertyNamesAndValues(Properties properties)
{
List<string> ret = new List<string>();
foreach (Property propertiy in properties)
{
string name = propertiy.Name;
string value = "";
try
{
foreach (EnvDTE.ProjectItem item in projectItems)
{
if (item.FileCodeModel != null && item.FileCodeModel.Language == CodeModelLanguageConstants.vsCMLanguageVC)
{
string extension = item.Properties.Item("Extension").Value.ToString();
if (extension == ".c")
{
return true;
}
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
try
{
value = propertiy.Value.ToString();
}
catch (Exception e)
{
value = "Error occurred while converting value to string.";
}
return false;
}
ret.Add(name + ": " + value);
}
static public List<ProjectItem> GetProjectItems(Project project)
{
List<ProjectItem> items = new List<ProjectItem>();
return ret;
}
IEnumerator itemEnumerator = project.ProjectItems.GetEnumerator();
public static bool HasProperty(Properties properties, string propertyName)
{
if (properties != null)
{
foreach (Property item in properties)
{
if (item != null && item.Name == propertyName)
{
return true;
}
}
}
return false;
}
while (itemEnumerator.MoveNext())
{
ProjectItem currentItem = (ProjectItem)itemEnumerator.Current;
items.Add(GetProjectSubItemsRecursive(currentItem, ref items));
}
public static bool ContainsCFiles(Project project)
{
List<ProjectItem> projectItems = GetProjectItems(project);
return items;
}
try
{
foreach (EnvDTE.ProjectItem item in projectItems)
{
if (item.FileCodeModel != null && item.FileCodeModel.Language == CodeModelLanguageConstants.vsCMLanguageVC)
{
string extension = item.Properties.Item("Extension").Value.ToString();
if (extension == ".c")
{
return true;
}
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
static private ProjectItem GetProjectSubItemsRecursive(ProjectItem item, ref List<ProjectItem> projectItems)
{
if (item.ProjectItems == null)
{
return item;
}
return false;
}
IEnumerator items = item.ProjectItems.GetEnumerator();
static public List<ProjectItem> GetProjectItems(Project project)
{
List<ProjectItem> items = new List<ProjectItem>();
while (items.MoveNext())
{
ProjectItem currentItem = (ProjectItem)items.Current;
projectItems.Add(GetProjectSubItemsRecursive(currentItem, ref projectItems));
}
IEnumerator itemEnumerator = project.ProjectItems.GetEnumerator();
return item;
}
while (itemEnumerator.MoveNext())
{
ProjectItem currentItem = (ProjectItem)itemEnumerator.Current;
items.Add(GetProjectSubItemsRecursive(currentItem, ref items));
}
// returns true if the project was reloaded, false if the project did not need to be reloaded
static public Guid ReloadProject(Project project)
{
Logging.Logging.LogInfo("Attempting to reload project");
return items;
}
try
{
if (project != null && project.Kind == EnvDTE.Constants.vsProjectKindUnmodeled)
{
DTE dte = project.DTE;
static private ProjectItem GetProjectSubItemsRecursive(ProjectItem item, ref List<ProjectItem> projectItems)
{
if (item.ProjectItems == null)
{
return item;
}
ServiceProvider sp = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
IVsSolution vsSolution = sp.GetService(typeof(SVsSolution)) as IVsSolution;
IEnumerator items = item.ProjectItems.GetEnumerator();
IVsHierarchy hierarchy;
while (items.MoveNext())
{
ProjectItem currentItem = (ProjectItem)items.Current;
projectItems.Add(GetProjectSubItemsRecursive(currentItem, ref projectItems));
}
string solutionDirectory = "";
string solutionFile = "";
string userOptions = "";
vsSolution.GetSolutionInfo(out solutionDirectory, out solutionFile, out userOptions);
return item;
}
vsSolution.GetProjectOfUniqueName(solutionDirectory + project.UniqueName, out hierarchy);
static public List<string> GetProjectIncludeDirectories(IVCProjectWrapper project, string configurationName, string platformName, IPathResolver pathResolver)
{
// get additional include directories
// source: http://www.mztools.com/articles/2014/MZ2014005.aspx
if (hierarchy != null)
{
Guid projectGuid;
Logging.Logging.LogInfo("Attempting to retreive Include Directories for project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.GetName()) + "'");
hierarchy.GetGuidProperty(
VSConstants.VSITEMID_ROOT,
(int)__VSHPROPID.VSHPROPID_ProjectIDGuid,
out projectGuid);
List<string> includeDirectories = new List<string>();
if (projectGuid != null)
{
Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' with GUID {" + projectGuid.ToString() + "} loaded.");
(vsSolution as IVsSolution4).ReloadProject(projectGuid);
return projectGuid;
}
else
{
Logging.Logging.LogError("Failed to load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
}
}
else
{
Logging.Logging.LogError("Failed to retreive IVsHierarchy. Can't load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
}
}
else
{
if (project == null)
{
Logging.Logging.LogWarning("Project is null");
}
else
{
Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' is already loaded");
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
IVCConfigurationWrapper vcProjectConfig = project.getConfiguration(configurationName, platformName);
return Guid.Empty;
}
if (vcProjectConfig != null && vcProjectConfig.isValid())
{
IVCCLCompilerToolWrapper compilerTool = vcProjectConfig.GetCompilerTool();
return Guid.Empty;
}
if (compilerTool != null && compilerTool.isValid())
{
foreach (string directory in compilerTool.GetAdditionalIncludeDirectories())
{
if (directory.Length <= 0)
{
continue;
}
static public void UnloadProject(Guid guid, DTE dte)
{
Logging.Logging.LogInfo("Attempting to unload project with GUID {" + guid.ToString() + "}");
string resolvedDirectories = pathResolver.ResolveVsMacroInPath(directory, vcProjectConfig);
if (dte == null)
{
return;
}
foreach (string resolvedDirectory in resolvedDirectories.Split(';'))
{
string dir = pathResolver.GetAsAbsoluteCanonicalPath(resolvedDirectory, project);
includeDirectories.Add(dir);
}
}
}
try
{
ServiceProvider sp = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
IVsSolution vsSolution = sp.GetService(typeof(SVsSolution)) as IVsSolution;
try
{
IVCPlatformWrapper platform = vcProjectConfig.GetPlatform();
if (platform != null && platform.isValid())
{
foreach (string directory in platform.GetIncludeDirectories())
{
string resolvedDirectories = pathResolver.ResolveVsMacroInPath(directory, vcProjectConfig);
foreach (string resolvedDirectory in resolvedDirectories.Split(';'))
{
includeDirectories.Add(resolvedDirectory);
}
}
}
}
catch (Exception e)
{
Logging.Logging.LogError("Failed to retreive platform include directories: " + e.Message);
return new List<string>();
}
}
else
{
Logging.Logging.LogWarning("Could not retreive Project Configuration. No include directories could be retreived.");
return new List<string>();
}
(vsSolution as IVsSolution4).UnloadProject(guid, (uint)_VSProjectUnloadStatus.UNLOADSTATUS_UnloadedByUser);
includeDirectories = includeDirectories.Distinct().ToList();
Logging.Logging.LogInfo("Done unloading project with GUID {" + guid.ToString() + "}");
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
}
Logging.Logging.LogInfo("Attempting to clean up.");
for (int i = 0; i < includeDirectories.Count; i++)
{
string path = includeDirectories.ElementAt(i).Replace("\\", "/"); // backslashes would cause some string-escaping hassles...
if (path.Length == 0)
{
includeDirectories.RemoveAt(i);
i--;
}
else
{
includeDirectories[i] = path;
}
}
Logging.Logging.LogInfo("Found " + includeDirectories.Count.ToString() + " distinct include directories.");
return includeDirectories;
}
static public List<string> GetProjectPreprocessorDefinitions(IVCProjectWrapper project, string configurationName, string platformName)
{
Logging.Logging.LogInfo("Attempting to retreive Preprocessor Definitions for project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.GetName()) + "'");
List<string> preprocessorDefinitions = new List<string>();
IVCCLCompilerToolWrapper compilerTool = null;
IVCConfigurationWrapper vcProjectConfig = project.getConfiguration(configurationName, platformName);
if (vcProjectConfig != null && vcProjectConfig.isValid())
{
compilerTool = vcProjectConfig.GetCompilerTool();
}
if (compilerTool != null && compilerTool.isValid())
{
foreach (string preprocessorDefinition in compilerTool.GetPreprocessorDefinitions())
{
preprocessorDefinitions.Add(preprocessorDefinition.Replace("\\\"", "\""));
}
}
else
{
Logging.Logging.LogWarning("Could not retreive compiler tool. No preprocessor definitions could be retreived.");
return new List<string>();
}
preprocessorDefinitions = preprocessorDefinitions.Distinct().ToList();
Logging.Logging.LogInfo("Found " + preprocessorDefinitions.Count.ToString() + " distinct preprocessor definitions.");
return preprocessorDefinitions;
}
// AFAIK there is no way to programmatically get the c++ standard version supported by any given VS version
// instead I'm refearing to the VS docu for that information
// https://msdn.microsoft.com/en-us/library/hh567368.aspx
static public string GetCppStandardForProject(IVCProjectWrapper project, string configurationName, string platformName)
{
string result = "";
string toolset = project.GetWrappedVersion();
string justNumbers = new String(toolset.Where(Char.IsDigit).ToArray());
int versionNumber = int.Parse(justNumbers);
if (versionNumber < 120) // version 11 (2012)
{
result = "-std=c++11";
}
else if (versionNumber < 130) // version 12 (2013)
{
result = "-std=c++14";
}
else if (versionNumber < 150) // version 14 (2015)
{
result = "-std=c++14";
}
else if (versionNumber < 160) // version 15 (2017)
{
result = "-std=c++14";
}
return result;
}
// returns a valid Guid if the project was reloaded or an empty Guid if the project did not need to be reloaded
static public Guid ReloadProject(Project project)
{
Logging.Logging.LogInfo("Attempting to reload project");
try
{
if (project != null && project.Kind == EnvDTE.Constants.vsProjectKindUnmodeled)
{
DTE dte = project.DTE;
ServiceProvider sp = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
IVsSolution vsSolution = sp.GetService(typeof(IVsSolution)) as IVsSolution;
IVsHierarchy hierarchy;
string solutionDirectory = "";
string solutionFile = "";
string userOptions = "";
vsSolution.GetSolutionInfo(out solutionDirectory, out solutionFile, out userOptions);
vsSolution.GetProjectOfUniqueName(solutionDirectory + project.UniqueName, out hierarchy);
if (hierarchy != null)
{
Guid projectGuid;
hierarchy.GetGuidProperty(
VSConstants.VSITEMID_ROOT,
(int)__VSHPROPID.VSHPROPID_ProjectIDGuid,
out projectGuid);
if (projectGuid != null)
{
Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' with GUID {" + projectGuid.ToString() + "} loaded.");
(vsSolution as IVsSolution4).ReloadProject(projectGuid);
return projectGuid;
}
else
{
Logging.Logging.LogError("Failed to load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
}
}
else
{
Logging.Logging.LogError("Failed to retreive IVsHierarchy. Can't load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
}
}
else
{
if (project == null)
{
Logging.Logging.LogWarning("Project is null");
}
else
{
Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' is already loaded");
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return Guid.Empty;
}
return Guid.Empty;
}
static public void UnloadProject(Guid guid, DTE dte)
{
Logging.Logging.LogInfo("Attempting to unload project with GUID {" + guid.ToString() + "}");
if (dte == null)
{
return;
}
try
{
ServiceProvider sp = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
IVsSolution vsSolution = sp.GetService(typeof(SVsSolution)) as IVsSolution;
(vsSolution as IVsSolution4).UnloadProject(guid, (uint)_VSProjectUnloadStatus.UNLOADSTATUS_UnloadedByUser);
Logging.Logging.LogInfo("Done unloading project with GUID {" + guid.ToString() + "}");
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
}
}
@@ -5,154 +5,160 @@ using System.Threading;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
class QueuedFileWriter
{
private bool _working = false;
Thread _workerThread = null;
class QueuedFileWriter
{
private bool _working = false;
private Thread _workerThread = null;
private static ReaderWriterLockSlim _statusLock = new ReaderWriterLockSlim();
private static ReaderWriterLockSlim _queueLock = new ReaderWriterLockSlim();
private static ReaderWriterLockSlim _fileLock = new ReaderWriterLockSlim();
private static ReaderWriterLockSlim _statusLock = new ReaderWriterLockSlim();
private static ReaderWriterLockSlim _queueLock = new ReaderWriterLockSlim();
private static ReaderWriterLockSlim _fileLock = new ReaderWriterLockSlim();
private Queue<string> _inputQueue = new Queue<string>();
private Queue<string> _outputQueue = new Queue<string>();
private Queue<string> _inputQueue = new Queue<string>();
private Queue<string> _outputQueue = new Queue<string>();
private string _targetDirectory = "";
private string _fileName = "";
private string _targetDirectory = "";
private string _fileName = "";
private int _messagesReceived = 0;
private int _messageWrittenCount = 0;
private int _messagesReceived = 0;
private int _messageWrittenCount = 0;
public string TargetDirectory
{
get { return _targetDirectory; }
set { _targetDirectory = value; }
}
public string TargetDirectory
{
get { return _targetDirectory; }
set { _targetDirectory = value; }
}
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
public void pushMessage(string message)
{
_queueLock.EnterWriteLock();
_messagesReceived++;
try
{
_inputQueue.Enqueue(message);
}
catch(Exception e)
{
Logging.Logging.LogError(e.Message);
}
finally
{
_queueLock.ExitWriteLock();
}
}
public QueuedFileWriter(string fileName, string targetDirectory)
{
_fileName = fileName;
_targetDirectory = targetDirectory;
}
public void startWorking()
{
_statusLock.EnterReadLock();
if (_working == true)
{
return;
}
_statusLock.ExitReadLock();
public void PushMessage(string message)
{
_queueLock.EnterWriteLock();
_messagesReceived++;
try
{
_inputQueue.Enqueue(message);
}
catch(Exception e)
{
Logging.Logging.LogError(e.Message);
}
finally
{
_queueLock.ExitWriteLock();
}
}
public void StartWorking()
{
_statusLock.EnterReadLock();
if (_working == true)
{
return;
}
_statusLock.ExitReadLock();
_statusLock.EnterWriteLock();
_working = true;
_workerThread = new Thread(new ThreadStart(work));
_workerThread.Start();
_statusLock.ExitWriteLock();
}
_statusLock.EnterWriteLock();
_working = true;
_workerThread = new Thread(new ThreadStart(Work));
_workerThread.Start();
_statusLock.ExitWriteLock();
}
public void stopWorking()
{
_statusLock.EnterWriteLock();
_working = false;
_statusLock.ExitWriteLock();
public void StopWorking()
{
_statusLock.EnterWriteLock();
_working = false;
_statusLock.ExitWriteLock();
if(_workerThread != null)
{
_workerThread.Join();
}
if(_workerThread != null)
{
_workerThread.Join();
}
// write remaining messages if stop was called
_queueLock.EnterWriteLock();
try
{
writeQueueToFile(ref _inputQueue);
writeQueueToFile(ref _outputQueue);
// write remaining messages if stop was called
_queueLock.EnterWriteLock();
try
{
WriteQueueToFile(ref _inputQueue);
WriteQueueToFile(ref _outputQueue);
Logging.Logging.LogInfo("final commit done");
}
catch(Exception e)
{
Logging.Logging.LogError(e.Message);
}
finally
{
_queueLock.ExitWriteLock();
}
Logging.Logging.LogInfo("final commit done");
}
catch(Exception e)
{
Logging.Logging.LogError(e.Message);
}
finally
{
_queueLock.ExitWriteLock();
}
Logging.Logging.LogInfo("Messages received: " + _messagesReceived);
Logging.Logging.LogInfo("Messages written: " + _messageWrittenCount);
}
Logging.Logging.LogInfo("Messages received: " + _messagesReceived);
Logging.Logging.LogInfo("Messages written: " + _messageWrittenCount);
}
private void work()
{
bool working = true;
private void Work()
{
bool working = true;
while(working)
{
commit();
while(working)
{
Commit();
_statusLock.EnterReadLock();
working = _working;
_statusLock.ExitReadLock();
}
}
_statusLock.EnterReadLock();
working = _working;
_statusLock.ExitReadLock();
}
}
private void commit()
{
_queueLock.EnterWriteLock();
private void Commit()
{
_queueLock.EnterWriteLock();
Queue<string> tmpQueue = _inputQueue;
_inputQueue = _outputQueue;
_outputQueue = tmpQueue;
Queue<string> tmpQueue = _inputQueue;
_inputQueue = _outputQueue;
_outputQueue = tmpQueue;
_queueLock.ExitWriteLock();
_queueLock.ExitWriteLock();
writeQueueToFile(ref _outputQueue);
}
WriteQueueToFile(ref _outputQueue);
}
private void writeQueueToFile(ref Queue<string> messageQueue)
{
_fileLock.EnterWriteLock();
try
{
while(messageQueue.Count > 0)
{
_messageWrittenCount++;
private void WriteQueueToFile(ref Queue<string> messageQueue)
{
_fileLock.EnterWriteLock();
try
{
while(messageQueue.Count > 0)
{
_messageWrittenCount++;
string message = messageQueue.Dequeue();
string message = messageQueue.Dequeue();
File.AppendAllText(_targetDirectory + "\\" + _fileName, message);
}
}
catch (Exception e)
{
Logging.Logging.LogError(e.Message);
}
finally
{
_fileLock.ExitWriteLock();
}
}
}
File.AppendAllText(_targetDirectory + "\\" + _fileName, message);
}
}
catch (Exception e)
{
Logging.Logging.LogError(e.Message);
}
finally
{
_fileLock.ExitWriteLock();
}
}
}
}
@@ -11,412 +11,442 @@ using Microsoft.VisualStudio;
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
public class SolutionUtility
{
[DllImport("ole32.dll")]
private static extern void CreateBindCtx(int reserved, out IBindCtx bindCtx);
[DllImport("ole32.dll")]
private static extern void GetRunningObjectTable(int reserved, out IRunningObjectTable runningObjectTable);
public class SolutionStructure
{
public class Node
{
public enum NodeType
{
UNKNOWN = 0,
PROJECT,
FOLDER
};
public string Name = "";
public Project Project = null;
public Object UserData = null;
public virtual NodeType GetNodeType() { throw (new NotImplementedException()); }
}
public class FolderNode : Node
{
public List<Node> SubNodes = new List<Node>();
public override NodeType GetNodeType() { return NodeType.FOLDER; }
}
public class ProjectNode : Node
{
public bool Include = false;
public override NodeType GetNodeType() { return NodeType.PROJECT; }
}
public List<Node> Nodes = new List<Node>();
}
public static String GetSolutionPath(DTE dte)
{
try
{
EnvDTE.Solution solution = dte.Solution;
return solution.FullName;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return "N/A";
}
}
public static SolutionStructure GetSolutionVCProjects(DTE dte)
{
return GetProjectStructureRecursive(dte); ;
}
public static SolutionStructure GetProjectStructureRecursive(DTE dte)
{
EnvDTE.Solution solution = dte.Solution;
EnvDTE.Projects solutionProjects = solution.Projects;
List<Guid> guids = new List<Guid>();
SolutionStructure projectStructure = new SolutionStructure();
foreach(Project project in solutionProjects)
{
try
{
if (project.Kind == EnvDTE.Constants.vsProjectKindUnmodeled) // not loaded
{
continue;
}
// check it's a c/c++ project
if (project.CodeModel != null)
{
if (project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageVC)
{
continue;
}
}
if (project.Kind == "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")
{
SolutionStructure.ProjectNode projectNode = new SolutionStructure.ProjectNode();
projectNode.Name = project.Name;
projectNode.Project = project;
projectNode.Include = false;
projectStructure.Nodes.Add(projectNode);
}
else
{
SolutionStructure.Node folderNode = GetSubProjects(project);
if (folderNode != null)
{
projectStructure.Nodes.Add(folderNode);
}
else
{
Logging.Logging.LogWarning("Subnode was NULL");
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
return projectStructure;
}
private static SolutionStructure.Node GetSubProjects(EnvDTE.Project project)
{
ProjectItems projectItems = project.ProjectItems;
List<Project> items = new List<Project>();
try
{
foreach (ProjectItem item in projectItems)
{
Project p = item.Object as Project;
if (p != null)
{
items.Add(p);
}
}
if (items.Count > 0)
{
SolutionStructure.FolderNode folderNode = new SolutionStructure.FolderNode();
folderNode.Name = project.Name;
for (int i = 0; i < items.Count; i++)
{
Project item = items[i];
SolutionStructure.Node subFolderNode = GetSubProjects(item);
if(subFolderNode != null)
{
folderNode.SubNodes.Add(subFolderNode);
}
else
{
Logging.Logging.LogWarning("SubNode was NULL");
}
}
return folderNode;
}
else
{
SolutionStructure.ProjectNode projectNode = new SolutionStructure.ProjectNode();
projectNode.Name = project.Name;
projectNode.Project = project;
projectNode.Include = false;
return projectNode;
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return null;
}
}
// Deprecated: remove when old project parsing is retired
public static List<String> GetSolutionProjectsFullNames(DTE dte)
{
List<String> projectNames = new List<String>();
EnvDTE.Solution solution = dte.Solution;
EnvDTE.Projects projects = solution.Projects;
List<Guid> guids = new List<Guid>();
foreach (EnvDTE.Project project in projects)
{
guids.Add(ProjectUtility.ReloadProject(project));
}
projects = solution.Projects;
foreach (EnvDTE.Project project in projects)
{
projectNames.Add(project.FullName);
}
foreach (Guid guid in guids)
{
ProjectUtility.UnloadProject(guid, dte);
}
return projectNames;
}
public static List<String> GetSolutionLanguages(DTE dte)
{
List<String> languages = new List<String>();
List<Project> projects = GetSolutionProjectList(dte);
foreach (EnvDTE.Project project in projects)
{
if (project.CodeModel != null)
{
string language = project.CodeModel.Language;
languages.Add(language);
}
}
languages = languages.Distinct().ToList();
return languages;
}
public static bool GetSolutionIsSaved(DTE dte)
{
try
{
EnvDTE.Solution solution = dte.Solution;
return solution.Saved;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
throw e;
}
}
public static List<List<string>> GetConfigurationAndPlatformNames(DTE dte)
{
List<List<string>> result = new List<List<string>>();
List<string> configNames = new List<string>();
List<string> platformNames = new List<string>();
DTE2 dte2 = SolutionUtility.GetDTE2(dte);
if(dte2 == null)
{
return result;
}
EnvDTE80.Solution2 solution = (EnvDTE80.Solution2)dte2.Solution;
if(solution == null)
{
return result;
}
EnvDTE80.SolutionBuild2 solutionBuild = (EnvDTE80.SolutionBuild2)solution.SolutionBuild;
if(solutionBuild == null)
{
return result;
}
try
{
foreach (SolutionConfiguration2 solutionConfiguration in solutionBuild.SolutionConfigurations)
{
foreach (SolutionContext context in solutionConfiguration.SolutionContexts)
{
string configurationName = context.ConfigurationName;
configNames.Add(configurationName);
string platformName = context.PlatformName;
platformNames.Add(platformName);
}
}
configNames = configNames.Distinct().ToList();
platformNames = platformNames.Distinct().ToList();
result.Add(configNames);
result.Add(platformNames);
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
return result;
}
public static DTE2 GetDTE2(DTE dte)
{
try
{
List<DTE2> dte2List = new List<DTE2>();
IRunningObjectTable runningObjectTable = null;
GetRunningObjectTable(0, out runningObjectTable);
IEnumMoniker enumMoniker = null;
runningObjectTable.EnumRunning(out enumMoniker);
enumMoniker.Reset();
IntPtr fetched = IntPtr.Zero;
IMoniker[] moniker = new IMoniker[1];
while (enumMoniker.Next(1, moniker, fetched) == 0)
{
IBindCtx bindCtx = null;
CreateBindCtx(0, out bindCtx);
string displayName = "";
moniker[0].GetDisplayName(bindCtx, null, out displayName);
// add all VisualStudio ROT entries to list
if (displayName.StartsWith("!VisualStudio"))
{
object comObject;
runningObjectTable.GetObject(moniker[0], out comObject);
dte2List.Add((DTE2)comObject);
}
}
// find the correct dte2 instance (each running VS instance has one...)
KeyValuePair<DTE2, int> maxMatch = new KeyValuePair<DTE2, int>(null, 0);
foreach (DTE2 dte2 in dte2List)
{
int m = StringUtility.GetMatchingCharsFromStart(dte.Solution.FullName, dte2.Solution.FullName);
if (m > maxMatch.Value)
{
maxMatch = new KeyValuePair<DTE2, int>(dte2, m);
}
}
return maxMatch.Key;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return null;
}
}
static public bool ContainsCFiles(DTE dte)
{
List<Project> projects = GetSolutionProjectList(dte); // dte.Solution.Projects;
foreach (Project project in projects)
{
if(ProjectUtility.ContainsCFiles(project) == true)
{
return true;
}
}
return false;
}
static public List<EnvDTE.Project> GetSolutionProjectList(DTE dte)
{
List<EnvDTE.Project> solutionProjects = new List<EnvDTE.Project>();
try
{
SolutionStructure solutionStructure = GetProjectStructureRecursive(dte);
Stack<SolutionStructure.Node> nodeStack = new Stack<Utility.SolutionUtility.SolutionStructure.Node>();
foreach (SolutionStructure.Node node in solutionStructure.Nodes)
{
nodeStack.Push(node);
}
while (nodeStack.Count > 0)
{
Utility.SolutionUtility.SolutionStructure.Node node = nodeStack.Pop();
string name = node.Name;
if (node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT)
{
solutionProjects.Add(node.Project);
}
else if (node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
Utility.SolutionUtility.SolutionStructure.FolderNode folderNode = node as Utility.SolutionUtility.SolutionStructure.FolderNode;
foreach (Utility.SolutionUtility.SolutionStructure.Node subNode in folderNode.SubNodes)
{
nodeStack.Push(subNode);
}
}
}
return solutionProjects;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return new List<EnvDTE.Project>();
}
}
}
public class SolutionUtility
{
[DllImport("ole32.dll")]
private static extern void CreateBindCtx(int reserved, out IBindCtx bindCtx);
[DllImport("ole32.dll")]
private static extern void GetRunningObjectTable(int reserved, out IRunningObjectTable runningObjectTable);
public class SolutionStructure
{
public class Node
{
public enum NodeType
{
UNKNOWN = 0,
PROJECT,
FOLDER
};
public string Name = "";
public Project Project = null;
public Object UserData = null;
public virtual NodeType GetNodeType()
{
throw (new NotImplementedException());
}
}
public class FolderNode : Node
{
public List<Node> SubNodes = new List<Node>();
public override NodeType GetNodeType()
{
return NodeType.FOLDER;
}
}
public class ProjectNode : Node
{
public bool Include = false;
public override NodeType GetNodeType()
{
return NodeType.PROJECT;
}
}
public List<Node> Nodes = new List<Node>();
}
public static String GetSolutionPath(DTE dte)
{
try
{
EnvDTE.Solution solution = dte.Solution;
return solution.FullName;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return "N/A";
}
}
public static SolutionStructure GetSolutionVCProjects(DTE dte)
{
return GetProjectStructureRecursive(dte); ;
}
public static SolutionStructure GetProjectStructureRecursive(DTE dte)
{
EnvDTE.Solution solution = dte.Solution;
EnvDTE.Projects solutionProjects = solution.Projects;
List<Guid> guids = new List<Guid>();
SolutionStructure projectStructure = new SolutionStructure();
foreach(Project project in solutionProjects)
{
try
{
if (project.Kind == EnvDTE.Constants.vsProjectKindUnmodeled) // not loaded
{
continue;
}
// check it's a c/c++ project
if (project.CodeModel != null)
{
if (project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageVC)
{
continue;
}
}
if (project.Kind == "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")
{
SolutionStructure.ProjectNode projectNode = new SolutionStructure.ProjectNode();
projectNode.Name = project.Name;
projectNode.Project = project;
projectNode.Include = false;
projectStructure.Nodes.Add(projectNode);
}
else
{
SolutionStructure.Node folderNode = GetSubProjects(project);
if (folderNode != null)
{
projectStructure.Nodes.Add(folderNode);
}
else
{
Logging.Logging.LogWarning("Subnode was NULL");
}
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
return projectStructure;
}
private static SolutionStructure.Node GetSubProjects(EnvDTE.Project project)
{
ProjectItems projectItems = project.ProjectItems;
List<Project> items = new List<Project>();
try
{
foreach (ProjectItem item in projectItems)
{
Project p = item.Object as Project;
if (p != null)
{
items.Add(p);
}
}
if (items.Count > 0)
{
SolutionStructure.FolderNode folderNode = new SolutionStructure.FolderNode();
folderNode.Name = project.Name;
for (int i = 0; i < items.Count; i++)
{
Project item = items[i];
SolutionStructure.Node subFolderNode = GetSubProjects(item);
if(subFolderNode != null)
{
folderNode.SubNodes.Add(subFolderNode);
}
else
{
Logging.Logging.LogWarning("SubNode was NULL");
}
}
return folderNode;
}
else
{
SolutionStructure.ProjectNode projectNode = new SolutionStructure.ProjectNode();
projectNode.Name = project.Name;
projectNode.Project = project;
projectNode.Include = false;
return projectNode;
}
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return null;
}
}
// Deprecated: remove when old project parsing is retired
public static List<String> GetSolutionProjectsFullNames(DTE dte)
{
List<String> projectNames = new List<String>();
EnvDTE.Solution solution = dte.Solution;
EnvDTE.Projects projects = solution.Projects;
List<Guid> guids = new List<Guid>();
foreach (EnvDTE.Project project in projects)
{
guids.Add(ProjectUtility.ReloadProject(project));
}
projects = solution.Projects;
foreach (EnvDTE.Project project in projects)
{
projectNames.Add(project.FullName);
}
foreach (Guid guid in guids)
{
ProjectUtility.UnloadProject(guid, dte);
}
return projectNames;
}
public static List<String> GetSolutionLanguages(DTE dte)
{
List<String> languages = new List<String>();
List<Project> projects = GetSolutionProjectList(dte);
foreach (EnvDTE.Project project in projects)
{
if (project.CodeModel != null)
{
string language = project.CodeModel.Language;
languages.Add(language);
}
}
languages = languages.Distinct().ToList();
return languages;
}
public static bool GetSolutionIsSaved(DTE dte)
{
try
{
EnvDTE.Solution solution = dte.Solution;
return solution.Saved;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
throw e;
}
}
public static List<string> GetConfigurationNames(DTE dte)
{
List<string> configurationNames = new List<string>();
SolutionBuild2 solutionBuild = GetSolutionBuild2(dte);
if (solutionBuild != null)
{
try
{
foreach (SolutionConfiguration2 solutionConfiguration in solutionBuild.SolutionConfigurations)
{
foreach (SolutionContext context in solutionConfiguration.SolutionContexts)
{
configurationNames.Add(context.ConfigurationName);
}
}
configurationNames = configurationNames.Distinct().ToList();
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
return configurationNames;
}
public static List<string> GetPlatformNames(DTE dte)
{
List<string> platformNames = new List<string>();
SolutionBuild2 solutionBuild = GetSolutionBuild2(dte);
if (solutionBuild != null)
{
try
{
foreach (SolutionConfiguration2 solutionConfiguration in solutionBuild.SolutionConfigurations)
{
foreach (SolutionContext context in solutionConfiguration.SolutionContexts)
{
platformNames.Add(context.PlatformName);
}
}
platformNames = platformNames.Distinct().ToList();
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
return platformNames;
}
public static DTE2 GetDTE2(DTE dte)
{
try
{
List<DTE2> dte2List = new List<DTE2>();
IRunningObjectTable runningObjectTable = null;
GetRunningObjectTable(0, out runningObjectTable);
IEnumMoniker enumMoniker = null;
runningObjectTable.EnumRunning(out enumMoniker);
enumMoniker.Reset();
IntPtr fetched = IntPtr.Zero;
IMoniker[] moniker = new IMoniker[1];
while (enumMoniker.Next(1, moniker, fetched) == 0)
{
IBindCtx bindCtx = null;
CreateBindCtx(0, out bindCtx);
string displayName = "";
moniker[0].GetDisplayName(bindCtx, null, out displayName);
// add all VisualStudio ROT entries to list
if (displayName.StartsWith("!VisualStudio"))
{
object comObject;
runningObjectTable.GetObject(moniker[0], out comObject);
dte2List.Add((DTE2)comObject);
}
}
// find the correct dte2 instance (each running VS instance has one...)
KeyValuePair<DTE2, int> maxMatch = new KeyValuePair<DTE2, int>(null, 0);
foreach (DTE2 dte2 in dte2List)
{
int m = StringUtility.GetMatchingCharsFromStart(dte.Solution.FullName, dte2.Solution.FullName);
if (m > maxMatch.Value)
{
maxMatch = new KeyValuePair<DTE2, int>(dte2, m);
}
}
return maxMatch.Key;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return null;
}
}
static public SolutionBuild2 GetSolutionBuild2(DTE dte)
{
DTE2 dte2 = SolutionUtility.GetDTE2(dte);
if (dte2 == null)
{
return null;
}
EnvDTE80.Solution2 solution = (EnvDTE80.Solution2)dte2.Solution;
if (solution == null)
{
return null;
}
return (EnvDTE80.SolutionBuild2)solution.SolutionBuild;
}
static public bool ContainsCFiles(DTE dte)
{
List<Project> projects = GetSolutionProjectList(dte); // dte.Solution.Projects;
foreach (Project project in projects)
{
if(ProjectUtility.ContainsCFiles(project) == true)
{
return true;
}
}
return false;
}
static public List<EnvDTE.Project> GetSolutionProjectList(DTE dte)
{
List<EnvDTE.Project> solutionProjects = new List<EnvDTE.Project>();
try
{
SolutionStructure solutionStructure = GetProjectStructureRecursive(dte);
Stack<SolutionStructure.Node> nodeStack = new Stack<Utility.SolutionUtility.SolutionStructure.Node>();
foreach (SolutionStructure.Node node in solutionStructure.Nodes)
{
nodeStack.Push(node);
}
while (nodeStack.Count > 0)
{
Utility.SolutionUtility.SolutionStructure.Node node = nodeStack.Pop();
string name = node.Name;
if (node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT)
{
solutionProjects.Add(node.Project);
}
else if (node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
Utility.SolutionUtility.SolutionStructure.FolderNode folderNode = node as Utility.SolutionUtility.SolutionStructure.FolderNode;
foreach (Utility.SolutionUtility.SolutionStructure.Node subNode in folderNode.SubNodes)
{
nodeStack.Push(subNode);
}
}
}
return solutionProjects;
}
catch(Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
return new List<EnvDTE.Project>();
}
}
}
}
@@ -2,60 +2,60 @@
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
class StringUtility
{
static public Tuple<int, int> FindFirstRange(string text, string startTag, string endTag)
{
if(startTag.Length > 0 && endTag.Length > 0 && (startTag.Length + endTag.Length) < text.Length)
{
int start = text.IndexOf(startTag);
int end = text.IndexOf(endTag);
public class StringUtility
{
static public Tuple<int, int> FindFirstRange(string text, string startTag, string endTag)
{
if(startTag.Length > 0 && endTag.Length > 0 && (startTag.Length + endTag.Length) < text.Length)
{
int start = text.IndexOf(startTag);
int end = text.IndexOf(endTag);
// just check wheter both, start and end, are valid and the end tag occurs after the start tag
if(start > -1 && end > -1 && end > start)
{
return new Tuple<int, int>(start, end);
}
}
// just check wheter both, start and end, are valid and the end tag occurs after the start tag
if(start > -1 && end > -1 && end > start)
{
return new Tuple<int, int>(start, end);
}
}
return null;
}
return null;
}
static public int GetMatchingCharsFromStart(string a, string b)
{
int matchingChars = 0;
static public int GetMatchingCharsFromStart(string a, string b)
{
int matchingChars = 0;
if (a != string.Empty)
{
a = a.ToLower();
}
else
{
return matchingChars;
}
if (a != string.Empty)
{
a = a.ToLower();
}
else
{
return matchingChars;
}
if (b != string.Empty)
{
b = b.ToLower();
}
else
{
return matchingChars;
}
if (b != string.Empty)
{
b = b.ToLower();
}
else
{
return matchingChars;
}
for (int i = 0; i < Math.Min(a.Length, b.Length); i++)
{
if (!char.Equals(a[i], b[i]))
{
break;
}
else
{
matchingChars++;
}
}
for (int i = 0; i < Math.Min(a.Length, b.Length); i++)
{
if (!char.Equals(a[i], b[i]))
{
break;
}
else
{
matchingChars++;
}
}
return matchingChars;
}
}
return matchingChars;
}
}
}
@@ -2,35 +2,35 @@
namespace CoatiSoftware.SourcetrailPlugin.Utility
{
class SystemUtility
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr SetActiveWindow(IntPtr hWnd);
class SystemUtility
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr SetActiveWindow(IntPtr hWnd);
public static void GetWindowFocus()
{
try
{
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
IntPtr windowHandle = process.MainWindowHandle;
public static void GetWindowFocus()
{
try
{
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
IntPtr windowHandle = process.MainWindowHandle;
if (windowHandle != null)
{
SetForegroundWindow(windowHandle);
SetActiveWindow(windowHandle);
}
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
if (windowHandle != null)
{
SetForegroundWindow(windowHandle);
SetActiveWindow(windowHandle);
}
}
catch (Exception e)
{
Logging.Logging.LogError("Exception: " + e.Message);
}
}
public static void OpenWindowsExplorerAtDirectory(string directory)
{
System.Diagnostics.Process.Start(directory);
}
}
public static void OpenWindowsExplorerAtDirectory(string directory)
{
System.Diagnostics.Process.Start(directory);
}
}
}
@@ -1,14 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
VS SDK Notes: This resx file contains the resources that will be consumed from your package by Visual Studio.
For example, Visual Studio will attempt to load resource '400' from this resource stream when it needs to
load your package's icon. Because Visual Studio will always look in the VSPackage.resources stream first for
resources it needs, you should put additional resources that Visual Studio will load directly into this resx
file.
Resources that you would like to access directly from your package in a strong-typed fashion should be stored
in Resources.resx or another resx file.
-->
<root>
<!--
Microsoft ResX Schema
@@ -132,6 +122,6 @@
<value>SourcetrailPlugin</value>
</data>
<data name="112" xml:space="preserve">
<value>Sourcetrail plugin test</value>
<value>The Sourcetrail Plugin allows Visual Studio to communicate with Sourcetrail - an external source code exploration tool. It also enables Visual Studio to generate a Clang Compilation Database from any Visual Studio Solution which can be used to automate the Sourcetrail project setup and to run other Clang based tools.</value>
</data>
</root>
@@ -6,484 +6,484 @@ using System.Text.RegularExpressions;
namespace CoatiSoftware.SourcetrailPlugin.Wizard
{
public partial class ProjectSetupWindow : Form
{
public class SolutionProject
{
public string _name = "";
public bool _include = false;
public SolutionProject(string name, bool include)
{
_name = name;
_include = include;
}
}
public delegate void OnCreateProject(List<EnvDTE.Project> projects, string configurationName, string platformName, string targetDir, string fileName, string cStandard);
// public List<SolutionProject> m_projects = new List<SolutionProject>();
public Utility.SolutionUtility.SolutionStructure _projectStructure = new Utility.SolutionUtility.SolutionStructure();
public List<string> _configurations = new List<string>();
public List<string> _platforms = new List<string>();
public OnCreateProject _onCreateProject = null;
public string _solutionDirectory = "";
public string _solutionFileName = "foo";
public bool _containsCFiles = false;
private List<string> _cStandards = new List<string>() { "c1x", "gnu1x", "iso9899:201x", "c11", "gnu11", "iso9899:2011",
"c9x", "gnu9x", "iso9899:199x", "c99", "gnu99", "iso9899:1999", "iso9899:199409", "c90", "gnu90", "iso9899:1990",
"c89", "gnu89" };
public SolutionParser.CompilationDatabase _cdb = new SolutionParser.CompilationDatabase();
public ProjectSetupWindow()
{
InitializeComponent();
UpdateGUI();
buttonCreate.Enabled = false;
}
public void UpdateGUI()
{
Logging.Logging.LogInfo("Populating GUI");
InitProjectCheckList();
InitComboBoxConfigurations();
InitComboBoxPlatforms();
InitTextBoxTargetDirectory();
InitTextBoxFileName();
InitComboBoxCStandard();
}
private void InitComboBoxConfigurations()
{
Logging.Logging.LogInfo("Adding " + _configurations.Count.ToString() + " build configurations.");
foreach(string configuration in _configurations)
{
comboBoxConfiguration.Items.Add(configuration);
}
if(comboBoxConfiguration.Items.Count > 0)
{
if(_cdb != null)
{
int index = comboBoxConfiguration.Items.IndexOf(_cdb.ConfigurationName);
comboBoxConfiguration.SelectedIndex = index;
}
else
{
comboBoxConfiguration.SelectedIndex = 0;
}
}
}
private void InitComboBoxPlatforms()
{
Logging.Logging.LogInfo("Adding " + _platforms.Count.ToString() + " target platforms.");
foreach (string platform in _platforms)
{
comboBoxPlatform.Items.Add(platform);
}
if(comboBoxPlatform.Items.Count > 0)
{
if(_cdb != null)
{
int index = comboBoxPlatform.Items.IndexOf(_cdb.PlatformName);
comboBoxPlatform.SelectedIndex = index;
}
else
{
comboBoxPlatform.SelectedIndex = 0;
}
}
}
private void InitProjectCheckList()
{
// way to slow for large projects
//if(_cdb != null)
//{
// _cdb.TryLoadData();
//}
foreach(Utility.SolutionUtility.SolutionStructure.Node node in _projectStructure.Nodes)
{
if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT)
{
TreeNode treeNode = new TreeNode(node.Name);
node.UserData = treeNode;
if (_cdb != null && _cdb.IncludedProjects.Exists(item => item == treeNode.Text))
{
treeNode.Checked = true;
}
treeViewProjects.Nodes.Add(treeNode);
}
else if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
TreeNode[] subNodes = GetSubNodes(node as Utility.SolutionUtility.SolutionStructure.FolderNode);
TreeNode treeNode = new TreeNode(node.Name, subNodes);
node.UserData = treeNode;
treeViewProjects.Nodes.Add(treeNode);
}
}
UpdateCreateButtonEnabled();
}
private TreeNode[] GetSubNodes(Utility.SolutionUtility.SolutionStructure.FolderNode folderNode)
{
List<TreeNode> result = new List<TreeNode>();
foreach(Utility.SolutionUtility.SolutionStructure.Node node in folderNode.SubNodes)
{
if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT)
{
TreeNode treeNode = new TreeNode(node.Name);
node.UserData = treeNode;
result.Add(treeNode);
}
else if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
TreeNode[] subNodes = GetSubNodes(node as Utility.SolutionUtility.SolutionStructure.FolderNode);
TreeNode treeNode = new TreeNode(node.Name, subNodes);
node.UserData = treeNode;
result.Add(treeNode);
}
}
return result.ToArray();
}
private void InitTextBoxTargetDirectory()
{
Logging.Logging.LogInfo("Setting default target directory: \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(_solutionDirectory) + "\"");
folderBrowserTargetDirectory.SelectedPath = _solutionDirectory;
string rootDirectory = folderBrowserTargetDirectory.SelectedPath.ToString();
textBoxTargetDirectory.Text = rootDirectory;
}
private void InitTextBoxFileName()
{
Logging.Logging.LogInfo("Setting default file name: '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(_solutionFileName) + "'");
if(_cdb == null)
{
textBoxFileName.Text = _solutionFileName;
}
else
{
textBoxFileName.Text = _cdb.Name;
}
}
private void InitComboBoxCStandard()
{
if(_containsCFiles == false)
{
Logging.Logging.LogInfo("Hiding C Standard selection");
comboBoxCStandard.Hide();
labelCStandard.Hide();
}
else
{
Logging.Logging.LogInfo("Showing C Standard selection");
comboBoxCStandard.Show();
labelCStandard.Show();
foreach(string standard in _cStandards)
{
comboBoxCStandard.Items.Add(standard);
}
comboBoxCStandard.SelectedIndex = 3;
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
Logging.Logging.LogInfo("Close button pressed. Aborting.");
Close();
}
private void buttonCreate_Click(object sender, EventArgs e)
{
OnCreate();
}
private void OnCreate()
{
Logging.Logging.LogInfo("Create button pressed");
if (_onCreateProject != null)
{
string configurationName = "";
string platformName = "";
configurationName = comboBoxConfiguration.SelectedItem as string;
platformName = comboBoxPlatform.SelectedItem as string;
Logging.Logging.LogInfo("Configuration " + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(configurationName) + "|" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(platformName) + " was selected.");
string targetDir = textBoxTargetDirectory.Text;
if(Directory.Exists(targetDir) && CheckFileNameIsValid(textBoxFileName.Text))
{
if (CheckFileExists())
{
Logging.Logging.LogWarning("A file \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(targetDir + "\\" + textBoxFileName.Text) + "\" already exists.");
DialogResult result = MessageBox.Show("A file of the chosen name already exists. Do you want to replace it?", "Sourcetrail Plugin", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if(result == DialogResult.No)
{
Logging.Logging.LogInfo("Aborting CDB creation and attempting to make file name unique.");
MakeFileNameUnique();
return;
}
}
string cStandard = "c11";
if(_containsCFiles)
{
cStandard = comboBoxCStandard.SelectedItem as string;
}
Logging.Logging.LogInfo("Setting C standard flag to " + cStandard);
_onCreateProject(GetTreeViewProjectItems(), configurationName, platformName, targetDir, textBoxFileName.Text, cStandard);
Close();
}
else
{
if(Directory.Exists(targetDir) == false)
{
Logging.Logging.LogError("The target directory \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(targetDir) + "\" does not exist.");
MessageBox.Show("The target directory does not exist.", "Sourcetrail Plugin", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
if (CheckFileNameIsValid(textBoxFileName.Text) == false)
{
Logging.Logging.LogError("The chosen file name \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(textBoxFileName.Text) + "\" is not valid. I'd almost dare to say it's invalid!");
MessageBox.Show("The chosen file name is not valid.", "Sourcetrail Plugin", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
{
Logging.Logging.LogError("CDB create callback is not set. Cannot start creating CDB.");
}
}
private bool CheckFileNameIsValid(string fileName)
{
Regex badChars = new Regex("[" + Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars())) + "]");
if(badChars.IsMatch(fileName))
{
return false;
}
return true;
}
private bool CheckFileExists()
{
string fileName = textBoxFileName.Text;
string path = textBoxTargetDirectory.Text;
string extension = labelFileNameEnding.Text;
return File.Exists(path + "\\" + fileName + extension);
}
private List<EnvDTE.Project> GetTreeViewProjectItems()
{
List<EnvDTE.Project> solutionProjects = new List<EnvDTE.Project>();
// Stack<TreeNode> treeNodes = new Stack<TreeNode>();
Stack<Utility.SolutionUtility.SolutionStructure.Node> nodeStack = new Stack<Utility.SolutionUtility.SolutionStructure.Node>();
foreach(Utility.SolutionUtility.SolutionStructure.Node node in _projectStructure.Nodes)
{
nodeStack.Push(node);
}
while(nodeStack.Count > 0)
{
Utility.SolutionUtility.SolutionStructure.Node node = nodeStack.Pop();
bool include = (node.UserData as TreeNode).Checked;
string name = node.Name;
if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT
&& (node.UserData as TreeNode).Checked == true)
{
solutionProjects.Add(node.Project);
}
else if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
Utility.SolutionUtility.SolutionStructure.FolderNode folderNode = node as Utility.SolutionUtility.SolutionStructure.FolderNode;
foreach(Utility.SolutionUtility.SolutionStructure.Node subNode in folderNode.SubNodes)
{
nodeStack.Push(subNode);
}
}
}
return solutionProjects;
}
private void ProjectCheckList_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void buttonSelectAll_Click(object sender, EventArgs e)
{
bool select = false;
// if one or more items are unselected, select all
// otherwise deselect all
for (int i = 0; i < treeViewProjects.Nodes.Count; i++)
{
if (treeViewProjects.Nodes[i].Checked == false)
{
select = true;
}
}
for (int i = 0; i < treeViewProjects.Nodes.Count; i++)
{
treeViewProjects.Nodes[i].Checked = select;
}
UpdateCreateButtonEnabled();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void buttonSelect_Click(object sender, EventArgs e)
{
if(Directory.Exists(textBoxTargetDirectory.Text))
{
folderBrowserTargetDirectory.SelectedPath = textBoxTargetDirectory.Text;
}
folderBrowserTargetDirectory.SelectedPath = textBoxTargetDirectory.Text;
DialogResult result = folderBrowserTargetDirectory.ShowDialog();
string selectedPath = folderBrowserTargetDirectory.SelectedPath;
textBoxTargetDirectory.Text = selectedPath;
}
private void treeViewProjects_NodeCheckChanged(object sender, TreeViewEventArgs e)
{
// treeViewProjects.AfterCheck -= treeViewProjects_NodeCheckChanged;
Stack<TreeNode> nodeStack = new Stack<TreeNode>();
foreach (TreeNode subNode in e.Node.Nodes)
{
nodeStack.Push(subNode);
}
while (nodeStack.Count > 0)
{
var node = nodeStack.Pop();
node.Checked = e.Node.Checked;
//foreach (TreeNode subNode in node.Nodes)
//{
// nodeStack.Push(subNode);
//}
}
// treeViewProjects.AfterCheck += treeViewProjects_NodeCheckChanged;
}
private void textBoxFileName_TextChanged(object sender, EventArgs e)
{
}
private void textBoxFileName_Leave(object sender, EventArgs e)
{
// MakeFileNameUnique();
}
private void MakeFileNameUnique()
{
string fileName = textBoxFileName.Text;
int i = 0;
while (CheckFileExists())
{
++i;
textBoxFileName.Text = fileName + i.ToString();
}
}
private void ProjectCheckList_ItemCheck(object sender, ItemCheckEventArgs e)
{
}
private void ProjectCheckList_Click(object sender, EventArgs e)
{
}
private void ProjectCheckList_MouseUp(object sender, MouseEventArgs e)
{
UpdateCreateButtonEnabled();
}
private void UpdateCreateButtonEnabled()
{
bool anythingChecked = false;
Stack<TreeNode> treeNodes = new Stack<TreeNode>();
foreach(TreeNode node in treeViewProjects.Nodes)
{
treeNodes.Push(node);
}
while(treeNodes.Count > 0)
{
TreeNode node = treeNodes.Pop();
if(node.Nodes.Count <= 0 && node.Checked == true)
{
anythingChecked = true;
}
foreach(TreeNode subNode in node.Nodes)
{
treeNodes.Push(subNode);
}
}
buttonCreate.Enabled = anythingChecked;
}
}
public partial class ProjectSetupWindow : Form
{
public class SolutionProject
{
public string _name = "";
public bool _include = false;
public SolutionProject(string name, bool include)
{
_name = name;
_include = include;
}
}
public delegate void OnCreateProject(List<EnvDTE.Project> projects, string configurationName, string platformName, string targetDir, string fileName, string cStandard);
// public List<SolutionProject> m_projects = new List<SolutionProject>();
public Utility.SolutionUtility.SolutionStructure _projectStructure = new Utility.SolutionUtility.SolutionStructure();
public List<string> _configurations = new List<string>();
public List<string> _platforms = new List<string>();
public OnCreateProject _onCreateProject = null;
public string _solutionDirectory = "";
public string _solutionFileName = "foo";
public bool _containsCFiles = false;
private List<string> _cStandards = new List<string>() { "c1x", "gnu1x", "iso9899:201x", "c11", "gnu11", "iso9899:2011",
"c9x", "gnu9x", "iso9899:199x", "c99", "gnu99", "iso9899:1999", "iso9899:199409", "c90", "gnu90", "iso9899:1990",
"c89", "gnu89" };
public SolutionParser.CompilationDatabase _cdb = new SolutionParser.CompilationDatabase();
public ProjectSetupWindow()
{
InitializeComponent();
UpdateGUI();
buttonCreate.Enabled = false;
}
public void UpdateGUI()
{
Logging.Logging.LogInfo("Populating GUI");
InitProjectCheckList();
InitComboBoxConfigurations();
InitComboBoxPlatforms();
InitTextBoxTargetDirectory();
InitTextBoxFileName();
InitComboBoxCStandard();
}
private void InitComboBoxConfigurations()
{
Logging.Logging.LogInfo("Adding " + _configurations.Count.ToString() + " build configurations.");
foreach(string configuration in _configurations)
{
comboBoxConfiguration.Items.Add(configuration);
}
if(comboBoxConfiguration.Items.Count > 0)
{
if(_cdb != null)
{
int index = comboBoxConfiguration.Items.IndexOf(_cdb.ConfigurationName);
comboBoxConfiguration.SelectedIndex = index;
}
else
{
comboBoxConfiguration.SelectedIndex = 0;
}
}
}
private void InitComboBoxPlatforms()
{
Logging.Logging.LogInfo("Adding " + _platforms.Count.ToString() + " target platforms.");
foreach (string platform in _platforms)
{
comboBoxPlatform.Items.Add(platform);
}
if(comboBoxPlatform.Items.Count > 0)
{
if(_cdb != null)
{
int index = comboBoxPlatform.Items.IndexOf(_cdb.PlatformName);
comboBoxPlatform.SelectedIndex = index;
}
else
{
comboBoxPlatform.SelectedIndex = 0;
}
}
}
private void InitProjectCheckList()
{
// way to slow for large projects
//if(_cdb != null)
//{
// _cdb.TryLoadData();
//}
foreach(Utility.SolutionUtility.SolutionStructure.Node node in _projectStructure.Nodes)
{
if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT)
{
TreeNode treeNode = new TreeNode(node.Name);
node.UserData = treeNode;
if (_cdb != null && _cdb.IncludedProjects.Exists(item => item == treeNode.Text))
{
treeNode.Checked = true;
}
treeViewProjects.Nodes.Add(treeNode);
}
else if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
TreeNode[] subNodes = GetSubNodes(node as Utility.SolutionUtility.SolutionStructure.FolderNode);
TreeNode treeNode = new TreeNode(node.Name, subNodes);
node.UserData = treeNode;
treeViewProjects.Nodes.Add(treeNode);
}
}
UpdateCreateButtonEnabled();
}
private TreeNode[] GetSubNodes(Utility.SolutionUtility.SolutionStructure.FolderNode folderNode)
{
List<TreeNode> result = new List<TreeNode>();
foreach(Utility.SolutionUtility.SolutionStructure.Node node in folderNode.SubNodes)
{
if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT)
{
TreeNode treeNode = new TreeNode(node.Name);
node.UserData = treeNode;
result.Add(treeNode);
}
else if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
TreeNode[] subNodes = GetSubNodes(node as Utility.SolutionUtility.SolutionStructure.FolderNode);
TreeNode treeNode = new TreeNode(node.Name, subNodes);
node.UserData = treeNode;
result.Add(treeNode);
}
}
return result.ToArray();
}
private void InitTextBoxTargetDirectory()
{
Logging.Logging.LogInfo("Setting default target directory: \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(_solutionDirectory) + "\"");
folderBrowserTargetDirectory.SelectedPath = _solutionDirectory;
string rootDirectory = folderBrowserTargetDirectory.SelectedPath.ToString();
textBoxTargetDirectory.Text = rootDirectory;
}
private void InitTextBoxFileName()
{
Logging.Logging.LogInfo("Setting default file name: '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(_solutionFileName) + "'");
if(_cdb == null)
{
textBoxFileName.Text = _solutionFileName;
}
else
{
textBoxFileName.Text = _cdb.Name;
}
}
private void InitComboBoxCStandard()
{
if(_containsCFiles == false)
{
Logging.Logging.LogInfo("Hiding C Standard selection");
comboBoxCStandard.Hide();
labelCStandard.Hide();
}
else
{
Logging.Logging.LogInfo("Showing C Standard selection");
comboBoxCStandard.Show();
labelCStandard.Show();
foreach(string standard in _cStandards)
{
comboBoxCStandard.Items.Add(standard);
}
comboBoxCStandard.SelectedIndex = 3;
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
Logging.Logging.LogInfo("Close button pressed. Aborting.");
Close();
}
private void buttonCreate_Click(object sender, EventArgs e)
{
OnCreate();
}
private void OnCreate()
{
Logging.Logging.LogInfo("Create button pressed");
if (_onCreateProject != null)
{
string configurationName = "";
string platformName = "";
configurationName = comboBoxConfiguration.SelectedItem as string;
platformName = comboBoxPlatform.SelectedItem as string;
Logging.Logging.LogInfo("Configuration " + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(configurationName) + "|" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(platformName) + " was selected.");
string targetDir = textBoxTargetDirectory.Text;
if(Directory.Exists(targetDir) && CheckFileNameIsValid(textBoxFileName.Text))
{
if (CheckFileExists())
{
Logging.Logging.LogWarning("A file \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(targetDir + "\\" + textBoxFileName.Text) + "\" already exists.");
DialogResult result = MessageBox.Show("A file of the chosen name already exists. Do you want to replace it?", "Sourcetrail Plugin", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if(result == DialogResult.No)
{
Logging.Logging.LogInfo("Aborting CDB creation and attempting to make file name unique.");
MakeFileNameUnique();
return;
}
}
string cStandard = "c11";
if(_containsCFiles)
{
cStandard = comboBoxCStandard.SelectedItem as string;
}
Logging.Logging.LogInfo("Setting C standard flag to " + cStandard);
_onCreateProject(GetTreeViewProjectItems(), configurationName, platformName, targetDir, textBoxFileName.Text, cStandard);
Close();
}
else
{
if(Directory.Exists(targetDir) == false)
{
Logging.Logging.LogError("The target directory \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(targetDir) + "\" does not exist.");
MessageBox.Show("The target directory does not exist.", "Sourcetrail Plugin", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
if (CheckFileNameIsValid(textBoxFileName.Text) == false)
{
Logging.Logging.LogError("The chosen file name \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(textBoxFileName.Text) + "\" is not valid. I'd almost dare to say it's invalid!");
MessageBox.Show("The chosen file name is not valid.", "Sourcetrail Plugin", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else
{
Logging.Logging.LogError("CDB create callback is not set. Cannot start creating CDB.");
}
}
private bool CheckFileNameIsValid(string fileName)
{
Regex badChars = new Regex("[" + Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars())) + "]");
if(badChars.IsMatch(fileName))
{
return false;
}
return true;
}
private bool CheckFileExists()
{
string fileName = textBoxFileName.Text;
string path = textBoxTargetDirectory.Text;
string extension = labelFileNameEnding.Text;
return File.Exists(path + "\\" + fileName + extension);
}
private List<EnvDTE.Project> GetTreeViewProjectItems()
{
List<EnvDTE.Project> solutionProjects = new List<EnvDTE.Project>();
// Stack<TreeNode> treeNodes = new Stack<TreeNode>();
Stack<Utility.SolutionUtility.SolutionStructure.Node> nodeStack = new Stack<Utility.SolutionUtility.SolutionStructure.Node>();
foreach(Utility.SolutionUtility.SolutionStructure.Node node in _projectStructure.Nodes)
{
nodeStack.Push(node);
}
while(nodeStack.Count > 0)
{
Utility.SolutionUtility.SolutionStructure.Node node = nodeStack.Pop();
bool include = (node.UserData as TreeNode).Checked;
string name = node.Name;
if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.PROJECT
&& (node.UserData as TreeNode).Checked == true)
{
solutionProjects.Add(node.Project);
}
else if(node.GetNodeType() == Utility.SolutionUtility.SolutionStructure.Node.NodeType.FOLDER)
{
Utility.SolutionUtility.SolutionStructure.FolderNode folderNode = node as Utility.SolutionUtility.SolutionStructure.FolderNode;
foreach(Utility.SolutionUtility.SolutionStructure.Node subNode in folderNode.SubNodes)
{
nodeStack.Push(subNode);
}
}
}
return solutionProjects;
}
private void ProjectCheckList_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void buttonSelectAll_Click(object sender, EventArgs e)
{
bool select = false;
// if one or more items are unselected, select all
// otherwise deselect all
for (int i = 0; i < treeViewProjects.Nodes.Count; i++)
{
if (treeViewProjects.Nodes[i].Checked == false)
{
select = true;
}
}
for (int i = 0; i < treeViewProjects.Nodes.Count; i++)
{
treeViewProjects.Nodes[i].Checked = select;
}
UpdateCreateButtonEnabled();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void buttonSelect_Click(object sender, EventArgs e)
{
if(Directory.Exists(textBoxTargetDirectory.Text))
{
folderBrowserTargetDirectory.SelectedPath = textBoxTargetDirectory.Text;
}
folderBrowserTargetDirectory.SelectedPath = textBoxTargetDirectory.Text;
DialogResult result = folderBrowserTargetDirectory.ShowDialog();
string selectedPath = folderBrowserTargetDirectory.SelectedPath;
textBoxTargetDirectory.Text = selectedPath;
}
private void treeViewProjects_NodeCheckChanged(object sender, TreeViewEventArgs e)
{
// treeViewProjects.AfterCheck -= treeViewProjects_NodeCheckChanged;
Stack<TreeNode> nodeStack = new Stack<TreeNode>();
foreach (TreeNode subNode in e.Node.Nodes)
{
nodeStack.Push(subNode);
}
while (nodeStack.Count > 0)
{
var node = nodeStack.Pop();
node.Checked = e.Node.Checked;
//foreach (TreeNode subNode in node.Nodes)
//{
// nodeStack.Push(subNode);
//}
}
// treeViewProjects.AfterCheck += treeViewProjects_NodeCheckChanged;
}
private void textBoxFileName_TextChanged(object sender, EventArgs e)
{
}
private void textBoxFileName_Leave(object sender, EventArgs e)
{
// MakeFileNameUnique();
}
private void MakeFileNameUnique()
{
string fileName = textBoxFileName.Text;
int i = 0;
while (CheckFileExists())
{
++i;
textBoxFileName.Text = fileName + i.ToString();
}
}
private void ProjectCheckList_ItemCheck(object sender, ItemCheckEventArgs e)
{
}
private void ProjectCheckList_Click(object sender, EventArgs e)
{
}
private void ProjectCheckList_MouseUp(object sender, MouseEventArgs e)
{
UpdateCreateButtonEnabled();
}
private void UpdateCreateButtonEnabled()
{
bool anythingChecked = false;
Stack<TreeNode> treeNodes = new Stack<TreeNode>();
foreach(TreeNode node in treeViewProjects.Nodes)
{
treeNodes.Push(node);
}
while(treeNodes.Count > 0)
{
TreeNode node = treeNodes.Pop();
if(node.Nodes.Count <= 0 && node.Checked == true)
{
anythingChecked = true;
}
foreach(TreeNode subNode in node.Nodes)
{
treeNodes.Push(subNode);
}
}
buttonCreate.Enabled = anythingChecked;
}
}
}
@@ -10,52 +10,52 @@ using System.Windows.Forms;
namespace CoatiSoftware.SourcetrailPlugin.Wizard
{
public partial class WindowCDBReady : Form
{
private string _message0 = "The CDB ";
private string _message1 = " was created at directory ";
private string _message2 = "Do you want to auto-import it in Sourcetrail now?";
public partial class WindowCDBReady : Form
{
private string _message0 = "The CDB ";
private string _message1 = " was created at directory ";
private string _message2 = "Do you want to auto-import it in Sourcetrail now?";
private WindowCreateCDB.CreationResult _creationResult = new WindowCreateCDB.CreationResult();
private WindowCreateCDB.CreationResult _creationResult = new WindowCreateCDB.CreationResult();
public WindowCDBReady()
{
InitializeComponent();
public WindowCDBReady()
{
InitializeComponent();
label_message.AutoSize = false;
label_message.MaximumSize = new Size((int)((float)MaximumSize.Width * 0.8f), 0);
}
label_message.AutoSize = false;
label_message.MaximumSize = new Size((int)((float)MaximumSize.Width * 0.8f), 0);
}
public void setData(WindowCreateCDB.CreationResult creationResult)
{
_creationResult = creationResult;
public void setData(WindowCreateCDB.CreationResult creationResult)
{
_creationResult = creationResult;
label_message.Text = _message0 + "'" + creationResult._cdbName + "'" + _message1 + "\"" + creationResult._cdbDirectory + "\".";
label_message.Text += "\n" + _message2;
}
label_message.Text = _message0 + "'" + creationResult._cdbName + "'" + _message1 + "\"" + creationResult._cdbDirectory + "\".";
label_message.Text += "\n" + _message2;
}
private void button_ok_Click(object sender, EventArgs e)
{
Close();
}
private void button_ok_Click(object sender, EventArgs e)
{
Close();
}
private void button_open_Click(object sender, EventArgs e)
{
Utility.SystemUtility.OpenWindowsExplorerAtDirectory(_creationResult._cdbDirectory);
}
private void button_open_Click(object sender, EventArgs e)
{
Utility.SystemUtility.OpenWindowsExplorerAtDirectory(_creationResult._cdbDirectory);
}
private void button_import_Click(object sender, EventArgs e)
{
string message = Utility.NetworkProtocolUtility.CreateCreateProjectMessage(_creationResult._cdbDirectory + "\\" + _creationResult._cdbName + ".json", _creationResult._headerDirectories);
private void button_import_Click(object sender, EventArgs e)
{
string message = Utility.NetworkProtocolUtility.CreateCreateProjectMessage(_creationResult._cdbDirectory + "\\" + _creationResult._cdbName + ".json", _creationResult._headerDirectories);
Utility.AsynchronousClient.Send(message);
Utility.AsynchronousClient.Send(message);
Close();
}
Close();
}
private void WindowCDBReady_Resize(object sender, EventArgs e)
{
label_message.MaximumSize = new Size((int)((float)MaximumSize.Width * 0.8f), 0);
}
}
private void WindowCDBReady_Resize(object sender, EventArgs e)
{
label_message.MaximumSize = new Size((int)((float)MaximumSize.Width * 0.8f), 0);
}
}
}
@@ -5,301 +5,295 @@ using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using CoatiSoftware.SourcetrailPlugin.SolutionParser;
namespace CoatiSoftware.SourcetrailPlugin.Wizard
{
public partial class WindowCreateCDB : Form
{
public struct CreationResult
{
public SolutionParser.CompilationDatabase _cdb;
public string _cdbDirectory;
public string _cdbName;
public List<string> _headerDirectories;
}
public delegate void OnFinishedCreatingCDB(CreationResult result);
private OnFinishedCreatingCDB _onFinishedCreateCDB = null;
private List<EnvDTE.Project> _projects = new List<EnvDTE.Project>();
private string _configurationName = "";
private string _platformName = "";
private string _targetDir = "";
private string _fileName = "";
private string _cStandard = "";
private string _solutionDir = "";
private SolutionParser.CompilationDatabase _cdb = null;
CreationResult _result = new CreationResult();
private int _threadCount = 1;
private static object _lockObject = new object();
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
public OnFinishedCreatingCDB CallbackOnFinishedCreatingCDB
{
get { return _onFinishedCreateCDB; }
set { _onFinishedCreateCDB = value; }
}
public List<EnvDTE.Project> Projects
{
get { return _projects; }
set { _projects = value; }
}
public string ConfigurationName
{
get { return _configurationName; }
set { _configurationName = value; }
}
public string PlatformName
{
get { return _platformName; }
set { _platformName = value; }
}
public string TargetDir
{
get { return _targetDir; }
set { _targetDir = value; }
}
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
public string CStandard
{
get { return _cStandard; }
set { _cStandard = value; }
}
public int ThreadCount
{
get { return _threadCount; }
set { _threadCount = value; }
}
public string SolutionDir
{
get { return _solutionDir; }
set { _solutionDir = value; }
}
public SolutionParser.CompilationDatabase CDB
{
get { return _cdb; }
set { _cdb = value; }
}
public WindowCreateCDB()
{
InitializeComponent();
progressBar.Maximum = 100;
progressBar.Value = 0;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
public void StartWorking()
{
// Show();
backgroundWorker1.RunWorkerAsync();
}
private CreationResult CreateCDB()
{
CreationResult result = new CreationResult();
result._cdb = null;
result._cdbDirectory = "";
result._cdbName = "";
result._headerDirectories = new List<string>();
SolutionParser.CompilationDatabase cdb = null;
List<string> headerDirectories = new List<string>();
Logging.Logging.LogInfo("Starting to create CDB");
try
{
SolutionParser.SolutionParser._headerDirectories.Clear();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
cdb = CreateCommandObjects();
watch.Stop();
Logging.Logging.LogInfo("Finished, elapsed time: " + watch.ElapsedMilliseconds.ToString() + " ms");
headerDirectories = SolutionParser.SolutionParser._headerDirectories;
cdb.Name = _fileName;
cdb.Directory = _targetDir;
cdb.SourceProject = _solutionDir;
cdb.LastUpdated = DateTime.Now;
cdb.ConfigurationName = _configurationName;
cdb.PlatformName = _platformName;
cdb.IncludedProjects = new List<string>();
foreach (EnvDTE.Project p in _projects)
{
cdb.IncludedProjects.Add(p.Name);
}
cdb.Clean();
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create CDB: " + e.Message);
}
result._cdb = cdb;
result._cdbDirectory = _targetDir;
result._cdbName = _fileName;
result._headerDirectories = headerDirectories;
Logging.Logging.LogInfo("Done creating CDB");
return result;
}
private SolutionParser.CompilationDatabase CreateCommandObjects()
{
SolutionParser.CompilationDatabase cdb = new SolutionParser.CompilationDatabase();
cdb.Directory = _targetDir;
cdb.Name = _fileName;
File.WriteAllText(_targetDir + "\\" + _fileName + ".json", "");
File.AppendAllText(_targetDir + "\\" + _fileName + ".json", "[\n");
// Mutex commandObjectMutex = new Mutex();
object lockObject = new object();
object lockObject2 = new object();
Utility.QueuedFileWriter fileWriter = new Utility.QueuedFileWriter();
fileWriter.FileName = _fileName + ".json";
fileWriter.TargetDirectory = _targetDir;
fileWriter.startWorking();
try
{
// parallel with tasks
Multitasking.LimitedThreadsTaskScheduler scheduler = new Multitasking.LimitedThreadsTaskScheduler(_threadCount);
TaskFactory factory = new TaskFactory(scheduler);
List<Task> tasks = new List<Task>();
int projectsProcessed = 0;
foreach (EnvDTE.Project project in _projects)
{
string projectName = project.Name;
Logging.Logging.LogInfo("Scheduling " + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(projectName) + " for parsing.");
Task t = factory.StartNew(() =>
{
List<SolutionParser.CommandObject> commandObjects = SolutionParser.SolutionParser.CreateCommandObjects(project, _configurationName, _platformName, _cStandard);
lock (_lockObject)
{
projectsProcessed++;
}
float relativProgress = (float)projectsProcessed / (float)_projects.Count;
Logging.Logging.LogInfo("Processing project \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "\"");
backgroundWorker1.ReportProgress((int)(relativProgress * 100), "Processing project \"" + project.Name + "\"");
foreach (SolutionParser.CommandObject obj in commandObjects)
{
// cdb.AddOrUpdateCommandObject(obj, false); // since the data is written to file right away now, no need to store it
// the cdb is however still needed to store some meta data later
fileWriter.pushMessage(obj.SerializeJSON() + ",");
}
});
tasks.Add(t);
}
int threadCount = System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
Task.WaitAll(tasks.ToArray());
fileWriter.stopWorking();
backgroundWorker1.ReportProgress(100, "Writing data to file. This might take several minutes...");
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create CDB: " + e.Message);
}
finally
{
File.AppendAllText(_targetDir + "\\" + _fileName + ".json", "\n]");
}
return cdb;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
_result = CreateCDB();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if(backgroundWorker1.CancellationPending == false)
{
progressBar.Value = e.ProgressPercentage;
labelStatus.Text = e.UserState as string;
}
else
{
progressBar.Value = 0;
labelStatus.Text = "Cancelling...";
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled == false && e.Error == null /*&& progressBar.Value >= 100*/)
{
if (_onFinishedCreateCDB != null)
{
_onFinishedCreateCDB(_result);
}
}
else
{
Logging.Logging.LogWarning("CDB creation was aborted by user");
}
Close();
}
private void WindowCreateCDB_FormClosed(object sender, FormClosedEventArgs e)
{
backgroundWorker1.CancelAsync();
}
}
public partial class WindowCreateCDB : Form
{
public struct CreationResult
{
public SolutionParser.CompilationDatabase _cdb;
public string _cdbDirectory;
public string _cdbName;
public List<string> _headerDirectories;
}
public delegate void OnFinishedCreatingCDB(CreationResult result);
private OnFinishedCreatingCDB _onFinishedCreateCDB = null;
private List<EnvDTE.Project> _projects = new List<EnvDTE.Project>();
private string _configurationName = "";
private string _platformName = "";
private string _targetDir = "";
private string _fileName = "";
private string _cStandard = "";
private string _solutionDir = "";
private List<string> _headerDirectories;
private SolutionParser.CompilationDatabase _cdb = null;
CreationResult _result = new CreationResult();
private int _threadCount = 1;
private static object _lockObject = new object();
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
public OnFinishedCreatingCDB CallbackOnFinishedCreatingCDB
{
get { return _onFinishedCreateCDB; }
set { _onFinishedCreateCDB = value; }
}
public List<EnvDTE.Project> Projects
{
get { return _projects; }
set { _projects = value; }
}
public string ConfigurationName
{
get { return _configurationName; }
set { _configurationName = value; }
}
public string PlatformName
{
get { return _platformName; }
set { _platformName = value; }
}
public string TargetDir
{
get { return _targetDir; }
set { _targetDir = value; }
}
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
public string CStandard
{
get { return _cStandard; }
set { _cStandard = value; }
}
public int ThreadCount
{
get { return _threadCount; }
set { _threadCount = value; }
}
public string SolutionDir
{
get { return _solutionDir; }
set { _solutionDir = value; }
}
public SolutionParser.CompilationDatabase CDB
{
get { return _cdb; }
set { _cdb = value; }
}
public WindowCreateCDB()
{
InitializeComponent();
progressBar.Maximum = 100;
progressBar.Value = 0;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
public void StartWorking()
{
// Show();
backgroundWorker1.RunWorkerAsync();
}
private CreationResult CreateCDB()
{
CreationResult result = new CreationResult();
result._cdb = null;
result._cdbDirectory = "";
result._cdbName = "";
result._headerDirectories = new List<string>();
Logging.Logging.LogInfo("Starting to create CDB");
SolutionParser.CompilationDatabase cdb = null;
_headerDirectories = new List<string>();
try
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
cdb = CreateCommandObjects();
watch.Stop();
Logging.Logging.LogInfo("Finished, elapsed time: " + watch.ElapsedMilliseconds.ToString() + " ms");
cdb.Name = _fileName;
cdb.Directory = _targetDir;
cdb.SourceProject = _solutionDir;
cdb.LastUpdated = DateTime.Now;
cdb.ConfigurationName = _configurationName;
cdb.PlatformName = _platformName;
cdb.IncludedProjects = new List<string>();
foreach (EnvDTE.Project p in _projects)
{
cdb.IncludedProjects.Add(p.Name);
}
cdb.Clean();
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create CDB: " + e.Message);
}
result._cdb = cdb;
result._cdbDirectory = _targetDir;
result._cdbName = _fileName;
result._headerDirectories = _headerDirectories;
Logging.Logging.LogInfo("Done creating CDB");
return result;
}
private SolutionParser.CompilationDatabase CreateCommandObjects()
{
SolutionParser.CompilationDatabase cdb = new SolutionParser.CompilationDatabase();
cdb.Directory = _targetDir;
cdb.Name = _fileName;
File.WriteAllText(_targetDir + "\\" + _fileName + ".json", "");
File.AppendAllText(_targetDir + "\\" + _fileName + ".json", "[\n");
// Mutex commandObjectMutex = new Mutex();
Utility.QueuedFileWriter fileWriter = new Utility.QueuedFileWriter(_fileName + ".json", _targetDir);
fileWriter.StartWorking();
try
{
Multitasking.LimitedThreadsTaskScheduler scheduler = new Multitasking.LimitedThreadsTaskScheduler(_threadCount);
TaskFactory factory = new TaskFactory(scheduler);
List<Task> tasks = new List<Task>();
int projectsProcessed = 0;
foreach (EnvDTE.Project project in _projects)
{
Logging.Logging.LogInfo("Scheduling project \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "\" for parsing.");
Task task = factory.StartNew(() =>
{
SolutionParser.SolutionParser solutionParser = new SolutionParser.SolutionParser(new VsPathResolver(_targetDir));
List<SolutionParser.CompileCommand> commands = solutionParser.CreateCompileCommands(project, _configurationName, _platformName, _cStandard);
lock (_lockObject)
{
projectsProcessed++;
_headerDirectories.AddRange(solutionParser.HeaderDirectories);
}
float relativProgress = (float)projectsProcessed / (float)_projects.Count;
Logging.Logging.LogInfo("Processing project \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "\"");
backgroundWorker1.ReportProgress((int)(relativProgress * 100), "Processing project \"" + project.Name + "\"");
foreach (SolutionParser.CompileCommand command in commands)
{
// cdb.AddOrUpdateCommandObject(obj, false); // since the data is written to file right away now, no need to store it
// the cdb is however still needed to store some meta data later
string serializedCommand = "";
foreach (string line in command.SerializeToJson().Split('\n'))
{
serializedCommand += " " + line + "\n";
}
serializedCommand = serializedCommand.TrimEnd('\n');
fileWriter.PushMessage(serializedCommand + ",\n");
}
});
tasks.Add(task);
}
int threadCount = System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
Task.WaitAll(tasks.ToArray());
fileWriter.StopWorking();
backgroundWorker1.ReportProgress(100, "Writing data to file. This might take several minutes...");
}
catch(Exception e)
{
Logging.Logging.LogError("Failed to create CDB: " + e.Message);
}
finally
{
File.AppendAllText(_targetDir + "\\" + _fileName + ".json", "\n]");
}
return cdb;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
_result = CreateCDB();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if(backgroundWorker1.CancellationPending == false)
{
progressBar.Value = e.ProgressPercentage;
labelStatus.Text = e.UserState as string;
}
else
{
progressBar.Value = 0;
labelStatus.Text = "Cancelling...";
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled == false && e.Error == null /*&& progressBar.Value >= 100*/)
{
_onFinishedCreateCDB?.Invoke(_result);
}
else
{
Logging.Logging.LogWarning("CDB creation was aborted by user");
}
Close();
}
private void WindowCreateCDB_FormClosed(object sender, FormClosedEventArgs e)
{
backgroundWorker1.CancelAsync();
}
}
}
@@ -3,78 +3,78 @@ using System.Windows.Forms;
namespace CoatiSoftware.SourcetrailPlugin.Wizard
{
public partial class WindowMessage : Form
{
private string _title = "Title";
private string _message = "Message";
public partial class WindowMessage : Form
{
private string _title = "Title";
private string _message = "Message";
public delegate void Callback();
public delegate void Callback();
private Callback _onOK = null;
private Callback _onCancel = null;
private Callback _onOK = null;
private Callback _onCancel = null;
public string Title
{
get { return _title; }
set { _title = value; }
}
public string Title
{
get { return _title; }
set { _title = value; }
}
public string Message
{
get { return _message; }
set { _message = value; }
}
public string Message
{
get { return _message; }
set { _message = value; }
}
public Callback OnOK
{
get { return _onOK; }
set { _onOK = value; }
}
public Callback OnOK
{
get { return _onOK; }
set { _onOK = value; }
}
public Callback OnCancel
{
get { return _onCancel; }
set { _onCancel = value; }
}
public Callback OnCancel
{
get { return _onCancel; }
set { _onCancel = value; }
}
public WindowMessage()
{
InitializeComponent();
}
public WindowMessage()
{
InitializeComponent();
}
public void RefreshWindow()
{
Text = _title;
labelContent.Text = _message;
public void RefreshWindow()
{
Text = _title;
labelContent.Text = _message;
if(_onCancel != null)
{
buttonCancel.Show();
}
else
{
buttonCancel.Hide();
}
}
if(_onCancel != null)
{
buttonCancel.Show();
}
else
{
buttonCancel.Hide();
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
if(_onCancel != null)
{
_onCancel();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
if(_onCancel != null)
{
_onCancel();
}
Close();
}
Close();
}
private void buttonOK_Click(object sender, EventArgs e)
{
if(_onOK != null)
{
_onOK();
}
private void buttonOK_Click(object sender, EventArgs e)
{
if(_onOK != null)
{
_onOK();
}
Close();
}
}
Close();
}
}
}
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="10.0.2" targetFramework="net461" />
</packages>
@@ -1,23 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="acf15780-03b5-440e-a41e-db79b7043fc2" Version="0.9.8" Language="en-US" Publisher="Coati Software OG" />
<Identity Id="acf15780-03b5-440e-a41e-db79b7043fc2" Version="0.9.81" Language="en-US" Publisher="Coati Software OG" />
<DisplayName>SourcetrailPlugin</DisplayName>
<Description xml:space="preserve">This package allows Sourcetrail to communicate with Visual Studio and vice versa.</Description>
<MoreInfo>http://www.sourcetrail.com/</MoreInfo>
<ReleaseNotes>Creation of CDBs is in beta and may change in future versions</ReleaseNotes>
<Description xml:space="preserve">The Sourcetrail Plugin allows Visual Studio to communicate with Sourcetrail - an external source code exploration tool. It also enables Visual Studio to generate a Clang Compilation Database from any Visual Studio Solution which can be used to automate the Sourcetrail project setup and to run other Clang based tools.</Description>
<MoreInfo>https://www.sourcetrail.com/</MoreInfo>
<License>LICENSE.txt</License>
<GettingStartedGuide>https://www.sourcetrail.com/documentation/#VisualStudio</GettingStartedGuide>
<Icon>sourcetrail.ico</Icon>
</Metadata>
<Installation InstalledByMsi="false">
<InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="11.0" />
<InstallationTarget Version="[12.0,13.0)" Id="Microsoft.VisualStudio.Pro" />
<InstallationTarget Version="[14.0,15.0)" Id="Microsoft.VisualStudio.Community" />
<InstallationTarget Version="[11.0,16.0)" Id="Microsoft.VisualStudio.Community" />
</Installation>
<Dependencies>
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="4.5" />
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="4.6" />
<Dependency Id="Microsoft.VisualStudio.MPF.11.0" DisplayName="Visual Studio MPF 11.0" d:Source="Installed" Version="11.0" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
</Assets>
<Prerequisites>
<Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,16.0)" DisplayName="Visual Studio core editor" />
</Prerequisites>
</PackageManifest>
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VCProjectEngineWrapperVs2012")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("VCProjectEngineWrapperVs2012")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("C5439B90-42E7-414D-8C3F-BDCABB0592E2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VCProjectEngineWrapperVs2013")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("VCProjectEngineWrapperVs2013")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8718929b-5270-4e5a-8998-48ac7ce19dc2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VCProjectEngineWrapperVs2015")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("VCProjectEngineWrapperVs2015")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1c139999-9592-4891-aa62-2c8a16430d0a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VCProjectEngineWrapperVs2017")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("VCProjectEngineWrapperVs2017")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b49207f9-89a3-42d8-bc04-8bf77ed2e295")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,21 @@
using Microsoft.VisualStudio.VCProjectEngine;
namespace VCProjectEngineWrapper
{
public static class Utility
{
public static string GetWrappedVersion()
{
return
#if (VS2012)
"11.0";
#elif (VS2013)
"12.0";
#elif (VS2015)
"14.0";
#elif (VS2017)
"15.0";
#endif
}
}
}
@@ -0,0 +1,70 @@
using Microsoft.VisualStudio.VCProjectEngine;
namespace VCProjectEngineWrapper
{
public class
#if (VS2012)
VCCLCompilerToolWrapperVs2012
#elif (VS2013)
VCCLCompilerToolWrapperVs2013
#elif (VS2015)
VCCLCompilerToolWrapperVs2015
#elif (VS2017)
VCCLCompilerToolWrapperVs2017
#endif
: IVCCLCompilerToolWrapper
{
private VCCLCompilerTool _wrapped = null;
public
#if (VS2012)
VCCLCompilerToolWrapperVs2012
#elif (VS2013)
VCCLCompilerToolWrapperVs2013
#elif (VS2015)
VCCLCompilerToolWrapperVs2015
#elif (VS2017)
VCCLCompilerToolWrapperVs2017
#endif
(object wrapped)
{
_wrapped = wrapped as VCCLCompilerTool;
}
public bool isValid()
{
return (_wrapped != null);
}
public string GetWrappedVersion()
{
return Utility.GetWrappedVersion();
}
public string GetAdditionalOptions()
{
return _wrapped.AdditionalOptions;
}
public bool GetCompilesAsC()
{
return _wrapped.CompileAs == CompileAsOptions.compileAsC;
}
public string GetToolPath()
{
return _wrapped.ToolPath;
}
public string[] GetAdditionalIncludeDirectories()
{
return _wrapped.AdditionalIncludeDirectories.Split(';');
}
public string[] GetPreprocessorDefinitions()
{
return _wrapped.PreprocessorDefinitions.Split(';');
}
}
}
@@ -0,0 +1,108 @@
using Microsoft.VisualStudio.VCProjectEngine;
using System;
using System.Collections;
namespace VCProjectEngineWrapper
{
public class
#if (VS2012)
VCConfigurationWrapperVs2012
#elif (VS2013)
VCConfigurationWrapperVs2013
#elif (VS2015)
VCConfigurationWrapperVs2015
#elif (VS2017)
VCConfigurationWrapperVs2017
#endif
: IVCConfigurationWrapper
{
private VCConfiguration _wrapped = null;
public
#if (VS2012)
VCConfigurationWrapperVs2012
#elif (VS2013)
VCConfigurationWrapperVs2013
#elif (VS2015)
VCConfigurationWrapperVs2015
#elif (VS2017)
VCConfigurationWrapperVs2017
#endif
(object wrapped)
{
_wrapped = wrapped as VCConfiguration;
}
public bool isValid()
{
return (_wrapped != null);
}
public string GetWrappedVersion()
{
return Utility.GetWrappedVersion();
}
public string EvaluateMacro(string macro)
{
return _wrapped.Evaluate(macro);
}
public IVCCLCompilerToolWrapper GetCompilerTool()
{
try
{
IEnumerable tools = _wrapped.Tools as IEnumerable;
foreach (Object tool in tools)
{
VCCLCompilerTool compilerTool = tool as VCCLCompilerTool;
if (compilerTool != null)
{
return new
#if (VS2012)
VCCLCompilerToolWrapperVs2012
#elif (VS2013)
VCCLCompilerToolWrapperVs2013
#elif (VS2015)
VCCLCompilerToolWrapperVs2015
#elif (VS2017)
VCCLCompilerToolWrapperVs2017
#endif
(compilerTool);
}
}
}
catch (Exception e)
{
// Logging.Logging.LogError("Failed to retreive compiler tool: " + e.Message);
}
return new
#if (VS2012)
VCCLCompilerToolWrapperVs2012
#elif (VS2013)
VCCLCompilerToolWrapperVs2013
#elif (VS2015)
VCCLCompilerToolWrapperVs2015
#elif (VS2017)
VCCLCompilerToolWrapperVs2017
#endif
(null);
}
public IVCPlatformWrapper GetPlatform()
{
return new
#if (VS2012)
VCPlatformWrapperVs2012
#elif (VS2013)
VCPlatformWrapperVs2013
#elif (VS2015)
VCPlatformWrapperVs2015
#elif (VS2017)
VCPlatformWrapperVs2017
#endif
(_wrapped.Platform);
}
}
}
@@ -0,0 +1,59 @@
using Microsoft.VisualStudio.VCProjectEngine;
namespace VCProjectEngineWrapper
{
public class
#if (VS2012)
VCFileConfigurationWrapperVs2012
#elif (VS2013)
VCFileConfigurationWrapperVs2013
#elif (VS2015)
VCFileConfigurationWrapperVs2015
#elif (VS2017)
VCFileConfigurationWrapperVs2017
#endif
: IVCFileConfigurationWrapper
{
private VCFileConfiguration _wrapped = null;
public
#if (VS2012)
VCFileConfigurationWrapperVs2012
#elif (VS2013)
VCFileConfigurationWrapperVs2013
#elif (VS2015)
VCFileConfigurationWrapperVs2015
#elif (VS2017)
VCFileConfigurationWrapperVs2017
#endif
(object wrapped)
{
_wrapped = wrapped as VCFileConfiguration;
}
public bool isValid()
{
return (_wrapped != null);
}
public string GetWrappedVersion()
{
return Utility.GetWrappedVersion();
}
public IVCCLCompilerToolWrapper GetTool()
{
return new
#if (VS2012)
VCCLCompilerToolWrapperVs2012
#elif (VS2013)
VCCLCompilerToolWrapperVs2013
#elif (VS2015)
VCCLCompilerToolWrapperVs2015
#elif (VS2017)
VCCLCompilerToolWrapperVs2017
#endif
(_wrapped.Tool);
}
}
}
@@ -0,0 +1,90 @@
using Microsoft.VisualStudio.VCProjectEngine;
using System;
using System.Collections.Generic;
namespace VCProjectEngineWrapper
{
public class
#if (VS2012)
VCFileWrapperVs2012
#elif (VS2013)
VCFileWrapperVs2013
#elif (VS2015)
VCFileWrapperVs2015
#elif (VS2017)
VCFileWrapperVs2017
#endif
: IVCFileWrapper
{
private VCFile _wrapped = null;
public
#if (VS2012)
VCFileWrapperVs2012
#elif (VS2013)
VCFileWrapperVs2013
#elif (VS2015)
VCFileWrapperVs2015
#elif (VS2017)
VCFileWrapperVs2017
#endif
(object wrapped)
{
_wrapped = wrapped as VCFile;
}
public bool isValid()
{
return (_wrapped != null);
}
public string GetWrappedVersion()
{
return Utility.GetWrappedVersion();
}
public string GetSubType()
{
return _wrapped.SubType;
}
public IVCProjectWrapper GetProject()
{
return new
#if (VS2012)
VCProjectWrapperVs2012
#elif (VS2013)
VCProjectWrapperVs2013
#elif (VS2015)
VCProjectWrapperVs2015
#elif (VS2017)
VCProjectWrapperVs2017
#endif
(_wrapped.project);
}
public List<IVCFileConfigurationWrapper> GetFileConfigurations()
{
List<IVCFileConfigurationWrapper> fileConfigurations = new List<IVCFileConfigurationWrapper>();
foreach (Object configuration in _wrapped.FileConfigurations)
{
IVCFileConfigurationWrapper vcFileConfig = new
#if (VS2012)
VCFileConfigurationWrapperVs2012
#elif (VS2013)
VCFileConfigurationWrapperVs2013
#elif (VS2015)
VCFileConfigurationWrapperVs2015
#elif (VS2017)
VCFileConfigurationWrapperVs2017
#endif
(configuration);
if (vcFileConfig.isValid())
{
fileConfigurations.Add(vcFileConfig);
}
}
return fileConfigurations;
}
}
}
@@ -0,0 +1,55 @@
using Microsoft.VisualStudio.VCProjectEngine;
namespace VCProjectEngineWrapper
{
public class
#if (VS2012)
VCPlatformWrapperVs2012
#elif (VS2013)
VCPlatformWrapperVs2013
#elif (VS2015)
VCPlatformWrapperVs2015
#elif (VS2017)
VCPlatformWrapperVs2017
#endif
: IVCPlatformWrapper
{
private VCPlatform _wrapped = null;
public
#if (VS2012)
VCPlatformWrapperVs2012
#elif (VS2013)
VCPlatformWrapperVs2013
#elif (VS2015)
VCPlatformWrapperVs2015
#elif (VS2017)
VCPlatformWrapperVs2017
#endif
(object wrapped)
{
_wrapped = wrapped as VCPlatform;
}
public bool isValid()
{
return (_wrapped != null);
}
public string GetWrappedVersion()
{
return Utility.GetWrappedVersion();
}
public string GetExecutableDirectories()
{
return _wrapped.ExecutableDirectories;
}
public string[] GetIncludeDirectories()
{
return _wrapped.IncludeDirectories.Split(';');
}
}
}
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C5439B90-42E7-414D-8C3F-BDCABB0592E2}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VCProjectEngineWrapper</RootNamespace>
<AssemblyName>VCProjectEngineWrapperVs2012</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;VS2012</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;VS2012</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>KeyVs2012.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VisualStudio.VCProjectEngine, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfoVs2012.cs" />
<Compile Include="Utility.cs" />
<Compile Include="VCCLCompilerToolWrapper.cs" />
<Compile Include="VCConfigurationWrapper.cs" />
<Compile Include="VCFileConfigurationWrapper.cs" />
<Compile Include="VCFileWrapper.cs" />
<Compile Include="VCPlatformWrapper.cs" />
<Compile Include="VCProjectWrapper.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj">
<Project>{F592DB46-0C77-470B-AAF8-80C51F44380E}</Project>
<Name>VCProjectEngineWrapperInterfaces</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="KeyVs2012.snk" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8718929C-5270-4E5A-8998-48AC7CE19DC2}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VCProjectEngineWrapper</RootNamespace>
<AssemblyName>VCProjectEngineWrapperVs2013</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;VS2013</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;VS2013</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>KeyVs2013.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VisualStudio.VCProjectEngine, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfoVs2013.cs" />
<Compile Include="Utility.cs" />
<Compile Include="VCCLCompilerToolWrapper.cs" />
<Compile Include="VCConfigurationWrapper.cs" />
<Compile Include="VCFileConfigurationWrapper.cs" />
<Compile Include="VCFileWrapper.cs" />
<Compile Include="VCPlatformWrapper.cs" />
<Compile Include="VCProjectWrapper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="KeyVs2013.snk" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj">
<Project>{F592DB46-0C77-470B-AAF8-80C51F44380E}</Project>
<Name>VCProjectEngineWrapperInterfaces</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{1C139999-9592-4891-AA62-2C8A16430D0A}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VCProjectEngineWrapper</RootNamespace>
<AssemblyName>VCProjectEngineWrapperVs2015</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;VS2015</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;VS2015</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>KeyVs2015.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VisualStudio.VCProjectEngine, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfoVs2015.cs" />
<Compile Include="Utility.cs" />
<Compile Include="VCCLCompilerToolWrapper.cs" />
<Compile Include="VCConfigurationWrapper.cs" />
<Compile Include="VCFileConfigurationWrapper.cs" />
<Compile Include="VCFileWrapper.cs" />
<Compile Include="VCPlatformWrapper.cs" />
<Compile Include="VCProjectWrapper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="KeyVs2015.snk" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj">
<Project>{F592DB46-0C77-470B-AAF8-80C51F44380E}</Project>
<Name>VCProjectEngineWrapperInterfaces</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B49207F9-89A3-42D8-BC04-8BF77ED2E295}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VCProjectEngineWrapper</RootNamespace>
<AssemblyName>VCProjectEngineWrapperVs2017</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;VS2017</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;VS2017</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>KeyVs2017.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.VisualStudio.VCProjectEngine, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfoVs2017.cs" />
<Compile Include="Utility.cs" />
<Compile Include="VCCLCompilerToolWrapper.cs" />
<Compile Include="VCConfigurationWrapper.cs" />
<Compile Include="VCFileConfigurationWrapper.cs" />
<Compile Include="VCFileWrapper.cs" />
<Compile Include="VCPlatformWrapper.cs" />
<Compile Include="VCProjectWrapper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="KeyVs2017.snk" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj">
<Project>{f592db46-0c77-470b-aaf8-80c51f44380e}</Project>
<Name>VCProjectEngineWrapperInterfaces</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,102 @@
using Microsoft.VisualStudio.VCProjectEngine;
using System;
using System.Collections;
namespace VCProjectEngineWrapper
{
public class
#if (VS2012)
VCProjectWrapperVs2012
#elif (VS2013)
VCProjectWrapperVs2013
#elif (VS2015)
VCProjectWrapperVs2015
#elif (VS2017)
VCProjectWrapperVs2017
#endif
: IVCProjectWrapper
{
private VCProject _wrapped = null;
public
#if (VS2012)
VCProjectWrapperVs2012
#elif (VS2013)
VCProjectWrapperVs2013
#elif (VS2015)
VCProjectWrapperVs2015
#elif (VS2017)
VCProjectWrapperVs2017
#endif
(object wrapped)
{
_wrapped = wrapped as VCProject;
}
public bool isValid()
{
return (_wrapped != null);
}
public string GetWrappedVersion()
{
return Utility.GetWrappedVersion();
}
public IVCConfigurationWrapper getConfiguration(string configurationName, string platformName)
{
try
{
IEnumerable configurations = _wrapped.Configurations as IEnumerable;
foreach (Object configuration in configurations)
{
VCConfiguration vcProjectConfig = configuration as VCConfiguration;
if (vcProjectConfig != null &&
vcProjectConfig.ConfigurationName == configurationName &&
vcProjectConfig.Platform.Name == platformName)
{
return new
#if (VS2012)
VCConfigurationWrapperVs2012
#elif (VS2013)
VCConfigurationWrapperVs2013
#elif (VS2015)
VCConfigurationWrapperVs2015
#elif (VS2017)
VCConfigurationWrapperVs2017
#endif
(vcProjectConfig);
}
}
}
catch (Exception e)
{
// Logging.Logging.LogError("Failed to retreive project configuration: " + e.Message);
}
// Logging.Logging.LogError("Failed to find project config matching with \"" + configurationName + "\"");
return new
#if (VS2012)
VCConfigurationWrapperVs2012
#elif (VS2013)
VCConfigurationWrapperVs2013
#elif (VS2015)
VCConfigurationWrapperVs2015
#elif (VS2017)
VCConfigurationWrapperVs2017
#endif
(null);
}
public string GetProjectDirectory()
{
return _wrapped.ProjectDirectory;
}
public string GetName()
{
return _wrapped.Name;
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VCProjectEngineWrapperFactory")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("VCProjectEngineWrapperFactory")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8188d64d-e880-490c-b267-b493a2171be3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,27 @@
namespace VCProjectEngineWrapper
{
public static class VCFileWrapperFactory
{
public static IVCFileWrapper create(object wrapped)
{
IVCFileWrapper wrapper = null;
wrapper = new VCFileWrapperVs2017(wrapped);
if (wrapper == null || !wrapper.isValid())
{
wrapper = new VCFileWrapperVs2015(wrapped);
}
if (wrapper == null || !wrapper.isValid())
{
wrapper = new VCFileWrapperVs2013(wrapped);
}
if (wrapper == null || !wrapper.isValid())
{
wrapper = new VCFileWrapperVs2012(wrapped);
}
return wrapper;
}
}
}
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8188D64D-E880-490C-B267-B493A2171BE3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VCProjectEngineWrapper</RootNamespace>
<AssemblyName>VCProjectEngineWrapperFactory</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>Key.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="VCFileWrapperFactory.cs" />
<Compile Include="VCProjectWrapperFactory.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VCProjectEngineWrapperInterfaces\VCProjectEngineWrapperInterfaces.csproj">
<Project>{f592db46-0c77-470b-aaf8-80c51f44380e}</Project>
<Name>VCProjectEngineWrapperInterfaces</Name>
</ProjectReference>
<ProjectReference Include="..\VCProjectEngineWrapper\VCProjectEngineWrapperVs2012.csproj">
<Project>{c5439b90-42e7-414d-8c3f-bdcabb0592e2}</Project>
<Name>VCProjectEngineWrapperVs2012</Name>
</ProjectReference>
<ProjectReference Include="..\VCProjectEngineWrapper\VCProjectEngineWrapperVs2013.csproj">
<Project>{8718929c-5270-4e5a-8998-48ac7ce19dc2}</Project>
<Name>VCProjectEngineWrapperVs2013</Name>
</ProjectReference>
<ProjectReference Include="..\VCProjectEngineWrapper\VCProjectEngineWrapperVs2015.csproj">
<Project>{1c139999-9592-4891-aa62-2c8a16430d0a}</Project>
<Name>VCProjectEngineWrapperVs2015</Name>
</ProjectReference>
<ProjectReference Include="..\VCProjectEngineWrapper\VCProjectEngineWrapperVs2017.csproj">
<Project>{b49207f9-89a3-42d8-bc04-8bf77ed2e295}</Project>
<Name>VCProjectEngineWrapperVs2017</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="Key.snk" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,27 @@
namespace VCProjectEngineWrapper
{
public static class VCProjectWrapperFactory
{
public static IVCProjectWrapper create(object wrapped)
{
IVCProjectWrapper wrapper = null;
wrapper = new VCProjectWrapperVs2017(wrapped);
if (wrapper == null || !wrapper.isValid())
{
wrapper = new VCProjectWrapperVs2015(wrapped);
}
if (wrapper == null || !wrapper.isValid())
{
wrapper = new VCProjectWrapperVs2013(wrapped);
}
if (wrapper == null || !wrapper.isValid())
{
wrapper = new VCProjectWrapperVs2012(wrapped);
}
return wrapper;
}
}
}
@@ -0,0 +1,14 @@
namespace VCProjectEngineWrapper
{
public interface IVCCLCompilerToolWrapper
{
string GetWrappedVersion();
bool isValid();
string GetAdditionalOptions();
bool GetCompilesAsC();
string GetToolPath();
string[] GetAdditionalIncludeDirectories();
string[] GetPreprocessorDefinitions();
}
}
@@ -0,0 +1,12 @@
namespace VCProjectEngineWrapper
{
public interface IVCConfigurationWrapper
{
string GetWrappedVersion();
bool isValid();
string EvaluateMacro(string macro);
IVCCLCompilerToolWrapper GetCompilerTool();
IVCPlatformWrapper GetPlatform();
}
}
@@ -0,0 +1,10 @@
namespace VCProjectEngineWrapper
{
public interface IVCFileConfigurationWrapper
{
string GetWrappedVersion();
bool isValid();
IVCCLCompilerToolWrapper GetTool();
}
}
@@ -0,0 +1,14 @@
using System.Collections.Generic;
namespace VCProjectEngineWrapper
{
public interface IVCFileWrapper
{
string GetWrappedVersion();
bool isValid();
string GetSubType();
IVCProjectWrapper GetProject();
List<IVCFileConfigurationWrapper> GetFileConfigurations();
}
}
@@ -0,0 +1,11 @@
namespace VCProjectEngineWrapper
{
public interface IVCPlatformWrapper
{
string GetWrappedVersion();
bool isValid();
string GetExecutableDirectories();
string[] GetIncludeDirectories();
}
}
@@ -0,0 +1,12 @@
namespace VCProjectEngineWrapper
{
public interface IVCProjectWrapper
{
string GetWrappedVersion();
bool isValid();
IVCConfigurationWrapper getConfiguration(string configurationName, string platformName);
string GetProjectDirectory();
string GetName();
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VCProjectWrapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coati Software")]
[assembly: AssemblyProduct("VCProjectWrapper")]
[assembly: AssemblyCopyright("Copyright © Coati Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f592db46-0c77-470b-aaf8-80c51f44380e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{F592DB46-0C77-470B-AAF8-80C51F44380E}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VCProjectEngineWrapper</RootNamespace>
<AssemblyName>VCProjectWrapper</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>Key.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="IVCCLCompilerToolWrapper.cs" />
<Compile Include="IVCConfigurationWrapper.cs" />
<Compile Include="IVCFileConfigurationWrapper.cs" />
<Compile Include="IVCFileWrapper.cs" />
<Compile Include="IVCPlatformWrapper.cs" />
<Compile Include="IVCProjectWrapper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Key.snk" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Some files were not shown because too many files have changed in this diff Show More