Пример #1
0
		public void Compile (PythonProject project,
		                     FilePath fileName,
		                     PythonConfiguration config,
		                     BuildResult result)
		{
			if (String.IsNullOrEmpty (fileName))
				throw new ArgumentNullException ("fileName");
			else if (config == null)
				throw new ArgumentNullException ("config");
			else if (result == null)
				throw new ArgumentNullException ("result");
			else if (Runtime == null)
				throw new InvalidOperationException ("No supported runtime!");
			
			// Get our relative path within the project
			if (!fileName.IsChildPathOf (project.BaseDirectory)) {
				Console.WriteLine ("File is not within our project!");
				return;
			}
			
			FilePath relName = fileName.ToRelative (project.BaseDirectory);
			string outFile = relName.ToAbsolute (config.OutputDirectory);
			
			if (!outFile.EndsWith (".py"))
				return;
			
			// Create the destination directory
			FileInfo fileInfo = new FileInfo (outFile);
			if (!fileInfo.Directory.Exists)
				fileInfo.Directory.Create ();
			
			// Create and start our process to generate the byte code
			Process process = BuildCompileProcess (fileName, outFile, config.Optimize);
			process.Start ();
			process.WaitForExit ();
			
			// Parse errors and warnings
			string output = process.StandardError.ReadToEnd ();
			
			// Extract potential Warnings
			foreach (Match m in m_WarningRegex.Matches (output)) {
				string lineNum  = m.Groups[m_WarningRegex.GroupNumberFromName ("line")].Value;
				string message  = m.Groups[m_WarningRegex.GroupNumberFromName ("message")].Value;
				
				result.AddWarning (fileName, Int32.Parse (lineNum), 0, String.Empty, message);
			}
			
			// Extract potential SyntaxError
			foreach (Match m in m_ErrorRegex.Matches (output)) {
				string lineNum = m.Groups[m_ErrorRegex.GroupNumberFromName ("line")].Value;
				result.AddError (fileName, Int32.Parse (lineNum), 0, String.Empty, "SyntaxError");
			}
		}
Пример #2
0
        private void OnProjectLoaded(object sender, ProjectEventArgs e)
        {
            var pyProj = PythonProject.FromObject(e.Project);

            if (pyProj != null)
            {
                var analyzer = pyProj.Analyzer;
                if (analyzer != null)
                {
                    _projectInfo[pyProj] = new ProjectInfo(this, pyProj);
                }
            }

            TestContainersUpdated?.Invoke(this, EventArgs.Empty);
        }
