示例#1
0
        public CommandStartInfo GetStartInfo(IPythonProject2 project)
        {
            var outputs = BuildTarget(project, _target);
            var config  = PythonProjectLaunchProperties.Create(project);

            var item = outputs.Values
                       .SelectMany(result => result.Items)
                       .FirstOrDefault(i =>
                                       !string.IsNullOrEmpty(i.ItemSpec) &&
                                       !string.IsNullOrEmpty(i.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey))
                                       );

            if (item == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.ErrorBuildingCustomCommand, _target));
            }

            var startInfo = new CommandStartInfo {
                Filename             = item.ItemSpec,
                Arguments            = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ArgumentsKey),
                WorkingDirectory     = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WorkingDirectoryKey),
                EnvironmentVariables = PythonProjectLaunchProperties.ParseEnvironment(item.GetMetadata(BuildTasks.CreatePythonCommandItem.EnvironmentKey)),
                TargetType           = item.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey),
                ExecuteIn            = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ExecuteInKey),
                RequiredPackages     = item.GetMetadata(BuildTasks.CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            };

            try {
                startInfo.WorkingDirectory = CommonUtils.GetAbsoluteFilePath(project.ProjectHome, startInfo.WorkingDirectory);
            } catch (ArgumentException) {
            }

            string errorRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ErrorRegexKey);

            if (!string.IsNullOrEmpty(errorRegex))
            {
                startInfo.ErrorRegex = new Regex(errorRegex);
            }

            string warningRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WarningRegexKey);

            if (!string.IsNullOrEmpty(warningRegex))
            {
                startInfo.WarningRegex = new Regex(warningRegex);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";
            startInfo.AddPropertiesAfter(PythonProjectLaunchProperties.Create(project));

            Debug.Assert(!string.IsNullOrEmpty(startInfo.WorkingDirectory));
            Debug.Assert(Path.IsPathRooted(startInfo.WorkingDirectory));

            return(startInfo);
        }
示例#2
0
 private async void RunInConsole(IPythonProject project, CommandStartInfo startInfo)
 {
     using (var process = ProcessOutput.Run(
                startInfo.Filename,
                new[] { startInfo.Arguments },
                startInfo.WorkingDirectory,
                startInfo.EnvironmentVariables,
                true,
                null,
                quoteArgs: false
                )) {
         await process;
     }
 }
示例#3
0
        private async void RunInOutput(IPythonProject project, CommandStartInfo startInfo)
        {
            Redirector redirector = OutputWindowRedirector.GetGeneral(project.Site);

            if (startInfo.ErrorRegex != null || startInfo.WarningRegex != null)
            {
                redirector = new TeeRedirector(redirector, new ErrorListRedirector(_project.Site, project as IVsHierarchy, startInfo.WorkingDirectory, _errorListProvider, startInfo.ErrorRegex, startInfo.WarningRegex));
            }
            redirector.ShowAndActivate();

            using (var process = ProcessOutput.Run(
                       startInfo.Filename,
                       new[] { startInfo.Arguments },
                       startInfo.WorkingDirectory,
                       startInfo.EnvironmentVariables,
                       false,
                       redirector,
                       quoteArgs: false
                       )) {
                await process;
            }
        }
