示例#1
0
        public void LaunchWebBrowserUriTests() {
            var testCases = new[] {
                new { Url = "/fob", Port = 1, Expected = "http://localhost:1/fob" },
                new { Url = "http://localhost:9999/fob", Port = 9999, Expected = "http://localhost:9999/fob" },
                new { Url = "http://localhost/fob", Port = 9999, Expected = "http://localhost:9999/fob" },
                new { Url = "fob", Port = 9999, Expected = "http://localhost:9999/fob" },
                new { Url = "/hello/world", Port = 367, Expected = "http://localhost:367/hello/world" },
                new { Url = "/fob", Port = -1, Expected = "http://localhost:{port}/fob" },
            };

            foreach (var testCase in testCases) {
                Console.WriteLine("{0} {1} == {2}", testCase.Url, testCase.Port, testCase.Expected);

                Uri url;
                int port;

                var config = new LaunchConfiguration(null, new Dictionary<string, string> {
                    { PythonConstants.WebBrowserUrlSetting, testCase.Url }
                });
                if (testCase.Port >= 0) {
                    config.LaunchOptions[PythonConstants.WebBrowserPortSetting] = testCase.Port.ToString();
                }
                PythonWebLauncher.GetFullUrl(null, config, out url, out port);
                Assert.AreEqual(
                    testCase.Expected.Replace("{port}", port.ToString()),
                    url.AbsoluteUri
                );
            }
        }
示例#2
0
        public static Dictionary <string, string> GetFullEnvironment(LaunchConfiguration config, IServiceProvider serviceProvider)
        {
            if (config.Interpreter == null)
            {
                throw new ArgumentNullException(nameof(Interpreter));
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }


            // Start with global environment, add configured environment,
            // then add search paths.
            var baseEnv = System.Environment.GetEnvironmentVariables();
            // Clear search paths from the global environment. The launch
            // configuration should include the existing value

            var pathVar = config.Interpreter?.PathEnvironmentVariable;

            if (string.IsNullOrEmpty(pathVar))
            {
                pathVar = "PYTHONPATH";
            }
            baseEnv[pathVar] = string.Empty;

            if (CondaUtils.IsCondaEnvironment(config.Interpreter.GetPrefixPath()))
            {
                var condaExe   = CondaUtils.GetRootCondaExecutablePath(serviceProvider);
                var prefixPath = config.Interpreter.GetPrefixPath();
                if (File.Exists(condaExe) && Directory.Exists(prefixPath))
                {
                    var condaEnv = ThreadHelper.JoinableTaskFactory.Run(() => CondaUtils.GetActivationEnvironmentVariablesForPrefixAsync(condaExe, prefixPath));
                    baseEnv = PathUtils.MergeEnvironments(baseEnv.AsEnumerable <string, string>(), condaEnv, "Path", pathVar);
                }
            }

            var env = PathUtils.MergeEnvironments(
                baseEnv.AsEnumerable <string, string>(),
                config.GetEnvironmentVariables(),
                "Path", pathVar
                );

            if (config.SearchPaths != null && config.SearchPaths.Any())
            {
                env = PathUtils.MergeEnvironments(
                    env,
                    new[] {
                    new KeyValuePair <string, string>(
                        pathVar,
                        PathUtils.JoinPathList(config.SearchPaths)
                        )
                },
                    pathVar
                    );
            }
            return(env);
        }