Пример #3
0
        public TestContainer GetTestContainer(PythonProject project, string path)
        {
            ProjectInfo projectInfo;

            if (_projectInfo.TryGetValue(project, out projectInfo))
            {
                TestContainer container;
                if (projectInfo.TryGetContainer(path, out container))
                {
                    return(container);
                }
            }

            return(null);
        }
        public void SetUpFixture()
        {
            MSBuildEngineHelper.InitMSBuildEngine();

            List <LanguageBindingDescriptor> bindings = new List <LanguageBindingDescriptor>();

            using (TextReader reader = PythonBindingAddInFile.ReadAddInFile()) {
                AddIn addin = AddIn.Load(reader, String.Empty);
                bindings.Add(new LanguageBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/LanguageBindings", "Python")));
            }
            LanguageBindingService.SetBindings(bindings);

            // Set up IProjectContent so the ConvertProjectToPythonProjectCommand can
            // locate the startup object and determine it's filename.

            mockProjectContent = new MockProjectContent();
            MockClass mainClass = new MockClass(mockProjectContent, startupObject);

            mainClass.CompilationUnit.FileName           = @"d:\projects\test\src\Main2.cs";
            mockProjectContent.ClassToReturnFromGetClass = mainClass;

            mockTextEditorProperties             = new MockTextEditorProperties();
            convertProjectCommand                = new DerivedConvertProjectToPythonProjectCommand(mockTextEditorProperties);
            convertProjectCommand.ProjectContent = mockProjectContent;
            mockTextEditorProperties.Encoding    = Encoding.Unicode;

            Solution solution = new Solution();

            sourceProject          = new MSBuildBasedProject(solution.BuildEngine);
            sourceProject.Parent   = solution;
            sourceProject.FileName = @"d:\projects\test\source.csproj";
            sourceProject.SetProperty(null, null, "StartupObject", startupObject, PropertyStorageLocations.Base, true);
            mainFile      = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Main.cs");
            targetProject = (PythonProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject);
            convertProjectCommand.CallCopyProperties(sourceProject, targetProject);
            targetMainFile = new FileProjectItem(targetProject, mainFile.ItemType, mainFile.Include);
            mainFile.CopyMetadataTo(targetMainFile);

            main2File       = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Main2.cs");
            targetMain2File = new FileProjectItem(targetProject, main2File.ItemType, main2File.Include);
            main2File.CopyMetadataTo(targetMain2File);

            convertProjectCommand.AddParseableFileContent(mainFile.FileName, mainSource);
            convertProjectCommand.AddParseableFileContent(main2File.FileName, main2Source);

            convertProjectCommand.CallConvertFile(mainFile, targetMainFile);
            convertProjectCommand.CallConvertFile(main2File, targetMain2File);
        }
Пример #5
0
        private async Task OnProjectLoadedAsync(IVsProject project)
        {
            var pyProj = PythonProject.FromObject(project);

            if (pyProj != null)
            {
                var analyzer = await pyProj.GetAnalyzerAsync();

                if (analyzer != null)
                {
                    _projectInfo[pyProj] = new ProjectInfo(this, pyProj);
                }
            }

            TestContainersUpdated?.Invoke(this, EventArgs.Empty);
        }
Пример #6
0
        private void OnProjectUnloaded(object sender, ProjectEventArgs e)
        {
            if (e.Project != null)
            {
                var         pyProj = PythonProject.FromObject(e.Project);
                ProjectInfo events;
                if (pyProj != null &&
                    _projectInfo.TryGetValue(pyProj, out events) &&
                    _projectInfo.Remove(pyProj))
                {
                    events.Dispose();
                }
            }

            TestContainersUpdated?.Invoke(this, EventArgs.Empty);
        }
Пример #7
0
        public override void Apply()
        {
            Project.SetProjectProperty(CommonConstants.StartupFile, _control.StartupFile);
            Project.SetProjectProperty(CommonConstants.WorkingDirectory, _control.WorkingDirectory);
            Project.SetProjectProperty(CommonConstants.IsWindowsApplication, _control.IsWindowsApplication.ToString());

            var interp = _control.DefaultInterpreter;

            if (interp != null && !PythonProject.InterpreterFactories.Contains(interp))
            {
                PythonProject.AddInterpreter(interp.Configuration.Id);
            }
            PythonProject.SetInterpreterFactory(_control.DefaultInterpreter);
            IsDirty = false;
            LoadSettings();
        }
Пример #8
0
        private static TestFrameworkType GetTestFramework(PythonProject pyProj)
        {
            var testFrameworkType = TestFrameworkType.None;

            try {
                string testFrameworkStr = pyProj.GetProperty(PythonConstants.TestFrameworkSetting);
                if (Enum.TryParse <TestFrameworkType>(testFrameworkStr, ignoreCase: true, out TestFrameworkType parsedFramework))
                {
                    testFrameworkType = parsedFramework;
                }
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                Trace.WriteLine("Exception : " + ex.Message);
            }

            return(testFrameworkType);
        }
        public void SetUp()
        {
            PythonMSBuildEngineHelper.InitMSBuildEngine();

            ProjectCreateInformation info = new ProjectCreateInformation();

            info.Solution              = new Solution(new MockProjectChangeWatcher());
            info.ProjectName           = "Test";
            info.OutputProjectFileName = @"C:\Projects\Test\Test.pyproj";
            info.RootNamespace         = "Test";

            project = new PythonProject(info);

            compilingOptionsPanel       = new DerivedCompilingOptionsPanel();
            compilingOptionsPanel.Owner = project;
            compilingOptionsPanel.LoadPanelContents();
        }
        public void SetUp()
        {
            MSBuildEngineHelper.InitMSBuildEngine();

            ProjectCreateInformation info = new ProjectCreateInformation();

            info.Solution              = new Solution();
            info.ProjectName           = "Test";
            info.OutputProjectFileName = @"C:\Projects\Test\Test.pyproj";
            info.RootNamespace         = "Test";

            project = new PythonProject(info);

            appSettingsPanel = new DerivedApplicationSettingsPanel();
            appSettingsPanel.CustomizationObject = project;
            appSettingsPanel.LoadPanelContents();
        }
        public void SetUpFixture()
        {
            MSBuildEngineHelper.InitMSBuildEngine();

            List <LanguageBindingDescriptor> bindings = new List <LanguageBindingDescriptor>();

            using (TextReader reader = PythonBindingAddInFile.ReadAddInFile()) {
                AddIn addin = AddIn.Load(reader, String.Empty);
                bindings.Add(new LanguageBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/LanguageBindings", "Python")));
            }
            LanguageBindingService.SetBindings(bindings);

            mockTextEditorProperties          = new MockTextEditorProperties();
            convertProjectCommand             = new DerivedConvertProjectToPythonProjectCommand(mockTextEditorProperties);
            mockTextEditorProperties.Encoding = Encoding.Unicode;

            sourceProject           = new MockProject();
            sourceProject.Directory = @"d:\projects\test";
            source        = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Program.cs");
            targetProject = (PythonProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject);
            target        = new FileProjectItem(targetProject, source.ItemType, source.Include);
            source.CopyMetadataTo(target);

            textFileSource = new FileProjectItem(sourceProject, ItemType.None, @"src\readme.txt");
            textFileTarget = new FileProjectItem(targetProject, textFileSource.ItemType, textFileSource.Include);
            textFileSource.CopyMetadataTo(textFileTarget);

            foreach (ProjectItem item in targetProject.Items)
            {
                ReferenceProjectItem reference = item as ReferenceProjectItem;
                if ((reference != null) && (reference.Name == "IronPython"))
                {
                    ironPythonReference = reference;
                    break;
                }
            }

            convertProjectCommand.AddParseableFileContent(source.FileName, sourceCode);

            convertProjectCommand.CallConvertFile(source, target);
            convertProjectCommand.CallConvertFile(textFileSource, textFileTarget);
        }
Пример #12
0
        public void Generate(Builder builder, PythonProject project, List <Project.Configuration> configurations, string projectFile, List <string> generatedFiles, List <string> skipFiles)
        {
            _builder = builder;

            FileInfo fileInfo        = new FileInfo(projectFile);
            string   projectPath     = fileInfo.Directory.FullName;
            string   projectFileName = fileInfo.Name;
            bool     updated;
            string   projectFileResult = Generate(project, configurations, projectPath, projectFileName, out updated);

            if (updated)
            {
                generatedFiles.Add(projectFileResult);
            }
            else
            {
                skipFiles.Add(projectFileResult);
            }

            _builder = null;
        }
Пример #13
0
        private void OnProjectUnloaded(object sender, ProjectEventArgs e)
        {
            if (e.Project == null)
            {
                return;
            }

            if (RemoveTestContainers(e.Project.GetProjectHome()))
            {
                NotifyContainerChanged();
            }

            // Unregister Properties handler
            var pyProj = PythonProject.FromObject(e.Project);

            if (pyProj != null)
            {
                pyProj.ProjectPropertyChanged   -= OnTestPropertiesChanged;
                pyProj.ActiveInterpreterChanged -= OnActiveInterpreterChanged;
            }
        }
Пример #14
0
        public string GetCurrentTest(string filePath, int line, int lineCharOffset)
        {
            var pyProj = PythonProject.FromObject(PathToProject(filePath));

            if (pyProj != null)
            {
                var container = _discoverer.GetTestContainer(pyProj, filePath);
                if (container != null)
                {
                    foreach (var testCase in container.TestCases)
                    {
                        if (testCase.StartLine >= line && line <= testCase.EndLine)
                        {
                            var moduleName = PathUtils.CreateFriendlyFilePath(pyProj.ProjectHome, testCase.Filename);
                            return(moduleName + "::" + testCase.ClassName + "::" + testCase.MethodName);
                        }
                    }
                }
            }

            return(null);
        }
Пример #15
0
        private string Generate(PythonProject project, List <Project.Configuration> unsortedConfigurations, string projectPath, string projectFile, out bool updated)
        {
            var itemGroups = new ItemGroups();

            // Need to sort by name and platform
            List <Project.Configuration> configurations = new List <Project.Configuration>();

            configurations.AddRange(unsortedConfigurations.OrderBy(conf => conf.Name + conf.Platform));
            string sourceRootPath = project.IsSourceFilesCaseSensitive ? Util.GetCapitalizedPath(project.SourceRootPath) : project.SourceRootPath;

            Resolver resolver = new Resolver();

            using (resolver.NewScopedParameter("guid", configurations.First().ProjectGuid))
                using (resolver.NewScopedParameter("projectHome", Util.PathGetRelative(projectPath, sourceRootPath)))
                    using (resolver.NewScopedParameter("startupFile", project.StartupFile))
                        using (resolver.NewScopedParameter("searchPath", project.SearchPaths.JoinStrings(";")))
                        {
                            _project = project;
                            _projectConfigurationList = configurations;

                            DevEnvRange devEnvRange     = new DevEnvRange(unsortedConfigurations);
                            bool        needsPypatching = devEnvRange.MinDevEnv >= DevEnv.vs2017;

                            if (!needsPypatching && (devEnvRange.MinDevEnv != devEnvRange.MaxDevEnv))
                            {
                                Builder.Instance.LogWarningLine("There are mixed devEnvs for one project. VS2017 or higher Visual Studio solutions will require manual updates.");
                            }

                            MemoryStream memoryStream = new MemoryStream();
                            StreamWriter writer       = new StreamWriter(memoryStream);

                            // xml begin header
                            Write(Template.Project.ProjectBegin, writer, resolver);

                            string defaultInterpreterRegisterKeyName = $@"Software\Microsoft\VisualStudio\{
                        devEnvRange.MinDevEnv.GetVisualVersionString()
                    }\PythonTools\Options\Interpreters";

                            var defaultInterpreter        = GetRegistryCurrentUserSubKeyValue(defaultInterpreterRegisterKeyName, "DefaultInterpreter", "{00000000-0000-0000-0000-000000000000}");
                            var defaultInterpreterVersion = GetRegistryCurrentUserSubKeyValue(defaultInterpreterRegisterKeyName, "DefaultInterpreterVersion", "2.7");

                            string currentInterpreterId      = defaultInterpreter;
                            string currentInterpreterVersion = defaultInterpreterVersion;
                            string ptvsTargetsFile           = $@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets";

                            // environments
                            foreach (PythonEnvironment pyEnvironment in _project.Environments)
                            {
                                if (pyEnvironment.IsActivated)
                                {
                                    string interpreterRegisterKeyName =
                                        $@"Software\Microsoft\VisualStudio\{
                                devEnvRange.MinDevEnv.GetVisualVersionString()
                            }\PythonTools\Interpreters\{{{pyEnvironment.Guid}}}";
                                    string interpreterDescription = GetRegistryCurrentUserSubKeyValue(interpreterRegisterKeyName, "Description", "");
                                    if (interpreterDescription != string.Empty)
                                    {
                                        currentInterpreterId      = $"{{{pyEnvironment.Guid}}}";
                                        currentInterpreterVersion = GetRegistryCurrentUserSubKeyValue(interpreterRegisterKeyName, "Version", currentInterpreterVersion);
                                    }
                                }
                            }

                            // virtual environments
                            foreach (PythonVirtualEnvironment virtualEnvironment in _project.VirtualEnvironments)
                            {
                                if (virtualEnvironment.IsDefault)
                                {
                                    string baseInterpreterRegisterKeyName =
                                        $@"Software\Microsoft\VisualStudio\{
                                devEnvRange.MinDevEnv.GetVisualVersionString()
                            }\PythonTools\Interpreters\{{{virtualEnvironment.BaseInterpreterGuid}}}";
                                    string baseInterpreterDescription = GetRegistryCurrentUserSubKeyValue(baseInterpreterRegisterKeyName, "Description", "");
                                    if (baseInterpreterDescription != string.Empty)
                                    {
                                        currentInterpreterId      = $"{{{virtualEnvironment.Guid}}}";
                                        currentInterpreterVersion = GetRegistryCurrentUserSubKeyValue(baseInterpreterRegisterKeyName, "Version", currentInterpreterVersion);
                                    }
                                }
                            }

                            // Project description
                            if (needsPypatching)
                            {
                                currentInterpreterId = $"MSBuild|debug|$(MSBuildProjectFullPath)";
                                ptvsTargetsFile      = FileGeneratorUtilities.RemoveLineTag;
                            }

                            using (resolver.NewScopedParameter("interpreterId", currentInterpreterId))
                                using (resolver.NewScopedParameter("interpreterVersion", currentInterpreterVersion))
                                    using (resolver.NewScopedParameter("ptvsTargetsFile", ptvsTargetsFile))
                                    {
                                        Write(Template.Project.ProjectDescription, writer, resolver);
                                    }

                            GenerateItems(writer, resolver);

                            string baseGuid = FileGeneratorUtilities.RemoveLineTag;

                            foreach (PythonVirtualEnvironment virtualEnvironment in _project.VirtualEnvironments)
                            {
                                baseGuid = needsPypatching ? baseGuid : virtualEnvironment.BaseInterpreterGuid.ToString();
                                string pyVersion = string.IsNullOrEmpty(virtualEnvironment.Version) ? currentInterpreterVersion : virtualEnvironment.Version;

                                Write(Template.Project.ProjectItemGroupBegin, writer, resolver);
                                using (resolver.NewScopedParameter("name", virtualEnvironment.Name))
                                    using (resolver.NewScopedParameter("version", pyVersion))
                                        using (resolver.NewScopedParameter("basePath", virtualEnvironment.Path))
                                            using (resolver.NewScopedParameter("baseGuid", baseGuid))
                                                using (resolver.NewScopedParameter("guid", virtualEnvironment.Guid))
                                                {
                                                    Write(Template.Project.VirtualEnvironmentInterpreter, writer, resolver);
                                                }
                                Write(Template.Project.ProjectItemGroupEnd, writer, resolver);
                            }

                            Write(Template.Project.ProjectItemGroupBegin, writer, resolver);

                            if (_project.Environments.Count > 0)
                            {
                                foreach (PythonEnvironment pyEnvironment in _project.Environments)
                                {
                                    // Verify if the interpreter exists in the register.
                                    string interpreterRegisterKeyName =
                                        $@"Software\Microsoft\VisualStudio\{
                                devEnvRange.MinDevEnv.GetVisualVersionString()
                            }\PythonTools\Interpreters\{{{pyEnvironment.Guid}}}";
                                    string interpreterDescription = GetRegistryCurrentUserSubKeyValue(interpreterRegisterKeyName, "Description", "");
                                    if (interpreterDescription != string.Empty)
                                    {
                                        string interpreterVersion = GetRegistryCurrentUserSubKeyValue(interpreterRegisterKeyName, "Version", currentInterpreterVersion);
                                        using (resolver.NewScopedParameter("guid", $"{{{pyEnvironment.Guid}}}"))
                                            using (resolver.NewScopedParameter("version", interpreterVersion))
                                            {
                                                Write(Template.Project.InterpreterReference, writer, resolver);
                                            }
                                    }
                                }
                            }
                            else if (_project.VirtualEnvironments.Count == 0) // Set the default interpreter
                            {
                                using (resolver.NewScopedParameter("guid", currentInterpreterId))
                                    using (resolver.NewScopedParameter("version", currentInterpreterVersion))
                                    {
                                        Write(Template.Project.InterpreterReference, writer, resolver);
                                    }
                            }
                            Write(Template.Project.ProjectItemGroupEnd, writer, resolver);

                            // configuration general
                            foreach (Project.Configuration conf in _projectConfigurationList)
                            {
                                foreach (var dependencies in new[] { conf.ResolvedPublicDependencies, conf.DotNetPrivateDependencies.Select(x => x.Configuration) })
                                {
                                    foreach (var dependency in dependencies)
                                    {
                                        string relativeToProjectFile = Util.PathGetRelative(sourceRootPath, dependency.ProjectFullFileNameWithExtension);
                                        bool   privateDependency     = project.DependenciesCopyLocal.HasFlag(Project.DependenciesCopyLocalTypes.ProjectReferences);
                                        conf.GetDependencySetting(dependency.Project.GetType());

                                        itemGroups.ProjectReferences.Add(new ItemGroups.ProjectReference
                                        {
                                            Include = relativeToProjectFile,
                                            Name    = dependency.ProjectName,
                                            Private = privateDependency ? "True" : "False",
                                            Project = new Guid(dependency.ProjectGuid)
                                        });
                                    }
                                }
                            }

                            GenerateFolders(writer, resolver);

                            // Import native Python Tools project
                            if (needsPypatching)
                            {
                                Write(Template.Project.ImportPythonTools, writer, resolver);
                            }

                            writer.Write(itemGroups.Resolve(resolver));

                            Write(Template.Project.ProjectEnd, writer, resolver);

                            // Write the project file
                            writer.Flush();

                            // remove all line that contain RemoveLineTag
                            memoryStream = Util.RemoveLineTags(memoryStream, FileGeneratorUtilities.RemoveLineTag);
                            memoryStream.Seek(0, SeekOrigin.Begin);

                            FileInfo projectFileInfo = new FileInfo(projectPath + @"\" + projectFile + ProjectExtension);
                            updated = _builder.Context.WriteGeneratedFile(project.GetType(), projectFileInfo, memoryStream);

                            writer.Close();

                            _project = null;

                            return(projectFileInfo.FullName);
                        }
        }