示例#4
0
        private async Task <bool> RunInRepl(IPythonProject project, CommandStartInfo startInfo)
        {
            var  executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
            bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture);

            var replTitle = executeIn.Substring(4).TrimStart(' ', ':');

            if (string.IsNullOrEmpty(replTitle))
            {
                replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys);
            }
            else
            {
                var match = _customCommandLabelRegex.Match(replTitle);
                if (match.Success)
                {
                    replTitle = LoadResourceFromAssembly(
                        match.Groups["assembly"].Value,
                        match.Groups["namespace"].Value,
                        match.Groups["key"].Value
                        );
                }
            }

            replTitle = PerformSubstitutions(project, replTitle);

            var replWindowId = PythonReplEvaluatorProvider.GetTemporaryId(
                ReplId + executeIn.Substring(4),
                _project.GetInterpreterFactory().Configuration
                );

            var model        = _project.Site.GetComponentModel();
            var replProvider = model.GetService <InteractiveWindowProvider>();

            if (replProvider == null)
            {
                return(false);
            }

            bool created;
            var  replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created);

            // TODO: Find alternative way of closing repl window on Dev15
            var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame;

            var interactive = replWindow.InteractiveWindow;
            var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator;

            if (pyEvaluator == null)
            {
                if (created && replFrame != null)
                {
                    // We created the window, but it isn't valid, so we'll close
                    // it again immediately.
                    replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                return(false);
            }

            if (pyEvaluator.IsExecuting)
            {
                throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning);
            }

            pyEvaluator.ProjectMoniker = _project.GetMkDocument();
            pyEvaluator.Configuration  = new LaunchConfiguration(startInfo.Interpreter)
            {
                WorkingDirectory = startInfo.WorkingDirectory,
                Environment      = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value)
            };

            project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close);

            replWindow.Show(true);

            var result = await pyEvaluator.ResetAsync(false, quiet : true);

            if (result.IsSuccessful)
            {
                try {
                    var filename  = startInfo.Filename;
                    var arguments = startInfo.Arguments ?? string.Empty;

                    if (startInfo.IsScript)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingScript.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteFileAsync(filename, arguments);
                    }
                    else if (startInfo.IsModule)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingModule.FormatUI(filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteModuleAsync(filename, arguments);
                    }
                    else if (startInfo.IsCode)
                    {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        await pyEvaluator.ExecuteCodeAsync(filename);
                    }
                    else
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingOther.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteProcessAsync(filename, arguments);
                    }

                    if (resetRepl)
                    {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Dispose();
                    }
                } catch (Exception ex) {
                    ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                    var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
                    if (outWindow != null)
                    {
                        outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                        outWindow.Show();
                    }
                }
                return(true);
            }

            return(false);
        }