示例#3
0
        private int Launch(LaunchConfiguration config, bool debug) {

            //if (factory.Id == _cpyInterpreterGuid || factory.Id == _cpy64InterpreterGuid) {
            //    MessageBox.Show(
            //        "The project is currently set to use the .NET debugger for IronPython debugging but the project is configured to start with a CPython interpreter.\r\n\r\nTo fix this change the debugger type in project properties->Debug->Launch mode.\r\nIf IronPython is not an available interpreter you may need to download it from http://ironpython.codeplex.com.",
            //        "Visual Studio");
            //    return VSConstants.S_OK;
            //}

            string extension = Path.GetExtension(config.ScriptName);
            if (string.Equals(extension, ".html", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(extension, ".htm", StringComparison.OrdinalIgnoreCase)) {
                try {
                    StartSilverlightApp(config, debug);
                } catch (ChironNotFoundException ex) {
                    MessageBox.Show(ex.Message, "Visual Studio");
                }
                return VSConstants.S_OK;
            }

            try {
                if (debug) {
                    if (string.IsNullOrEmpty(config.InterpreterArguments)) {
                        config.InterpreterArguments = "-X:Debug";
                    } else if (config.InterpreterArguments.IndexOf("-X:Debug", StringComparison.InvariantCultureIgnoreCase) < 0) {
                        config.InterpreterArguments = "-X:Debug " + config.InterpreterArguments;
                    }

                    var debugStdLib = _project.GetProperty(IronPythonLauncherOptions.DebugStandardLibrarySetting);
                    bool debugStdLibResult;
                    if (!bool.TryParse(debugStdLib, out debugStdLibResult) || !debugStdLibResult) {
                        string interpDir = config.Interpreter.PrefixPath;
                        config.InterpreterArguments += " -X:NoDebug \"" + System.Text.RegularExpressions.Regex.Escape(Path.Combine(interpDir, "Lib\\")) + ".*\"";
                    }

                    using (var dti = DebugLaunchHelper.CreateDebugTargetInfo(_serviceProvider, config)) {
                        // Set the CLR debugger
                        dti.Info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
                        dti.Info.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd;

                        // Clear the CLSID list while launching, then restore it
                        // so Dispose() can free it.
                        var clsidList = dti.Info.pClsidList;
                        dti.Info.pClsidList = IntPtr.Zero;
                        try {
                            dti.Launch();
                        } finally {
                            dti.Info.pClsidList = clsidList;
                        }
                    }
                } else {
                    var psi = DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config);
                    Process.Start(psi).Dispose();
                }
            } catch (FileNotFoundException) {
            }
            return VSConstants.S_OK;
        }
示例#4
0
        private int Launch(LaunchConfiguration config, bool debug) {
            if (debug) {
                StartWithDebugger(config);
            } else {
                StartWithoutDebugger(config).Dispose();
            }

            return VSConstants.S_OK;
        }
示例#5
0
        /// <summary>
        /// Default implementation of the "Start Debugging" command.
        /// </summary>
        private void StartWithDebugger(LaunchConfiguration config) {
            _serviceProvider.GetPythonToolsService().Logger.LogEvent(Logging.PythonLogEvent.Launch, 1);

            // Historically, we would clear out config.InterpreterArguments at
            // this stage if doing mixed-mode debugging. However, there doesn't
            // seem to be any need to do this, so we now leave them alone.

            using (var dbgInfo = DebugLaunchHelper.CreateDebugTargetInfo(_serviceProvider, config)) {
                dbgInfo.Launch();
            }
        }
示例#6
0
 /// <summary>
 /// Default implementation of the "Start without Debugging" command.
 /// </summary>
 private Process StartWithoutDebugger(LaunchConfiguration config) {
     try {
         _serviceProvider.GetPythonToolsService().Logger.LogEvent(Logging.PythonLogEvent.Launch, new Logging.LaunchInfo {
             IsDebug = false,
             Version = config.Interpreter?.Version.ToString() ?? ""
         });
     } catch (Exception ex) {
         Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
     }
     return Process.Start(DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config));
 }
示例#7
0
 public PythonWebLauncher(
     IServiceProvider serviceProvider,
     LaunchConfiguration runConfig,
     LaunchConfiguration debugConfig,
     LaunchConfiguration defaultConfig
 ) {
     _serviceProvider = serviceProvider;
     _pyService = _serviceProvider.GetPythonToolsService();
     _runConfig = runConfig;
     _debugConfig = debugConfig;
     _defaultConfig = defaultConfig;
 }
