public void ImportWizardInterpreter() { using (var wpf = new WpfProxy()) { var settings = wpf.Create(() => new ImportSettings(null, null)); settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\"); settings.Filters = "*.py;*.pyproj"; var interpreter = new PythonInterpreterView("Test", "Test|Blah", null); settings.Dispatcher.Invoke((Action)(() => settings.AvailableInterpreters.Add(interpreter))); //settings.AddAvailableInterpreter(interpreter); settings.SelectedInterpreter = interpreter; settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj"); string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); Assert.AreEqual(interpreter.Id, proj.Descendant("InterpreterId").Value); var interp = proj.Descendant("InterpreterReference"); Assert.AreEqual(string.Format("{0}", interpreter.Id), interp.Attribute("Include").Value); } }
public async Task <string> CreateRequestedProjectAsync() { await UpdateSourcePathAsync().HandleAllExceptions(_site); string projectPath = ProjectPath; string sourcePath = SourcePath; string filters = Filters; string searchPaths = string.Join(";", (SearchPaths ?? "").Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(p => PathUtils.GetRelativeDirectoryPath(SourcePath, p))); string startupFile = StartupFile; PythonInterpreterView selectedInterpreter = SelectedInterpreter; ProjectCustomization projectCustomization = UseCustomization ? Customization : null; bool detectVirtualEnv = DetectVirtualEnv; return(await Task.Run(() => { bool success = false; try { Directory.CreateDirectory(Path.GetDirectoryName(projectPath)); using (var writer = new StreamWriter(projectPath, false, Encoding.UTF8)) { WriteProjectXml( _service, writer, projectPath, sourcePath, filters, searchPaths, startupFile, selectedInterpreter, projectCustomization, detectVirtualEnv ); } success = true; return projectPath; } finally { if (!success) { try { File.Delete(projectPath); } catch { // Try and avoid leaving stray files, but it does // not matter much if we do. } } } })); }
public StandaloneTargetView(IServiceProvider serviceProvider) { var componentService = serviceProvider.GetComponentModel(); var interpreterProviders = componentService.DefaultExportProvider.GetExports <IPythonInterpreterFactoryProvider, Dictionary <string, object> >(); var interpreterOptions = componentService.GetService <IInterpreterOptionsService>(); var registry = componentService.GetService <IInterpreterRegistryService>(); var pythonService = serviceProvider.GetPythonToolsService(); var availableInterpreters = registry.Configurations.Select( config => new PythonInterpreterView( config.Description, config.Id, config.InterpreterPath ) ).ToList(); _customInterpreter = new PythonInterpreterView(Strings.LaunchProfiling_OtherInterpreter, "", null); availableInterpreters.Add(_customInterpreter); _availableInterpreters = new ReadOnlyCollection <PythonInterpreterView>(availableInterpreters); _interpreterPath = null; _canSpecifyInterpreterPath = false; _scriptPath = null; _workingDirectory = null; _arguments = null; _isValid = false; PropertyChanged += new PropertyChangedEventHandler(StandaloneTargetView_PropertyChanged); if (IsAnyAvailableInterpreters) { var defaultId = interpreterOptions.DefaultInterpreterId; Interpreter = AvailableInterpreters.FirstOrDefault(v => v.Id == defaultId); } }
internal static void WriteProjectXml( IInterpreterRegistryService service, TextWriter writer, string projectPath, string sourcePath, string filters, string searchPaths, string startupFile, PythonInterpreterView selectedInterpreter, ProjectCustomization customization, bool detectVirtualEnv ) { var projectHome = PathUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath); var project = ProjectRootElement.Create(); project.DefaultTargets = "Build"; project.ToolsVersion = "4.0"; var globals = project.AddPropertyGroup(); globals.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' "; globals.AddProperty("SchemaVersion", "2.0"); globals.AddProperty("ProjectGuid", Guid.NewGuid().ToString("B")); globals.AddProperty("ProjectHome", projectHome); if (PathUtils.IsValidPath(startupFile)) { globals.AddProperty("StartupFile", startupFile); } else { globals.AddProperty("StartupFile", ""); } globals.AddProperty("SearchPath", searchPaths); globals.AddProperty("WorkingDirectory", "."); globals.AddProperty("OutputPath", "."); globals.AddProperty("ProjectTypeGuids", "{888888a0-9f3d-457c-b088-3a5042f75d52}"); globals.AddProperty("LaunchProvider", DefaultLauncherProvider.DefaultLauncherName); var interpreterId = globals.AddProperty(PythonConstants.InterpreterId, ""); if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) { interpreterId.Value = selectedInterpreter.Id; } // VS requires property groups with conditions for Debug // and Release configurations or many COMExceptions are // thrown. var debugGroup = project.AddPropertyGroup(); var releaseGroup = project.AddPropertyGroup(); debugGroup.Condition = "'$(Configuration)' == 'Debug'"; releaseGroup.Condition = "'$(Configuration)' == 'Release'"; var folders = new HashSet <string>(); var virtualEnvPaths = detectVirtualEnv ? new List <string>() : null; foreach (var unescapedFile in EnumerateAllFiles(sourcePath, filters, virtualEnvPaths)) { var file = ProjectCollection.Escape(unescapedFile); var ext = Path.GetExtension(file); var fileType = "Content"; if (PythonConstants.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase) || PythonConstants.WindowsFileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { fileType = "Compile"; } folders.Add(Path.GetDirectoryName(file)); project.AddItem(fileType, file); } foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) { project.AddItem("Folder", folder); } if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) { project.AddItem( MSBuildConstants.InterpreterReferenceItem, selectedInterpreter.Id ); } if (virtualEnvPaths != null && virtualEnvPaths.Any() && service != null) { foreach (var path in virtualEnvPaths) { var shortId = PathUtils.GetFileOrDirectoryName(path); var longId = MSBuildProjectInterpreterFactoryProvider.GetInterpreterId("$(MSBuildProjectFullPath)", shortId); var config = VirtualEnv.FindInterpreterConfiguration(longId, path, service); if (config != null) { AddVirtualEnvironment(project, sourcePath, shortId, config); if (string.IsNullOrEmpty(interpreterId.Value)) { interpreterId.Value = longId; } } } } var imports = project.AddPropertyGroup(); imports.AddProperty("VisualStudioVersion", "10.0").Condition = " '$(VisualStudioVersion)' == '' "; (customization ?? DefaultProjectCustomization.Instance).Process( sourcePath, project, new Dictionary <string, ProjectPropertyGroupElement> { { "Globals", globals }, { "Imports", imports }, { "Debug", debugGroup }, { "Release", releaseGroup } } ); project.Save(writer); }
internal static void WriteProjectXml( IInterpreterOptionsService service, TextWriter writer, string projectPath, string sourcePath, string filters, string searchPaths, string startupFile, PythonInterpreterView selectedInterpreter, ProjectCustomization customization, bool detectVirtualEnv ) { var projectHome = CommonUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath); var project = ProjectRootElement.Create(); project.DefaultTargets = "Build"; project.ToolsVersion = "4.0"; var globals = project.AddPropertyGroup(); globals.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' "; globals.AddProperty("SchemaVersion", "2.0"); globals.AddProperty("ProjectGuid", Guid.NewGuid().ToString("B")); globals.AddProperty("ProjectHome", projectHome); if (CommonUtils.IsValidPath(startupFile)) { globals.AddProperty("StartupFile", startupFile); } else { globals.AddProperty("StartupFile", ""); } globals.AddProperty("SearchPath", searchPaths); globals.AddProperty("WorkingDirectory", "."); globals.AddProperty("OutputPath", "."); globals.AddProperty("ProjectTypeGuids", "{888888a0-9f3d-457c-b088-3a5042f75d52}"); globals.AddProperty("LaunchProvider", DefaultLauncherProvider.DefaultLauncherName); var interpreterId = globals.AddProperty(PythonConstants.InterpreterId, ""); var interpreterVersion = globals.AddProperty(PythonConstants.InterpreterVersion, ""); if (selectedInterpreter != null && selectedInterpreter.Id != Guid.Empty) { interpreterId.Value = selectedInterpreter.Id.ToString("B"); interpreterVersion.Value = selectedInterpreter.Version.ToString(); } // VS requires property groups with conditions for Debug // and Release configurations or many COMExceptions are // thrown. var debugGroup = project.AddPropertyGroup(); var releaseGroup = project.AddPropertyGroup(); debugGroup.Condition = "'$(Configuration)' == 'Debug'"; releaseGroup.Condition = "'$(Configuration)' == 'Release'"; var folders = new HashSet<string>(); var virtualEnvPaths = detectVirtualEnv ? new List<string>() : null; foreach (var unescapedFile in EnumerateAllFiles(sourcePath, filters, virtualEnvPaths)) { var file = ProjectCollection.Escape(unescapedFile); var ext = Path.GetExtension(file); var fileType = "Content"; if (PythonConstants.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase) || PythonConstants.WindowsFileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { fileType = "Compile"; } folders.Add(Path.GetDirectoryName(file)); project.AddItem(fileType, file); } foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) { project.AddItem("Folder", folder); } if (selectedInterpreter != null && selectedInterpreter.Id != Guid.Empty) { project.AddItem( MSBuildProjectInterpreterFactoryProvider.InterpreterReferenceItem, string.Format("{0:B}\\{1}", selectedInterpreter.Id, selectedInterpreter.Version) ); } if (virtualEnvPaths != null && virtualEnvPaths.Any() && service != null) { foreach (var options in virtualEnvPaths.Select(p => VirtualEnv.FindInterpreterOptions(p, service))) { AddVirtualEnvironment(project, sourcePath, options); if (string.IsNullOrEmpty(interpreterId.Value)) { interpreterId.Value = options.IdString; interpreterVersion.Value = options.LanguageVersionString; } } } var imports = project.AddPropertyGroup(); imports.AddProperty("VisualStudioVersion", "10.0").Condition = " '$(VisualStudioVersion)' == '' "; (customization ?? DefaultProjectCustomization.Instance).Process( project, new Dictionary<string, ProjectPropertyGroupElement> { { "Globals", globals }, { "Imports", imports }, { "Debug", debugGroup }, { "Release", releaseGroup } } ); project.Save(writer); }
private void ImportWizardVirtualEnvWorker( PythonVersion python, string venvModuleName, string expectedFile, bool brokenBaseInterpreter ) { var mockService = new MockInterpreterOptionsService(); mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider", new MockPythonInterpreterFactory(python.Configuration) )); using (var wpf = new WpfProxy()) { var settings = wpf.Create(() => new ImportSettings(null, mockService)); var sourcePath = TestData.GetTempPath(); // Create a fake set of files to import File.WriteAllText(Path.Combine(sourcePath, "main.py"), ""); Directory.CreateDirectory(Path.Combine(sourcePath, "A")); File.WriteAllText(Path.Combine(sourcePath, "A", "__init__.py"), ""); // Create a real virtualenv environment to import using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", venvModuleName, Path.Combine(sourcePath, "env"))) { Console.WriteLine(p.Arguments); p.Wait(); Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines))); Assert.AreEqual(0, p.ExitCode); } if (brokenBaseInterpreter) { var cfgPath = Path.Combine(sourcePath, "env", "Lib", "orig-prefix.txt"); if (File.Exists(cfgPath)) { File.WriteAllText(cfgPath, string.Format("C:\\{0:N}", Guid.NewGuid())); } else if (File.Exists((cfgPath = Path.Combine(sourcePath, "env", "pyvenv.cfg")))) { File.WriteAllLines(cfgPath, File.ReadAllLines(cfgPath) .Select(line => { if (line.StartsWith("home = ")) { return(string.Format("home = C:\\{0:N}", Guid.NewGuid())); } return(line); }) ); } } Console.WriteLine("All files:"); foreach (var f in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)) { Console.WriteLine(PathUtils.GetRelativeFilePath(sourcePath, f)); } Assert.IsTrue( File.Exists(Path.Combine(sourcePath, "env", expectedFile)), "Virtualenv was not created correctly" ); if (!brokenBaseInterpreter) { var interpreter = new PythonInterpreterView($"Test{venvModuleName}", "TestEnv", Path.Combine(sourcePath, "env")); settings.Dispatcher.Invoke((Action)(() => settings.AvailableInterpreters.Add(interpreter))); settings.SelectedInterpreter = interpreter; } settings.DetectVirtualEnv = true; settings.SourcePath = sourcePath; string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); // Does not include any .py files from the virtualenv AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value), "main.py", "A\\__init__.py" ); // Does not contain 'env' AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value), "A" ); var env = proj.Descendants(proj.GetName("Interpreter")).SingleOrDefault(); if (brokenBaseInterpreter) { Assert.IsNull(env); } else { Assert.AreEqual("env\\", env.Attribute("Include").Value); Assert.AreNotEqual("", env.Descendant("Id").Value); Assert.AreEqual(string.Format("env ({0})", python.Configuration.Description), env.Descendant("Description").Value); Assert.AreEqual("scripts\\python.exe", env.Descendant("InterpreterPath").Value, true); Assert.AreEqual("scripts\\pythonw.exe", env.Descendant("WindowsInterpreterPath").Value, true); Assert.AreEqual("PYTHONPATH", env.Descendant("PathEnvironmentVariable").Value, true); Assert.AreEqual(python.Configuration.Version.ToString(), env.Descendant("Version").Value, true); Assert.AreEqual(python.Configuration.Architecture.ToString("X"), env.Descendant("Architecture").Value, true); } } }