示例#5
0
        public CommandStartInfo GetStartInfo(IPythonProject project)
        {
            var outputs = BuildTarget(project, _target);
            var config  = project.GetLaunchConfigurationOrThrow();

            var item = outputs.Values
                       .SelectMany(result => result.Items)
                       .FirstOrDefault(i =>
                                       !string.IsNullOrEmpty(i.ItemSpec) &&
                                       !string.IsNullOrEmpty(i.GetMetadata(CreatePythonCommandItem.TargetTypeKey))
                                       );

            if (item == null)
            {
                throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(_target));
            }

            var startInfo = new CommandStartInfo(config.Interpreter)
            {
                Filename         = item.ItemSpec,
                Arguments        = item.GetMetadata(CreatePythonCommandItem.ArgumentsKey),
                WorkingDirectory = item.GetMetadata(CreatePythonCommandItem.WorkingDirectoryKey),
                TargetType       = item.GetMetadata(CreatePythonCommandItem.TargetTypeKey),
                ExecuteIn        = item.GetMetadata(CreatePythonCommandItem.ExecuteInKey),
                RequiredPackages = item.GetMetadata(CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            };

            var pathVar = config.Interpreter.PathEnvironmentVariable;
            var env     = new Dictionary <string, string> {
                { pathVar, PathUtils.JoinPathList(config.SearchPaths) }
            };

            startInfo.EnvironmentVariables = PathUtils.MergeEnvironments(
                PathUtils.MergeEnvironments(env, config.Environment, pathVar),
                PathUtils.ParseEnvironment(item.GetMetadata(CreatePythonCommandItem.EnvironmentKey)),
                "Path", config.Interpreter.PathEnvironmentVariable
                );

            try {
                startInfo.WorkingDirectory = PathUtils.GetAbsoluteFilePath(project.ProjectHome, startInfo.WorkingDirectory);
            } catch (ArgumentException) {
            }

            string errorRegex = item.GetMetadata(CreatePythonCommandItem.ErrorRegexKey);

            if (!string.IsNullOrEmpty(errorRegex))
            {
                startInfo.ErrorRegex = new Regex(errorRegex);
            }

            string warningRegex = item.GetMetadata(CreatePythonCommandItem.WarningRegexKey);

            if (!string.IsNullOrEmpty(warningRegex))
            {
                startInfo.WarningRegex = new Regex(warningRegex);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";

            Debug.Assert(!string.IsNullOrEmpty(startInfo.WorkingDirectory));
            Debug.Assert(Path.IsPathRooted(startInfo.WorkingDirectory));

            return(startInfo);
        }
示例#6
0
 private async void RunInConsole(IPythonProject2 project, CommandStartInfo startInfo) {
     using (var process = ProcessOutput.Run(
         startInfo.Filename,
         new[] { startInfo.Arguments },
         startInfo.WorkingDirectory,
         startInfo.EnvironmentVariables,
         true,
         null,
         quoteArgs: false
     )) {
         await process;
     }
 }
示例#7
0
        private async void RunInOutput(IPythonProject2 project, CommandStartInfo startInfo) {
            Redirector redirector = OutputWindowRedirector.GetGeneral(project.Site);
            if (startInfo.ErrorRegex != null || startInfo.WarningRegex != null) {
                redirector = new TeeRedirector(redirector, new ErrorListRedirector(_project.Site, project as IVsHierarchy, startInfo.WorkingDirectory, _errorListProvider, startInfo.ErrorRegex, startInfo.WarningRegex));
            }
            redirector.ShowAndActivate();

            using (var process = ProcessOutput.Run(
                startInfo.Filename,
                new[] { startInfo.Arguments },
                startInfo.WorkingDirectory,
                startInfo.EnvironmentVariables,
                false,
                redirector,
                quoteArgs: false
            )) {
                await process;
            }
        }
示例#8
0
        private async Task<bool> RunInRepl(IPythonProject2 project, CommandStartInfo startInfo) {
            var executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
            bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture);

            var replTitle = executeIn.Substring(4).TrimStart(' ', ':');
            if (string.IsNullOrEmpty(replTitle)) {
                replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys);
            } else {
                var match = _customCommandLabelRegex.Match(replTitle);
                if (match.Success) {
                    replTitle = LoadResourceFromAssembly(
                        match.Groups["assembly"].Value,
                        match.Groups["namespace"].Value,
                        match.Groups["key"].Value
                    );
                }
            }

            replTitle = PerformSubstitutions(project, replTitle);

            var replWindowId = PythonReplEvaluatorProvider.GetConfigurableReplId(ReplId + executeIn.Substring(4));
            
            var model = _project.Site.GetComponentModel();
            var replProvider = model.GetService<InteractiveWindowProvider>();
            if (replProvider == null) {
                return false;
            }

            var replWindow = replProvider.FindReplWindow(replWindowId);
            bool created = replWindow == null;
            if (created) {
                replWindow = replProvider.CreateInteractiveWindow(
                    _project.Site.GetPythonContentType(),
                    replTitle,
                    typeof(PythonLanguageInfo).GUID,
                    replWindowId
                );
            }

            var replToolWindow = replWindow as ToolWindowPane;
            var replFrame = (replToolWindow != null) ? replToolWindow.Frame as IVsWindowFrame : null;

            var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonReplEvaluator;
            var options = (pyEvaluator != null) ? pyEvaluator.CurrentOptions as ConfigurablePythonReplOptions : null;
            if (options == null) {
                if (created && replFrame != null) {
                    // We created the window, but it isn't valid, so we'll close
                    // it again immediately.
                    replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                return false;
            }

            if (pyEvaluator.IsExecuting) {
                throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning);
            }

            var ipp3 = project as IPythonProject3;
            if (ipp3 != null) {
                options.InterpreterFactory = ipp3.GetInterpreterFactoryOrThrow();
            } else {
                options.InterpreterFactory = project.GetInterpreterFactory();
            }
            options.Project = project as PythonProjectNode;
            options._workingDir = startInfo.WorkingDirectory;
            options._envVars = startInfo.EnvironmentVariables;

            project.AddActionOnClose((object)replWindow, BasePythonReplEvaluator.CloseReplWindow);

            var pane = replWindow as ToolWindowPane;
            var frame = pane != null ? pane.Frame as IVsWindowFrame : null;
            if (frame != null) {
                ErrorHandler.ThrowOnFailure(frame.Show());
            }

            var result = await pyEvaluator.Reset(quiet: true);

            if (result.IsSuccessful) {
                try {
                    var filename = startInfo.Filename;
                    var arguments = startInfo.Arguments ?? string.Empty;

                    if (startInfo.IsScript) {
                        pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteFile(filename, arguments);
                    } else if (startInfo.IsModule) {
                        pyEvaluator.Window.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteModule(filename, arguments);
                    } else if (startInfo.IsCode) {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        result = await pyEvaluator.ExecuteText(filename);
                    } else {
                        pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteProcess(filename, arguments);
                    }

                    if (resetRepl) {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Close();
                    }
                } catch (Exception ex) {
                    ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                    var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
                    if (outWindow != null) {
                        outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                        outWindow.Show();
                    }
                }
                return true;
            }

            return false;
        }