示例#8
0
        private static IEnumerable<string> GetLaunchConfigurationOptions(LaunchConfiguration config) {
            yield return string.Format("{0}={1}", AD7Engine.VersionSetting, config.Interpreter.Version);
            yield return string.Format("{0}={1}",
                AD7Engine.InterpreterOptions,
                config.InterpreterArguments ?? string.Empty
            );
            var url = config.GetLaunchOption(PythonConstants.WebBrowserUrlSetting);
            if (!string.IsNullOrWhiteSpace(url)) {
                yield return string.Format("{0}={1}", AD7Engine.WebBrowserUrl, HttpUtility.UrlEncode(url));
            }

            if (config.GetLaunchOption("DjangoDebug").IsTrue()) {
                yield return AD7Engine.EnableDjangoDebugging + "=True";
            }
        }
        private static LaunchConfiguration GetMSBuildCommandConfig(
            LaunchConfiguration original,
            IPythonProject project,
            string targetProperty,
            string targetTypeProperty,
            string argumentsProperty,
            string environmentProperty
        ) {
            var target = DoSubstitutions(original, project, project.GetProperty(targetProperty));
            if (string.IsNullOrEmpty(target)) {
                target = original.ScriptName;
            }

            var targetType = project.GetProperty(targetTypeProperty);
            if (string.IsNullOrEmpty(targetType)) {
                targetType = PythonCommandTask.TargetTypeScript;
            }

            var config = original.Clone();
            if (PythonCommandTask.TargetTypeModule.Equals(targetType, StringComparison.OrdinalIgnoreCase)) {
                if (string.IsNullOrEmpty(config.InterpreterArguments)) {
                    config.InterpreterArguments = "-m " + target;
                } else {
                    config.InterpreterArguments = config.InterpreterArguments + " -m " + target;
                }
            } else if (PythonCommandTask.TargetTypeExecutable.Equals(targetType, StringComparison.OrdinalIgnoreCase)) {
                config.InterpreterPath = target;
            } else {
                config.ScriptName = target;
            }

            var args = DoSubstitutions(original, project, project.GetProperty(argumentsProperty));
            if (!string.IsNullOrEmpty(args)) {
                if (string.IsNullOrEmpty(config.ScriptArguments)) {
                    config.ScriptArguments = args;
                } else {
                    config.ScriptArguments = config.ScriptArguments + " " + args;
                }
            }

            var env = DoSubstitutions(original, project, project.GetProperty(environmentProperty));
            config.Environment = PathUtils.MergeEnvironments(config.Environment, PathUtils.ParseEnvironment(env));

            return config;
        }
示例#10
0
        internal static string DoSubstitutions(LaunchConfiguration original, IPythonProject project, string str) {
            if (string.IsNullOrEmpty(str)) {
                return str;
            }

            return SubstitutionPattern.Replace(
                str,
                m => {
                    switch (m.Groups[1].Value.ToLowerInvariant()) {
                        case "startupfile":
                            return original.ScriptName;
                        case "startupmodule":
                            try {
                                return ModulePath.FromFullPath(original.ScriptName, project.ProjectHome).ModuleName;
                            } catch (ArgumentException) {
                            }
                            break;
                    }
                    return m.Value;
                }
            );
        }
示例#11
0
        private void GetFullUrl(LaunchConfiguration config, out Uri uri, out int port)
        {
            int p;
            if (!int.TryParse(config.GetLaunchOption(PythonConstants.WebBrowserPortSetting) ?? "", out p)) {
                p = TestServerPort;
            }
            port = p;

            var host = config.GetLaunchOption(PythonConstants.WebBrowserUrlSetting);
            if (string.IsNullOrEmpty(host)) {
                uri = null;
                return;
            }
            try {
                uri = GetFullUrl(host, p);
            } catch (UriFormatException) {
                var output = OutputWindowRedirector.GetGeneral(_serviceProvider);
                output.WriteErrorLine(Strings.ErrorInvalidLaunchUrl.FormatUI(host));
                output.ShowAndActivate();
                uri = null;
            }
        }