Пример #16
0
        public void Compile(PythonProject project,
                            FilePath fileName,
                            PythonConfiguration config,
                            BuildResult result)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            else if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            else if (result == null)
            {
                throw new ArgumentNullException("result");
            }
            else if (Runtime == null)
            {
                throw new InvalidOperationException("No supported runtime!");
            }

            // Get our relative path within the project
            if (!fileName.IsChildPathOf(project.BaseDirectory))
            {
                Console.WriteLine("File is not within our project!");
                return;
            }

            FilePath relName = fileName.ToRelative(project.BaseDirectory);
            string   outFile = relName.ToAbsolute(config.OutputDirectory);

            if (!outFile.EndsWith(".py"))
            {
                return;
            }

            // Create the destination directory
            FileInfo fileInfo = new FileInfo(outFile);

            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }

            // Create and start our process to generate the byte code
            Process process = BuildCompileProcess(fileName, outFile, config.Optimize);

            process.Start();
            process.WaitForExit();

            // Parse errors and warnings
            string output = process.StandardError.ReadToEnd();

            // Extract potential Warnings
            foreach (Match m in m_WarningRegex.Matches(output))
            {
                string lineNum = m.Groups[m_WarningRegex.GroupNumberFromName("line")].Value;
                string message = m.Groups[m_WarningRegex.GroupNumberFromName("message")].Value;

                result.AddWarning(fileName, Int32.Parse(lineNum), 0, String.Empty, message);
            }

            // Extract potential SyntaxError
            foreach (Match m in m_ErrorRegex.Matches(output))
            {
                string lineNum = m.Groups[m_ErrorRegex.GroupNumberFromName("line")].Value;
                result.AddError(fileName, Int32.Parse(lineNum), 0, String.Empty, "SyntaxError");
            }
        }