示例#9
0
        public CommandStartInfo GetStartInfo(IPythonProject2 project) {
            var outputs = BuildTarget(project, _target);
            var config = PythonProjectLaunchProperties.Create(project);

            var item = outputs.Values
                .SelectMany(result => result.Items)
                .FirstOrDefault(i =>
                    !string.IsNullOrEmpty(i.ItemSpec) &&
                    !string.IsNullOrEmpty(i.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey))
                );

            if (item == null) {
                throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(_target));
            }

            var startInfo = new CommandStartInfo {
                Filename = item.ItemSpec,
                Arguments = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ArgumentsKey),
                WorkingDirectory = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WorkingDirectoryKey),
                EnvironmentVariables = PythonProjectLaunchProperties.ParseEnvironment(item.GetMetadata(BuildTasks.CreatePythonCommandItem.EnvironmentKey)),
                TargetType = item.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey),
                ExecuteIn = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ExecuteInKey),
                RequiredPackages = item.GetMetadata(BuildTasks.CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            };

            try {
                startInfo.WorkingDirectory = PathUtils.GetAbsoluteFilePath(project.ProjectHome, startInfo.WorkingDirectory);
            } catch (ArgumentException) {
            }

            string errorRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ErrorRegexKey);
            if (!string.IsNullOrEmpty(errorRegex)) {
                startInfo.ErrorRegex = new Regex(errorRegex);
            }

            string warningRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WarningRegexKey);
            if (!string.IsNullOrEmpty(warningRegex)) {
                startInfo.WarningRegex = new Regex(warningRegex);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";
            startInfo.AddPropertiesAfter(PythonProjectLaunchProperties.Create(project));

            Debug.Assert(!string.IsNullOrEmpty(startInfo.WorkingDirectory));
            Debug.Assert(Path.IsPathRooted(startInfo.WorkingDirectory));

            return startInfo;
        }