示例#12
0
        public override async void DoCommand(object sender, EventArgs e) {
            var pyProj = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
            var textView = CommonPackage.GetActiveTextView(_serviceProvider);

            var config = pyProj?.GetLaunchConfigurationOrThrow();
            if (config == null && textView != null) {
                var pyService = _serviceProvider.GetPythonToolsService();
                config = new LaunchConfiguration(pyService.DefaultInterpreterConfiguration) {
                    ScriptName = textView.GetFilePath(),
                    WorkingDirectory = PathUtils.GetParent(textView.GetFilePath())
                };
            }
            if (config == null) {
                Debug.Fail("Should not be executing command when it is invisible");
                return;
            }

            var window = EnsureReplWindow(_serviceProvider, config.Interpreter, pyProj);
            window.Show(true);

            var eval = (IPythonInteractiveEvaluator)window.InteractiveWindow.Evaluator;

            // The interpreter may take some time to startup, do this off the UI thread.
            await ThreadHelper.JoinableTaskFactory.RunAsync(async () => {
                await ((IInteractiveEvaluator)eval).ResetAsync();

                window.InteractiveWindow.WriteLine(string.Format("Running {0}", config.ScriptName));

                await eval.ExecuteFileAsync(config.ScriptName, config.ScriptArguments);
            });
        }
示例#13
0
 public DefaultPythonLauncher(IServiceProvider serviceProvider, LaunchConfiguration config) {
     _serviceProvider = serviceProvider;
     _config = config;
 }
示例#14
0
        public static ProcessStartInfo CreateProcessStartInfo(IServiceProvider provider, LaunchConfiguration config)
        {
            var psi = new ProcessStartInfo {
                FileName = config.GetInterpreterPath(),
                Arguments = string.Join(" ", new[] {
                    config.InterpreterArguments,
                    ProcessOutput.QuoteSingleArgument(config.ScriptName),
                    config.ScriptArguments
                }.Where(s => !string.IsNullOrEmpty(s))),
                WorkingDirectory = config.WorkingDirectory,
                UseShellExecute = false
            };

            if (string.IsNullOrEmpty(psi.FileName)) {
                throw new FileNotFoundException(Strings.DebugLaunchInterpreterMissing);
            }
            if (!File.Exists(psi.FileName)) {
                throw new FileNotFoundException(Strings.DebugLaunchInterpreterMissing_Path.FormatUI(psi.FileName));
            }
            if (string.IsNullOrEmpty(psi.WorkingDirectory)) {
                psi.WorkingDirectory = PathUtils.GetParent(config.ScriptName);
            }
            if (string.IsNullOrEmpty(psi.WorkingDirectory)) {
                throw new DirectoryNotFoundException(Strings.DebugLaunchWorkingDirectoryMissing);
            }
            if (!Directory.Exists(psi.WorkingDirectory)) {
                throw new DirectoryNotFoundException(Strings.DebugLaunchWorkingDirectoryMissing_Path.FormatUI(psi.FileName));
            }

            foreach (var kv in provider.GetPythonToolsService().GetFullEnvironment(config)) {
                psi.Environment[kv.Key] = kv.Value;
            }

            var pyService = provider.GetPythonToolsService();
            // Pause if the user has requested it.
            string pauseCommand = null;
            if (pyService.DebuggerOptions.WaitOnAbnormalExit && pyService.DebuggerOptions.WaitOnNormalExit) {
                pauseCommand = "pause";
            } else if (pyService.DebuggerOptions.WaitOnAbnormalExit && !pyService.DebuggerOptions.WaitOnNormalExit) {
                pauseCommand = "if errorlevel 1 pause";
            } else if (pyService.DebuggerOptions.WaitOnNormalExit && !pyService.DebuggerOptions.WaitOnAbnormalExit) {
                pauseCommand = "if not errorlevel 1 pause";
            }

            if (!string.IsNullOrEmpty(pauseCommand)) {
                psi.Arguments = string.Format("/c \"{0} {1}\" & {2}",
                    ProcessOutput.QuoteSingleArgument(psi.FileName),
                    psi.Arguments,
                    pauseCommand
                );
                psi.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
            }

            return psi;
        }