Пример #17
0
        private string Generate(PythonProject project, List <Project.Configuration> unsortedConfigurations, string projectPath, string projectFile, out bool updated)
        {
            var itemGroups = new ItemGroups();

            // Need to sort by name and platform
            List <Project.Configuration> configurations = new List <Project.Configuration>();

            configurations.AddRange(unsortedConfigurations.OrderBy(conf => conf.Name + conf.Platform));
            string sourceRootPath = project.IsSourceFilesCaseSensitive ? Util.GetCapitalizedPath(project.SourceRootPath) : project.SourceRootPath;

            Resolver resolver = new Resolver();

            using (resolver.NewScopedParameter("guid", configurations.First().ProjectGuid))
                using (resolver.NewScopedParameter("projectHome", Util.PathGetRelative(projectPath, sourceRootPath)))
                    using (resolver.NewScopedParameter("startupFile", project.StartupFile))
                        using (resolver.NewScopedParameter("searchPath", project.SearchPaths.JoinStrings(";")))
                        {
                            _project = project;
                            _projectConfigurationList = configurations;

                            DevEnvRange devEnvRange = new DevEnvRange(unsortedConfigurations);

                            MemoryStream memoryStream = new MemoryStream();
                            StreamWriter writer       = new StreamWriter(memoryStream);

                            // xml begin header
                            Write(Template.Project.ProjectBegin, writer, resolver);

                            string defaultInterpreterRegisterKeyName = $@"HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{
                        devEnvRange.MinDevEnv.GetVisualVersionString()
                    }\PythonTools\Options\Interpreters";
                            var    defaultInterpreter        = (string)Registry.GetValue(defaultInterpreterRegisterKeyName, "DefaultInterpreter", "{}") ?? "{00000000-0000-0000-0000-000000000000}";
                            var    defaultInterpreterVersion = (string)Registry.GetValue(defaultInterpreterRegisterKeyName, "DefaultInterpreterVersion", "2.7") ?? "2.7";

                            string currentInterpreterId      = defaultInterpreter;
                            string currentInterpreterVersion = defaultInterpreterVersion;

                            foreach (PythonEnvironment pyEnvironment in _project.Environments)
                            {
                                if (pyEnvironment.IsActivated)
                                {
                                    string interpreterRegisterKeyName =
                                        $@"HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{
                                devEnvRange.MinDevEnv.GetVisualVersionString()
                            }\PythonTools\Interpreters\{{{pyEnvironment.Guid}}}";
                                    string interpreterDescription = (string)Registry.GetValue(interpreterRegisterKeyName, "Description", "");
                                    if (interpreterDescription != string.Empty)
                                    {
                                        currentInterpreterId      = $"{{{pyEnvironment.Guid}}}";
                                        currentInterpreterVersion = (string)Registry.GetValue(interpreterRegisterKeyName, "Version", currentInterpreterVersion);
                                    }
                                }
                            }

                            foreach (PythonVirtualEnvironment virtualEnvironment in _project.VirtualEnvironments)
                            {
                                if (virtualEnvironment.IsDefault)
                                {
                                    string baseInterpreterRegisterKeyName =
                                        $@"HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{
                                devEnvRange.MinDevEnv.GetVisualVersionString()
                            }\PythonTools\Interpreters\{{{virtualEnvironment.BaseInterpreterGuid}}}";
                                    string baseInterpreterDescription = (string)Registry.GetValue(baseInterpreterRegisterKeyName, "Description", "");
                                    if (baseInterpreterDescription != string.Empty)
                                    {
                                        currentInterpreterId      = $"{{{virtualEnvironment.Guid}}}";
                                        currentInterpreterVersion = (string)Registry.GetValue(baseInterpreterRegisterKeyName, "Version", currentInterpreterVersion);
                                    }
                                }
                            }

                            using (resolver.NewScopedParameter("interpreterId", currentInterpreterId))
                                using (resolver.NewScopedParameter("interpreterVersion", currentInterpreterVersion))
                                {
                                    Write(Template.Project.ProjectDescription, writer, resolver);
                                }

                            GenerateItems(writer, resolver);

                            foreach (PythonVirtualEnvironment virtualEnvironment in _project.VirtualEnvironments)
                            {
                                Write(Template.Project.ProjectItemGroupBegin, writer, resolver);
                                using (resolver.NewScopedParameter("name", virtualEnvironment.Name))
                                    using (resolver.NewScopedParameter("version", currentInterpreterVersion))
                                        using (resolver.NewScopedParameter("basePath", virtualEnvironment.Path))
                                            using (resolver.NewScopedParameter("baseGuid", virtualEnvironment.BaseInterpreterGuid))
                                                using (resolver.NewScopedParameter("guid", virtualEnvironment.Guid))
                                                {
                                                    Write(Template.Project.VirtualEnvironmentInterpreter, writer, resolver);
                                                }
                                Write(Template.Project.ProjectItemGroupEnd, writer, resolver);
                            }

                            Write(Template.Project.ProjectItemGroupBegin, writer, resolver);
                            if (_project.Environments.Count > 0)
                            {
                                foreach (PythonEnvironment pyEnvironment in _project.Environments)
                                {
                                    // Verify if the interpreter exists in the register.
                                    string interpreterRegisterKeyName =
                                        $@"HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{
                                devEnvRange.MinDevEnv.GetVisualVersionString()
                            }\PythonTools\Interpreters\{{{pyEnvironment.Guid}}}";
                                    string interpreterDescription = (string)Registry.GetValue(interpreterRegisterKeyName, "Description", "");
                                    if (interpreterDescription != string.Empty)
                                    {
                                        string interpreterVersion = (string)Registry.GetValue(interpreterRegisterKeyName, "Version", currentInterpreterVersion);
                                        using (resolver.NewScopedParameter("guid", $"{{{pyEnvironment.Guid}}}"))
                                            using (resolver.NewScopedParameter("version", interpreterVersion))
                                            {
                                                Write(Template.Project.InterpreterReference, writer, resolver);
                                            }
                                    }
                                }
                            }
                            else if (_project.VirtualEnvironments.Count == 0) // Set the default interpreter
                            {
                                using (resolver.NewScopedParameter("guid", currentInterpreterId))
                                    using (resolver.NewScopedParameter("version", currentInterpreterVersion))
                                    {
                                        Write(Template.Project.InterpreterReference, writer, resolver);
                                    }
                            }
                            Write(Template.Project.ProjectItemGroupEnd, writer, resolver);

                            // configuration general
                            foreach (Project.Configuration conf in _projectConfigurationList)
                            {
                                foreach (var dependencies in new[] { conf.ResolvedPublicDependencies, conf.DotNetPrivateDependencies.Select(x => x.Configuration) })
                                {
                                    foreach (var dependency in dependencies)
                                    {
                                        string relativeToProjectFile = Util.PathGetRelative(sourceRootPath, dependency.ProjectFullFileNameWithExtension);
                                        bool   privateDependency     = project.DependenciesCopyLocal.HasFlag(Project.DependenciesCopyLocalTypes.ProjectReferences);
                                        conf.GetDependencySetting(dependency.Project.GetType());

                                        itemGroups.ProjectReferences.Add(new ItemGroups.ProjectReference
                                        {
                                            Include = relativeToProjectFile,
                                            Name    = dependency.ProjectName,
                                            Private = privateDependency ? "True" : "False",
                                            Project = new Guid(dependency.ProjectGuid)
                                        });
                                    }
                                }
                            }

                            GenerateFolders(writer, resolver);

                            writer.Write(itemGroups.Resolve(resolver));

                            Write(Template.Project.ProjectEnd, writer, resolver);

                            // Write the project file
                            writer.Flush();

                            // remove all line that contain RemoveLineTag
                            memoryStream.Seek(0, SeekOrigin.Begin);

                            FileInfo projectFileInfo = new FileInfo(projectPath + @"\" + projectFile + ProjectExtension);
                            updated = _builder.Context.WriteGeneratedFile(project.GetType(), projectFileInfo, memoryStream);

                            writer.Close();

                            _project = null;

                            return(projectFileInfo.FullName);
                        }
        }
Пример #18
0
        public void IsTestProjectReturnsFalseForNullPythonProject()
        {
            PythonProject project = null;

            Assert.IsFalse(testFramework.IsTestProject(project));
        }
Пример #19
0
 public void Generate(Builder builder, PythonProject project, List <Project.Configuration> configurations, string projectFile, List <string> generatedFiles,
                      List <string> skipFiles)
 {
     PyprojGenerator.Generate(builder, project, configurations, projectFile, generatedFiles, skipFiles);
 }
Пример #20
0
        internal bool IsProjectKnown(IVsProject project)
        {
            var pyProj = PythonProject.FromObject(project);

            return(pyProj != null && _projectInfo.ContainsKey(pyProj));
        }