示例#10
0
        private async Task <bool> RunInRepl(IPythonProject2 project, CommandStartInfo startInfo)
        {
            var  executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
            bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture);

            var replTitle = executeIn.Substring(4).TrimStart(' ', ':');

            if (string.IsNullOrEmpty(replTitle))
            {
                replTitle = SR.GetString(SR.CustomCommandReplTitle, DisplayLabelWithoutAccessKeys);
            }
            else
            {
                var match = _customCommandLabelRegex.Match(replTitle);
                if (match.Success)
                {
                    replTitle = LoadResourceFromAssembly(
                        match.Groups["assembly"].Value,
                        match.Groups["namespace"].Value,
                        match.Groups["key"].Value
                        );
                }
            }

            replTitle = PerformSubstitutions(project, replTitle);

            var replWindowId = PythonReplEvaluatorProvider.GetConfigurableReplId(ReplId + executeIn.Substring(4));

            var model        = _project.Site.GetComponentModel();
            var replProvider = model.GetService <IReplWindowProvider>();

            if (replProvider == null)
            {
                return(false);
            }

            var  replWindow = replProvider.FindReplWindow(replWindowId);
            bool created    = replWindow == null;

            if (created)
            {
                replWindow = replProvider.CreateReplWindow(
                    _project.Site.GetPythonContentType(),
                    replTitle,
                    typeof(PythonLanguageInfo).GUID,
                    replWindowId
                    );
            }

            var replToolWindow = replWindow as ToolWindowPane;
            var replFrame      = (replToolWindow != null) ? replToolWindow.Frame as IVsWindowFrame : null;

            var pyEvaluator = replWindow.Evaluator as PythonReplEvaluator;
            var options     = (pyEvaluator != null) ? pyEvaluator.CurrentOptions as ConfigurablePythonReplOptions : null;

            if (options == null)
            {
                if (created && replFrame != null)
                {
                    // We created the window, but it isn't valid, so we'll close
                    // it again immediately.
                    replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                return(false);
            }

            if (pyEvaluator.IsExecuting)
            {
                throw new InvalidOperationException(SR.GetString(SR.ErrorCommandAlreadyRunning));
            }

            options.InterpreterFactory = project.GetInterpreterFactory();
            options.Project            = project as PythonProjectNode;
            options._workingDir        = startInfo.WorkingDirectory;
            options._envVars           = startInfo.EnvironmentVariables;

            project.AddActionOnClose((object)replWindow, BasePythonReplEvaluator.CloseReplWindow);

            var pane  = replWindow as ToolWindowPane;
            var frame = pane != null ? pane.Frame as IVsWindowFrame : null;

            if (frame != null)
            {
                ErrorHandler.ThrowOnFailure(frame.Show());
            }

            var result = await pyEvaluator.Reset(quiet : true);

            if (result.IsSuccessful)
            {
                try {
                    var filename  = startInfo.Filename;
                    var arguments = startInfo.Arguments;

                    if (startInfo.IsScript)
                    {
                        pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteFile(filename, arguments);
                    }
                    else if (startInfo.IsModule)
                    {
                        pyEvaluator.Window.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteModule(filename, arguments);
                    }
                    else if (startInfo.IsCode)
                    {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        result = await pyEvaluator.ExecuteText(filename);
                    }
                    else
                    {
                        pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteProcess(filename, arguments);
                    }

                    if (resetRepl)
                    {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Close();
                    }
                } catch (Exception ex) {
                    ActivityLog.LogError(SR.ProductName, SR.GetString(SR.ErrorRunningCustomCommand, _label, ex));
                    var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
                    if (outWindow != null)
                    {
                        outWindow.WriteErrorLine(SR.GetString(SR.ErrorRunningCustomCommand, _label, ex));
                        outWindow.Show();
                    }
                }
                return(true);
            }

            return(false);
        }