示例#15
0
        public static unsafe DebugTargetInfo CreateDebugTargetInfo(IServiceProvider provider, LaunchConfiguration config)
        {
            var pyService = provider.GetPythonToolsService();
            var dti = new DebugTargetInfo(provider);

            try {
                dti.Info.dlo = DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
                dti.Info.bstrExe = config.GetInterpreterPath();
                dti.Info.bstrCurDir = config.WorkingDirectory;
                if (string.IsNullOrEmpty(dti.Info.bstrCurDir)) {
                    dti.Info.bstrCurDir = PathUtils.GetParent(config.ScriptName);
                }

                dti.Info.bstrRemoteMachine = null;
                dti.Info.fSendStdoutToOutputWindow = 0;

                bool nativeDebug = config.GetLaunchOption(PythonConstants.EnableNativeCodeDebugging).IsTrue();
                if (!nativeDebug) {
                    dti.Info.bstrOptions = string.Join(";",
                        GetGlobalDebuggerOptions(pyService)
                            .Concat(GetLaunchConfigurationOptions(config))
                            .Where(s => !string.IsNullOrEmpty(s))
                            .Select(s => s.Replace(";", ";;"))
                    );
                }

                // Environment variables should be passed as a
                // null-terminated block of null-terminated strings.
                // Each string is in the following form:name=value\0
                var buf = new StringBuilder();
                foreach (var kv in provider.GetPythonToolsService().GetFullEnvironment(config)) {
                    buf.AppendFormat("{0}={1}\0", kv.Key, kv.Value);
                }
                if (buf.Length > 0) {
                    buf.Append("\0");
                    dti.Info.bstrEnv = buf.ToString();
                }

                var args = string.Join(" ", new[] {
                    config.InterpreterArguments,
                    ProcessOutput.QuoteSingleArgument(config.ScriptName),
                    config.ScriptArguments
                }.Where(s => !string.IsNullOrEmpty(s)));

                if (config.Environment != null) {
                    args = DoSubstitutions(config.Environment, args);
                }
                dti.Info.bstrArg = args;

                if (nativeDebug) {
                    dti.Info.dwClsidCount = 2;
                    dti.Info.pClsidList = Marshal.AllocCoTaskMem(sizeof(Guid) * 2);
                    var engineGuids = (Guid*)dti.Info.pClsidList;
                    engineGuids[0] = dti.Info.clsidCustom = DkmEngineId.NativeEng;
                    engineGuids[1] = AD7Engine.DebugEngineGuid;
                } else {
                    // Set the Python debugger
                    dti.Info.clsidCustom = new Guid(AD7Engine.DebugEngineId);
                    dti.Info.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd;
                }

                // Null out dti so that it is not disposed before we return.
                var result = dti;
                dti = null;
                return result;
            } finally {
                if (dti != null) {
                    dti.Dispose();
                }
            }
        }
示例#16
0
        public void StartSilverlightApp(LaunchConfiguration config, bool debug) {
            var root = Path.GetFullPath(config.WorkingDirectory).TrimEnd('\\');
            var file = Path.Combine(root, config.ScriptName);
            int port = EnsureChiron(root);
            var url = string.Format(
                "http://localhost:{0}/{1}",
                port,
                (file.StartsWith(root + "\\") ? file.Substring(root.Length + 1) : file.TrimStart('\\')).Replace('\\', '/')
            );

            StartInBrowser(url, debug ? guidSilverlightDebug : null);
        }