示例#11
0
        public CommandStartInfo GetStartInfo(IPythonProject2 project)
        {
            var outputs = BuildTarget(project, _target);

            var item = outputs.Values
                       .SelectMany(result => result.Items)
                       .FirstOrDefault(i =>
                                       !string.IsNullOrEmpty(i.ItemSpec) &&
                                       !string.IsNullOrEmpty(i.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey))
                                       );

            if (item == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.ErrorBuildingCustomCommand, _target));
            }

            var startInfo = new CommandStartInfo {
                Filename             = item.ItemSpec,
                Arguments            = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ArgumentsKey),
                WorkingDirectory     = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WorkingDirectoryKey),
                EnvironmentVariables = new Dictionary <string, string>(),
                TargetType           = item.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey),
                ExecuteIn            = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ExecuteInKey),
                RequiredPackages     = item.GetMetadata(BuildTasks.CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            };

            string errorRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ErrorRegexKey);

            if (!string.IsNullOrEmpty(errorRegex))
            {
                startInfo.ErrorRegex = new Regex(errorRegex);
            }

            string warningRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WarningRegexKey);

            if (!string.IsNullOrEmpty(warningRegex))
            {
                startInfo.WarningRegex = new Regex(warningRegex);
            }

            // Fill PYTHONPATH from interpreter settings before we load values from Environment metadata item,
            // so that commands can explicitly override it if they want to.
            var pythonPathVarName = project.GetInterpreterFactory().Configuration.PathEnvironmentVariable;

            if (!string.IsNullOrWhiteSpace(pythonPathVarName))
            {
                var pythonPath = string.Join(";", project.GetSearchPaths());
                if (!_project.Site.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath)
                {
                    pythonPath += ";" + Environment.GetEnvironmentVariable(pythonPathVarName);
                }
                startInfo.EnvironmentVariables[pythonPathVarName] = pythonPath;
            }

            // Fill other environment variables from project properties.
            string userEnv = project.GetProperty(PythonConstants.EnvironmentSetting);

            if (userEnv != null)
            {
                foreach (var envVar in userEnv.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var nameValue = envVar.Split(new[] { '=' }, 2);
                    if (nameValue.Length == 2)
                    {
                        startInfo.EnvironmentVariables[nameValue[0]] = nameValue[1];
                    }
                }
            }

            var environment = item.GetMetadata(BuildTasks.CreatePythonCommandItem.EnvironmentKey);

            foreach (var line in environment.Split('\r', '\n'))
            {
                int equals = line.IndexOf('=');
                if (equals > 0)
                {
                    startInfo.EnvironmentVariables[line.Substring(0, equals)] = line.Substring(equals + 1);
                }
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";

            if (string.IsNullOrEmpty(startInfo.WorkingDirectory))
            {
                startInfo.WorkingDirectory = project.ProjectHome ?? string.Empty;
            }
            else if (!Path.IsPathRooted(startInfo.WorkingDirectory))
            {
                startInfo.WorkingDirectory = CommonUtils.GetAbsoluteDirectoryPath(project.ProjectHome, startInfo.WorkingDirectory);
            }

            return(startInfo);
        }