示例#17
0
 private static Dictionary<string, string> GetEnvironment(IServiceProvider provider, LaunchConfiguration config) {
     // Start with global environment, add configured environment,
     // then add search paths.
     var baseEnv = Environment.GetEnvironmentVariables();
     if (provider.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath) {
         // Clear search paths from the global environment
         baseEnv[config.Interpreter.PathEnvironmentVariable] = string.Empty;
     }
     var env = PathUtils.MergeEnvironments(
         baseEnv.AsEnumerable<string, string>(),
         config.GetEnvironmentVariables(),
         "Path", config.Interpreter.PathEnvironmentVariable
     );
     env = PathUtils.MergeEnvironments(
         env,
         new[] { new KeyValuePair<string, string>(
                 config.Interpreter.PathEnvironmentVariable,
                 PathUtils.JoinPathList(config.SearchPaths)
             ) },
         config.Interpreter.PathEnvironmentVariable
     );
     return env;
 }
示例#18
0
        private void StartInterpreter_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var view = (EnvironmentView)e.Parameter;

            var config = new LaunchConfiguration(view.Factory.Configuration) {
                PreferWindowedInterpreter = (e.Command == EnvironmentPathsExtension.StartWindowsInterpreter),
                WorkingDirectory = view.Factory.Configuration.PrefixPath,
                SearchPaths = new List<string>()
            };

            var sln = (IVsSolution)_site.GetService(typeof(SVsSolution));
            foreach (var pyProj in sln.EnumerateLoadedPythonProjects()) {
                if (pyProj.InterpreterConfigurations.Contains(config.Interpreter)) {
                    config.SearchPaths.AddRange(pyProj.GetSearchPaths());
                }
            }

            Process.Start(DebugLaunchHelper.CreateProcessStartInfo(_site, config)).Dispose();
        }
示例#19
0
 /// <summary>
 /// Default implementation of the "Start without Debugging" command.
 /// </summary>
 private Process StartWithoutDebugger(LaunchConfiguration config) {
     _serviceProvider.GetPythonToolsService().Logger.LogEvent(Logging.PythonLogEvent.Launch, 0);
     return Process.Start(DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config));
 }
示例#20
0
        internal void AddPropertiesAfter(LaunchConfiguration config) {
            AddArgumentAtEnd(config.ScriptArguments);
            WorkingDirectory = ChooseFirst(WorkingDirectory, config.WorkingDirectory);

            EnvironmentVariables = PathUtils.MergeEnvironments(
                EnvironmentVariables.MaybeEnumerate(),
                config.Environment.MaybeEnumerate(),
                "PATH", config.Interpreter.PathEnvironmentVariable
            );
        }
示例#21
0
        /// <summary>
        /// Default implementation of the "Start Debugging" command.
        /// </summary>
        private void StartWithDebugger(LaunchConfiguration config) {
            try {
                _serviceProvider.GetPythonToolsService().Logger.LogEvent(Logging.PythonLogEvent.Launch, new Logging.LaunchInfo {
                    IsDebug = true,
                    Version = config.Interpreter?.Version.ToString() ?? ""
                });
            } catch (Exception ex) {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
            }

            // Historically, we would clear out config.InterpreterArguments at
            // this stage if doing mixed-mode debugging. However, there doesn't
            // seem to be any need to do this, so we now leave them alone.

            using (var dbgInfo = DebugLaunchHelper.CreateDebugTargetInfo(_serviceProvider, config)) {
                dbgInfo.Launch();
            }
        }
示例#22
0
        private static void RunProfiler(SessionNode session, LaunchConfiguration config, bool openReport) {
            var process = new ProfiledProcess(
                (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService)),
                config.GetInterpreterPath(),
                string.Join(" ", ProcessOutput.QuoteSingleArgument(config.ScriptName), config.ScriptArguments),
                config.WorkingDirectory,
                session._serviceProvider.GetPythonToolsService().GetFullEnvironment(config)
            );

            string baseName = Path.GetFileNameWithoutExtension(session.Filename);
            string date = DateTime.Now.ToString("yyyyMMdd");
            string outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + ".vsp");

            int count = 1;
            while (File.Exists(outPath)) {
                outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vsp");
                count++;
            }

            process.ProcessExited += (sender, args) => {
                var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));
                _profilingProcess = null;
                _stopCommand.Enabled = false;
                _startCommand.Enabled = true;
                if (openReport && File.Exists(outPath)) {
                    dte.ItemOperations.OpenFile(outPath);
                }
            };

            session.AddProfile(outPath);

            process.StartProfiling(outPath);
            _profilingProcess = process;
            _stopCommand.Enabled = true;
            _startCommand.Enabled = false;
        }
示例#23
0
        private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport) {
            LaunchConfiguration config;
            if (runTarget.PythonInterpreter != null) {
                var registry = session._serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>();
                var interpreter = registry.FindConfiguration(runTarget.PythonInterpreter.Id);
                if (interpreter == null) {
                    return;
                }
                config = new LaunchConfiguration(interpreter);
            } else {
                config = new LaunchConfiguration(null);
            }

            config.InterpreterPath = runTarget.InterpreterPath;
            config.ScriptName = runTarget.Script;
            config.ScriptArguments = runTarget.Arguments;
            config.WorkingDirectory = runTarget.WorkingDirectory;

            RunProfiler(session, config, openReport);
        }
示例#24
0
        internal static void GetFullUrl(IServiceProvider provider, LaunchConfiguration config, out Uri uri, out int port) {
            int p;
            if (int.TryParse(config.GetLaunchOption(PythonConstants.WebBrowserPortSetting) ?? "", out p)) {
                port = p;
            } else {
                port = GetTestServerPort();
                p = -1;
            }

            var host = config.GetLaunchOption(PythonConstants.WebBrowserUrlSetting);
            if (string.IsNullOrEmpty(host)) {
                uri = null;
                return;
            }

            try {
                UriBuilder builder;
                if (Uri.TryCreate(host, UriKind.Absolute, out uri)) {
                    builder = new UriBuilder(uri);
                } else {
                    builder = new UriBuilder();
                    builder.Scheme = Uri.UriSchemeHttp;
                    builder.Host = "localhost";
                    builder.Path = host;
                }

                if (p >= 0) {
                    builder.Port = p;
                } else if (builder.Port < 0 || (builder.Uri.IsDefaultPort && !host.Contains(":{0}".FormatInvariant(builder.Port)))) {
                    builder.Port = GetTestServerPort();
                }

                uri = builder.Uri;
                port = uri.Port;
            } catch (UriFormatException) {
                if (provider == null) {
                    throw;
                }
                var output = OutputWindowRedirector.GetGeneral(provider);
                output.WriteErrorLine(Strings.ErrorInvalidLaunchUrl.FormatUI(host));
                output.ShowAndActivate();
                uri = null;
            }
        }
        public void LaunchDebugTarget(IServiceProvider serviceProvider, DebugLaunchActionContext debugLaunchActionContext) {
            var registry = serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>();

            var settings = debugLaunchActionContext.LaunchConfiguration;
            var scriptName = settings.GetValue(ScriptNameKey, string.Empty);
            var debug = !settings.GetValue("noDebug", false);
            var path = settings.GetValue(InterpreterKey, string.Empty);
            InterpreterConfiguration config = null;

            if (string.IsNullOrEmpty(scriptName)) {
                throw new InvalidOperationException(Strings.DebugLaunchScriptNameMissing);
            }

            if (!string.IsNullOrEmpty(path) && !DefaultInterpreterValue.Equals(path, StringComparison.OrdinalIgnoreCase)) {
                if (PathUtils.IsValidPath(path) && !Path.IsPathRooted(path)) {
                    // Cannot (currently?) get the workspace path easily from here, so we'll start from
                    // the startup file and work our way up until we find it.
                    var basePath = PathUtils.GetParent(scriptName);
                    string candidate = null;
                    
                    while (Directory.Exists(basePath)) {
                        candidate = PathUtils.GetAbsoluteFilePath(basePath, path);
                        if (File.Exists(candidate)) {
                            path = candidate;
                            break;
                        }
                        basePath = PathUtils.GetParent(basePath);
                    }
                }

                if (File.Exists(path)) {
                    config = registry.Configurations.FirstOrDefault(c => c.InterpreterPath.Equals(path, StringComparison.OrdinalIgnoreCase)) ??
                        new InterpreterConfiguration("Custom", path, PathUtils.GetParent(path), path);
                } else {
                    config = registry.FindConfiguration(path);
                }
            } else {
                var service = serviceProvider.GetComponentModel().GetService<IInterpreterOptionsService>();
                service.DefaultInterpreter.ThrowIfNotRunnable();
                config = service.DefaultInterpreter.Configuration;
                path = config.InterpreterPath;
            }

            if (!File.Exists(path)) {
                throw new InvalidOperationException(Strings.DebugLaunchInterpreterMissing_Path.FormatUI(path));
            }

            IProjectLauncher launcher = null;
            var launchConfig = new LaunchConfiguration(config) {
                InterpreterPath = config == null ? path : null,
                InterpreterArguments = settings.GetValue(InterpreterArgumentsKey, string.Empty),
                ScriptName = scriptName,
                ScriptArguments = settings.GetValue(ScriptArgumentsKey, string.Empty),
                WorkingDirectory = settings.GetValue(WorkingDirectoryKey, string.Empty),
                // TODO: Support search paths
                SearchPaths = null,
                // TODO: Support env variables
                Environment = null,
            };
            launchConfig.LaunchOptions[PythonConstants.EnableNativeCodeDebugging] = settings.GetValue(NativeDebuggingKey, false).ToString();


            var browserUrl = settings.GetValue(WebBrowserUrlKey, string.Empty);
            if (!string.IsNullOrEmpty(browserUrl)) {
                launchConfig.LaunchOptions[PythonConstants.WebBrowserUrlSetting] = browserUrl;
                launcher = new PythonWebLauncher(serviceProvider, launchConfig, launchConfig, launchConfig);
            }

            (launcher ?? new DefaultPythonLauncher(serviceProvider, launchConfig)).LaunchProject(debug);
        }