示例#12
0
        private async Task<bool> RunInRepl(IPythonProject project, CommandStartInfo startInfo) {
            var executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
            bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture);

            var replTitle = executeIn.Substring(4).TrimStart(' ', ':');
            if (string.IsNullOrEmpty(replTitle)) {
                replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys);
            } else {
                var match = _customCommandLabelRegex.Match(replTitle);
                if (match.Success) {
                    replTitle = LoadResourceFromAssembly(
                        match.Groups["assembly"].Value,
                        match.Groups["namespace"].Value,
                        match.Groups["key"].Value
                    );
                }
            }

            replTitle = PerformSubstitutions(project, replTitle);

            var replWindowId = PythonReplEvaluatorProvider.GetTemporaryId(
                ReplId + executeIn.Substring(4),
                _project.GetInterpreterFactory().Configuration
            );
            
            var model = _project.Site.GetComponentModel();
            var replProvider = model.GetService<InteractiveWindowProvider>();
            if (replProvider == null) {
                return false;
            }

            bool created;
            var replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created);

            // TODO: Find alternative way of closing repl window on Dev15
            var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame;

            var interactive = replWindow.InteractiveWindow;
            var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator;
            if (pyEvaluator == null) {
                if (created && replFrame != null) {
                    // We created the window, but it isn't valid, so we'll close
                    // it again immediately.
                    replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                return false;
            }

            if (pyEvaluator.IsExecuting) {
                throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning);
            }

            pyEvaluator.ProjectMoniker = _project.GetMkDocument();
            pyEvaluator.Configuration = new LaunchConfiguration(startInfo.Interpreter) {
                WorkingDirectory = startInfo.WorkingDirectory,
                Environment = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value)
            };

            project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close);

            replWindow.Show(true);

            var result = await pyEvaluator.ResetAsync(false, quiet: true);

            if (result.IsSuccessful) {
                try {
                    var filename = startInfo.Filename;
                    var arguments = startInfo.Arguments ?? string.Empty;

                    if (startInfo.IsScript) {
                        interactive.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteFileAsync(filename, arguments);
                    } else if (startInfo.IsModule) {
                        interactive.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteModuleAsync(filename, arguments);
                    } else if (startInfo.IsCode) {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        await pyEvaluator.ExecuteCodeAsync(filename);
                    } else {
                        interactive.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteProcessAsync(filename, arguments);
                    }

                    if (resetRepl) {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Dispose();
                    }
                } catch (Exception ex) {
                    ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                    var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
                    if (outWindow != null) {
                        outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                        outWindow.Show();
                    }
                }
                return true;
            }

            return false;
        }
示例#13
0
        public CommandStartInfo GetStartInfo(IPythonProject project) {
            var outputs = BuildTarget(project, _target);
            var config = project.GetLaunchConfigurationOrThrow();

            var item = outputs.Values
                .SelectMany(result => result.Items)
                .FirstOrDefault(i =>
                    !string.IsNullOrEmpty(i.ItemSpec) &&
                    !string.IsNullOrEmpty(i.GetMetadata(CreatePythonCommandItem.TargetTypeKey))
                );

            if (item == null) {
                throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(_target));
            }

            var startInfo = new CommandStartInfo(config.Interpreter) {
                Filename = item.ItemSpec,
                Arguments = item.GetMetadata(CreatePythonCommandItem.ArgumentsKey),
                WorkingDirectory = item.GetMetadata(CreatePythonCommandItem.WorkingDirectoryKey),
                TargetType = item.GetMetadata(CreatePythonCommandItem.TargetTypeKey),
                ExecuteIn = item.GetMetadata(CreatePythonCommandItem.ExecuteInKey),
                RequiredPackages = item.GetMetadata(CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            };

            var pathVar = config.Interpreter.PathEnvironmentVariable;
            var env = new Dictionary<string, string> {
                { pathVar, PathUtils.JoinPathList(config.SearchPaths) }
            };
            startInfo.EnvironmentVariables = PathUtils.MergeEnvironments(
                PathUtils.MergeEnvironments(env, config.Environment, pathVar),
                PathUtils.ParseEnvironment(item.GetMetadata(CreatePythonCommandItem.EnvironmentKey)),
                "Path", config.Interpreter.PathEnvironmentVariable
            );

            try {
                startInfo.WorkingDirectory = PathUtils.GetAbsoluteFilePath(project.ProjectHome, startInfo.WorkingDirectory);
            } catch (ArgumentException) {
            }

            string errorRegex = item.GetMetadata(CreatePythonCommandItem.ErrorRegexKey);
            if (!string.IsNullOrEmpty(errorRegex)) {
                startInfo.ErrorRegex = new Regex(errorRegex);
            }

            string warningRegex = item.GetMetadata(CreatePythonCommandItem.WarningRegexKey);
            if (!string.IsNullOrEmpty(warningRegex)) {
                startInfo.WarningRegex = new Regex(warningRegex);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";

            Debug.Assert(!string.IsNullOrEmpty(startInfo.WorkingDirectory));
            Debug.Assert(Path.IsPathRooted(startInfo.WorkingDirectory));

            return startInfo;
        }