示例#26
0
        public static Dictionary <string, string> GetFullEnvironment(LaunchConfiguration config, IServiceProvider serviceProvider)
        {
            if (config.Interpreter == null)
            {
                throw new ArgumentNullException(nameof(Interpreter));
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }


            // Start with global environment, add configured environment,
            // then add search paths.
            var baseEnv = System.Environment.GetEnvironmentVariables();
            // Clear search paths from the global environment. The launch
            // configuration should include the existing value

            var pathVar = config.Interpreter?.PathEnvironmentVariable;

            if (string.IsNullOrEmpty(pathVar))
            {
                pathVar = "PYTHONPATH";
            }
            baseEnv[pathVar] = string.Empty;

            // TODO: We could introduce a cache so that we don't activate the
            // environment + capture the env variables every time. Not doing this
            // right now to minimize risk/complexity so close to release.
            if (CondaUtils.IsCondaEnvironment(config.Interpreter.GetPrefixPath()))
            {
                var condaExe   = CondaUtils.GetRootCondaExecutablePath(serviceProvider);
                var prefixPath = config.Interpreter.GetPrefixPath();
                if (File.Exists(condaExe) && Directory.Exists(prefixPath))
                {
                    var condaEnv = CondaUtils.CaptureActivationEnvironmentVariablesForPrefix(condaExe, prefixPath);
                    baseEnv = PathUtils.MergeEnvironments(baseEnv.AsEnumerable <string, string>(), condaEnv, "Path", pathVar);
                }
            }

            var env = PathUtils.MergeEnvironments(
                baseEnv.AsEnumerable <string, string>(),
                config.GetEnvironmentVariables(),
                "Path", pathVar
                );

            if (config.SearchPaths != null && config.SearchPaths.Any())
            {
                env = PathUtils.MergeEnvironments(
                    env,
                    new[] {
                    new KeyValuePair <string, string>(
                        pathVar,
                        PathUtils.JoinPathList(config.SearchPaths)
                        )
                },
                    pathVar
                    );
            }
            return(env);
        }