コード例 #1
0
        private async void CreateProjectAndHandleErrors(
            IVsStatusbar statusBar,
            Microsoft.PythonTools.Project.ImportWizard.ImportWizard dlg,
            bool addToExistingSolution
            )
        {
            try {
                var path = await dlg.ImportSettings.CreateRequestedProjectAsync();

                if (File.Exists(path))
                {
                    object outRef = null, pathRef = ProcessOutput.QuoteSingleArgument(path);
                    _serviceProvider.GetDTE().Commands.Raise(
                        VSConstants.GUID_VSStandardCommandSet97.ToString("B"),
                        addToExistingSolution
                            ? (int)VSConstants.VSStd97CmdID.AddExistingProject
                            : (int)VSConstants.VSStd97CmdID.OpenProject,
                        ref pathRef,
                        ref outRef
                        );
                    statusBar.SetText("");
                    return;
                }
            } catch (UnauthorizedAccessException) {
                MessageBox.Show(Strings.ErrorImportWizardUnauthorizedAccess, Strings.ProductTitle);
            } catch (Exception ex) {
                ActivityLog.LogError(Strings.ProductTitle, ex.ToString());
                MessageBox.Show(Strings.ErrorImportWizardException.FormatUI(ex.GetType().Name), Strings.ProductTitle);
            }
            statusBar.SetText(Strings.StatusImportWizardError);
        }
コード例 #2
0
ファイル: DiagnosticsForm.cs プロジェクト: zuokaihuang/PTVS
        private void _save_Click(object sender, EventArgs e)
        {
            var path = _provider.BrowseForFileSave(
                Handle,
                "Text Files (*.txt)|*.txt|All Files (*.*)|*.*",
                PathUtils.GetAbsoluteFilePath(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    string.Format("Diagnostic Info {0:yyyy-MM-dd'T'HHmmss}.txt", DateTime.Now)
                    )
                );

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            try {
                TaskDialog.CallWithRetry(
                    _ => File.WriteAllText(path, _textBox.Text),
                    _provider,
                    Strings.ProductTitle,
                    Strings.FailedToSaveDiagnosticInfo,
                    Strings.ErrorDetail,
                    Strings.Retry,
                    Strings.Cancel
                    );

                Process.Start("explorer.exe", "/select," + ProcessOutput.QuoteSingleArgument(path));
            } catch (OperationCanceledException) {
            }
        }
コード例 #3
0
        public async Task <bool> DeleteAsync(string envPath, ICondaEnvironmentManagerUI ui, CancellationToken ct)
        {
            bool success = false;

            using (await _working.LockAsync(ct)) {
                var args = new[] {
                    "remove",
                    "-p",
                    ProcessOutput.QuoteSingleArgument(envPath),
                    "--all",
                    "-y",
                };

                var operation = "conda " + string.Join(" ", args);

                ui?.OnOperationStarted(this, operation);
                ui?.OnOutputTextReceived(this, Strings.CondaDeleteStarted.FormatUI(envPath));
                try {
                    if (!Directory.Exists(envPath))
                    {
                        ui?.OnErrorTextReceived(this, Strings.CondaFolderNotFoundError.FormatUI(envPath));
                        success = false;
                        return(success);
                    }

                    success = await DoOperationAsync(args, ui, ct);

                    return(success);
                } finally {
                    var msg = success ? Strings.CondaDeleteSuccess : Strings.CondaDeleteFailed;
                    ui?.OnOutputTextReceived(this, msg.FormatUI(envPath));
                    ui?.OnOperationFinished(this, operation, success);
                }
            }
        }
コード例 #4
0
        public async Task <bool> CreateAsync(string newEnvNameOrPath, IEnumerable <PackageSpec> packageSpecs, ICondaEnvironmentManagerUI ui, CancellationToken ct)
        {
            bool success = false;

            using (await _working.LockAsync(ct)) {
                var args = new[] {
                    "create",
                    IsAbsolutePath(newEnvNameOrPath) ? "-p" : "-n",
                    ProcessOutput.QuoteSingleArgument(newEnvNameOrPath),
                    "-y",
                }.Union(packageSpecs.Select(s => s.FullSpec));

                var operation = "conda " + string.Join(" ", args);

                ui?.OnOperationStarted(this, operation);
                ui?.OnOutputTextReceived(this, Strings.CondaCreateStarted.FormatUI(newEnvNameOrPath));
                try {
                    if (!PathUtils.IsValidPath(newEnvNameOrPath))
                    {
                        ui?.OnErrorTextReceived(this, Strings.CondaCreateInvalidNameOrPath.FormatUI(newEnvNameOrPath));
                        success = false;
                        return(success);
                    }

                    success = await DoOperationAsync(args, ui, ct);

                    return(success);
                } finally {
                    var msg = success ? Strings.CondaCreateSuccess : Strings.CondaCreateFailed;
                    ui?.OnOutputTextReceived(this, msg.FormatUI(newEnvNameOrPath));
                    ui?.OnOperationFinished(this, operation, success);
                }
            }
        }
コード例 #5
0
ファイル: ProfiledProcess.cs プロジェクト: zhangjinxing/PTVS
        private void StartPerfMon(string filename)
        {
            string perfToolsPath = GetPerfToolsPath();

            string perfMonPath = Path.Combine(perfToolsPath, "VSPerfMon.exe");

            if (!File.Exists(perfMonPath))
            {
                throw new InvalidOperationException(Strings.CannotLocatePerformanceTools);
            }

            var psi = new ProcessStartInfo(perfMonPath, "/trace /output:" + ProcessOutput.QuoteSingleArgument(filename));

            psi.CreateNoWindow         = true;
            psi.UseShellExecute        = false;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            Process.Start(psi).Dispose();

            string perfCmdPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe");

            using (var p = ProcessOutput.RunHiddenAndCapture(perfCmdPath, "/waitstart")) {
                p.Wait();
                if (p.ExitCode != 0)
                {
                    throw new InvalidOperationException(Strings.StartPerfCmdError.FormatUI(
                                                            string.Join(Environment.NewLine, p.StandardOutputLines),
                                                            string.Join(Environment.NewLine, p.StandardErrorLines)
                                                            ));
                }
            }
        }
コード例 #6
0
        private void Save_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var path = _provider.BrowseForFileSave(
                new WindowInteropHelper(this).Handle,
                Strings.DiagnosticsWindow_TextFileFilter,
                PathUtils.GetAbsoluteFilePath(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    Strings.DiagnosticsWindow_DefaultFileName.FormatUI(DateTime.Now)
                    )
                );

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            try {
                TaskDialog.CallWithRetry(
                    _ => File.WriteAllText(path, _info.Result),
                    _provider,
                    Strings.ProductTitle,
                    Strings.FailedToSaveDiagnosticInfo,
                    Strings.ErrorDetail,
                    Strings.Retry,
                    Strings.Cancel
                    );

                Process.Start("explorer.exe", "/select," + ProcessOutput.QuoteSingleArgument(path)).Dispose();
            } catch (OperationCanceledException) {
            }
        }
コード例 #7
0
ファイル: ProfiledProcess.cs プロジェクト: xNUTs/PTVS
        private void StartPerfMon(string filename)
        {
            string perfToolsPath = GetPerfToolsPath();

            string perfMonPath = Path.Combine(perfToolsPath, "VSPerfMon.exe");

            var psi = new ProcessStartInfo(perfMonPath, "/trace /output:" + ProcessOutput.QuoteSingleArgument(filename));

            psi.CreateNoWindow         = true;
            psi.UseShellExecute        = false;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            var process = Process.Start(psi);

            string perfCmdPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe");

            psi = new ProcessStartInfo(perfCmdPath, "/waitstart");
            psi.CreateNoWindow         = true;
            psi.UseShellExecute        = false;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            process = Process.Start(psi);
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                throw new InvalidOperationException("Starting perf cmd failed: " + process.StandardOutput.ReadToEnd());
            }
        }
コード例 #8
0
ファイル: DefaultPythonLauncher.cs プロジェクト: krus/PTVS
 /// <summary>
 /// Creates language specific command line for starting the project without debigging.
 /// </summary>
 public string CreateCommandLineNoDebug(string startupFile, IPythonProjectLaunchProperties props)
 {
     return(string.Join(" ", new[] {
         props.GetInterpreterArguments(),
         ProcessOutput.QuoteSingleArgument(startupFile),
         props.GetArguments()
     }.Where(s => !string.IsNullOrEmpty(s))));
 }
コード例 #9
0
ファイル: DefaultPythonLauncher.cs プロジェクト: krus/PTVS
 /// <summary>
 /// Creates language specific command line for starting the project with debigging.
 /// </summary>
 public string CreateCommandLineDebug(string startupFile, IPythonProjectLaunchProperties props)
 {
     return(string.Join(" ", new[] {
         (props.GetIsNativeDebuggingEnabled() ?? false) ? props.GetInterpreterArguments() : null,
         ProcessOutput.QuoteSingleArgument(startupFile),
         props.GetArguments()
     }.Where(s => !string.IsNullOrEmpty(s))));
 }
コード例 #10
0
ファイル: ProfiledProcess.cs プロジェクト: zhangjinxing/PTVS
        public ProfiledProcess(PythonToolsService pyService, string exe, string args, string dir, Dictionary <string, string> envVars)
        {
            var arch = NativeMethods.GetBinaryType(exe);

            if (arch != ProcessorArchitecture.X86 && arch != ProcessorArchitecture.Amd64)
            {
                throw new InvalidOperationException(Strings.UnsupportedArchitecture.FormatUI(arch));
            }

            dir = PathUtils.TrimEndSeparator(dir);
            if (string.IsNullOrEmpty(dir))
            {
                dir = ".";
            }

            _pyService = pyService;
            _exe       = exe;
            _args      = args;
            _dir       = dir;
            _arch      = arch;

            ProcessStartInfo processInfo;
            string           pythonInstallDir = Path.GetDirectoryName(PythonToolsInstallPath.GetFile("VsPyProf.dll", typeof(ProfiledProcess).Assembly));

            string dll       = _arch == ProcessorArchitecture.Amd64 ? "VsPyProf.dll" : "VsPyProfX86.dll";
            string arguments = string.Join(" ",
                                           ProcessOutput.QuoteSingleArgument(Path.Combine(pythonInstallDir, "proflaun.py")),
                                           ProcessOutput.QuoteSingleArgument(Path.Combine(pythonInstallDir, dll)),
                                           ProcessOutput.QuoteSingleArgument(dir),
                                           _args
                                           );

            processInfo = new ProcessStartInfo(_exe, arguments);
            if (_pyService.DebuggerOptions.WaitOnNormalExit)
            {
                processInfo.EnvironmentVariables["VSPYPROF_WAIT_ON_NORMAL_EXIT"] = "1";
            }
            if (_pyService.DebuggerOptions.WaitOnAbnormalExit)
            {
                processInfo.EnvironmentVariables["VSPYPROF_WAIT_ON_ABNORMAL_EXIT"] = "1";
            }

            processInfo.CreateNoWindow         = false;
            processInfo.UseShellExecute        = false;
            processInfo.RedirectStandardOutput = false;
            processInfo.WorkingDirectory       = _dir;

            if (envVars != null)
            {
                foreach (var keyValue in envVars)
                {
                    processInfo.EnvironmentVariables[keyValue.Key] = keyValue.Value;
                }
            }

            _process           = new Process();
            _process.StartInfo = processInfo;
        }
コード例 #11
0
ファイル: CondaPackageManager.cs プロジェクト: zyxws012/PTVS
        public async Task <bool> InstallAsync(PackageSpec package, IPackageManagerUI ui, CancellationToken cancellationToken)
        {
            AbortOnInvalidConfiguration();
            await AbortIfNotReady(cancellationToken);

            bool success = false;
            var  args    = new List <string>();

            args.Add("install");
            args.Add("-p");
            args.Add(ProcessOutput.QuoteSingleArgument(_factory.Configuration.GetPrefixPath()));
            args.Add("-y");

            args.Add(package.FullSpec);
            var name      = string.IsNullOrEmpty(package.Name) ? package.FullSpec : package.Name;
            var operation = string.Join(" ", args);

            using (await _working.LockAsync(cancellationToken)) {
                ui?.OnOperationStarted(this, operation);
                ui?.OnOutputTextReceived(this, Strings.InstallingPackageStarted.FormatUI(name));

                var envVars = await GetEnvironmentVariables();

                try {
                    using (var output = ProcessOutput.Run(
                               _condaPath,
                               args,
                               _factory.Configuration.GetPrefixPath(),
                               envVars,
                               false,
                               PackageManagerUIRedirector.Get(this, ui),
                               quoteArgs: false,
                               elevate: await ShouldElevate(ui, operation)
                               )) {
                        if (!output.IsStarted)
                        {
                            return(false);
                        }
                        var exitCode = await output;
                        success = exitCode == 0;
                    }
                    return(success);
                } catch (IOException) {
                    return(false);
                } finally {
                    if (!success)
                    {
                        // Check whether we failed because conda is missing
                        UpdateIsReadyAsync(true, CancellationToken.None).DoNotWait();
                    }

                    var msg = success ? Strings.InstallingPackageSuccess : Strings.InstallingPackageFailed;
                    ui?.OnOutputTextReceived(this, msg.FormatUI(name));
                    ui?.OnOperationFinished(this, operation, success);
                    await CacheInstalledPackagesAsync(true, false, cancellationToken);
                }
            }
        }
コード例 #12
0
        private static void RunVTune(SessionNode session, LaunchConfiguration config, bool openReport)
        {
            var interpreter = config.GetInterpreterPath();

            if (!File.Exists(interpreter))
            {
                MessageBox.Show(Strings.CannotFindPythonInterpreter, Strings.ProductTitle);
                return;
            }

            string outPathDir = Path.GetTempPath();
            var    subpath    = Path.Combine(outPathDir, Path.GetRandomFileName());

            while (Directory.Exists(subpath) || File.Exists(subpath))
            {
                subpath = Path.Combine(outPathDir, Path.GetRandomFileName());
            }
            outPathDir = subpath;

            string outPath = Path.Combine(outPathDir, "pythontrace.diagsession");

            var driver = PythonToolsInstallPath.GetFile(ExternalProfilerDriverExe, typeof(PythonProfilingPackage).Assembly);

            var procInfo = new ProcessStartInfo(driver)
            {
                CreateNoWindow = false,
                Arguments      = string.Join(" ", new[] {
                    "-d",
                    ProcessOutput.QuoteSingleArgument(outPathDir),
                    "--",
                    ProcessOutput.QuoteSingleArgument(interpreter),
                    config.InterpreterArguments,
                    string.IsNullOrEmpty(config.ScriptName) ? "" : ProcessOutput.QuoteSingleArgument(config.ScriptName),
                    config.ScriptArguments
                }),
                WorkingDirectory = config.WorkingDirectory,
            };

            var proc = new Process {
                StartInfo = procInfo
            };
            var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));

            proc.EnableRaisingEvents = true;
            proc.Exited += (_, args) => {
                if (!File.Exists(Path.Combine(outPathDir, "Sample.dwjson")))
                {
                    MessageBox.Show(Strings.CannotFindGeneratedFile, Strings.ProductTitle);
                }
                else
                {
                    PackageTrace(outPathDir);
                    dte.ItemOperations.OpenFile(Path.Combine(outPathDir, "trace.diagsession"));
                }
            };
            proc.Start();
        }
コード例 #13
0
        public async Task Run()
        {
            var service = _project.Site.GetComponentModel().GetService <IInterpreterRegistryService>();

            IPythonInterpreterFactory factory;

            try {
                var baseInterp = service.FindInterpreter(_baseInterpreter);

                factory = await _project.CreateOrAddVirtualEnvironment(
                    service,
                    _create,
                    _virtualEnvPath,
                    baseInterp,
                    _useVEnv
                    );
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                WriteError(ex.Message);
                factory = null;
            }

            if (factory == null)
            {
                return;
            }

            var txt = PathUtils.GetAbsoluteFilePath(_project.ProjectHome, "requirements.txt");

            if (!_installRequirements || !File.Exists(txt))
            {
                return;
            }

            if (factory.PackageManager == null)
            {
                WriteError(
                    Strings.PackageManagementNotSupported_Package.FormatUI(PathUtils.GetFileOrDirectoryName(txt))
                    );
                return;
            }

            WriteOutput(Strings.RequirementsTxtInstalling.FormatUI(txt));
            if (await factory.PackageManager.InstallAsync(
                    PackageSpec.FromArguments("-r " + ProcessOutput.QuoteSingleArgument(txt)),
                    new VsPackageManagerUI(_project.Site),
                    CancellationToken.None
                    ))
            {
                WriteOutput(Strings.PackageInstallSucceeded.FormatUI(Path.GetFileName(txt)));
            }
            else
            {
                WriteOutput(Strings.PackageInstallFailed.FormatUI(Path.GetFileName(txt)));
            }
        }
コード例 #14
0
        private void SaveToFile(bool includeAnalysisLogs)
        {
            string initialPath = null;

            try {
                initialPath = PathUtils.GetAbsoluteFilePath(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    Strings.DiagnosticsWindow_DefaultFileName.FormatUI(DateTime.Now)
                    );
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
            }

            var path = Site.BrowseForFileSave(
                _window.Handle,
                Strings.DiagnosticsWindow_TextFileFilter,
                initialPath
                );

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            Cursor.Current = Cursors.WaitCursor;
            try {
                try {
                    TaskDialog.CallWithRetry(
                        _ => {
                        using (var log = new StreamWriter(path, false, new UTF8Encoding(false))) {
                            PyService.GetDiagnosticsLog(log, includeAnalysisLogs);
                        }
                    },
                        Site,
                        Strings.ProductTitle,
                        Strings.FailedToSaveDiagnosticInfo,
                        Strings.ErrorDetail,
                        Strings.Retry,
                        Strings.Cancel
                        );

                    if (File.Exists(path))
                    {
                        Process.Start(
                            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"),
                            "/select," + ProcessOutput.QuoteSingleArgument(path)
                            )?.Dispose();
                    }
                } catch (OperationCanceledException) {
                }
            } finally {
                Cursor.Current = Cursors.Arrow;
            }
        }
コード例 #15
0
        /// <summary>
        /// Creates language specific command line for starting the project with debigging.
        /// </summary>
        public string CreateCommandLineDebug(string startupFile, bool includeInterpreterArgs)
        {
            string interpArgs  = includeInterpreterArgs ? _project.GetProperty(PythonConstants.InterpreterArgumentsSetting) : null;
            string cmdLineArgs = _project.GetProperty(CommonConstants.CommandLineArguments) ?? string.Empty;

            return(string.Join(" ", new[] {
                interpArgs,
                ProcessOutput.QuoteSingleArgument(startupFile),
                cmdLineArgs
            }.Where(s => !string.IsNullOrEmpty(s))));
        }
コード例 #16
0
 public void AddArgumentAtStart(string argument)
 {
     if (string.IsNullOrEmpty(Arguments))
     {
         Arguments = ProcessOutput.QuoteSingleArgument(argument);
     }
     else
     {
         Arguments = ProcessOutput.QuoteSingleArgument(argument) + " " + Arguments;
     }
 }
コード例 #17
0
 public void AddArgumentAtEnd(string argument)
 {
     if (string.IsNullOrEmpty(Arguments))
     {
         Arguments = ProcessOutput.QuoteSingleArgument(argument);
     }
     else
     {
         Arguments += " " + ProcessOutput.QuoteSingleArgument(argument);
     }
 }
コード例 #18
0
        public async Task <bool> ExportExplicitSpecificationFileAsync(string envPath, string destinationSpecFilePath, ICondaEnvironmentManagerUI ui, CancellationToken ct)
        {
            var args = new[] {
                "list",
                "--explicit",
                "-p",
                ProcessOutput.QuoteSingleArgument(envPath),
            };

            return(await ExportAsync(envPath, destinationSpecFilePath, args, ui, ct));
        }
コード例 #19
0
        private static IEnumerable <string> QuotedArgumentsWithPackageName(IEnumerable <string> args, string package)
        {
            var quotedArgs = string.Join(" ", args.Select(a => ProcessOutput.QuoteSingleArgument(a))) + " ";

            if (Directory.Exists(package) || File.Exists(package))
            {
                yield return(quotedArgs + ProcessOutput.QuoteSingleArgument(package));
            }
            else
            {
                yield return(quotedArgs + package);
            }
        }
コード例 #20
0
        private static string GetArgs(LaunchConfiguration config)
        {
            var args = string.Join(" ", new[] {
                config.InterpreterArguments,
                config.ScriptName == null ? "" : ProcessOutput.QuoteSingleArgument(config.ScriptName),
                config.ScriptArguments
            }.Where(s => !string.IsNullOrEmpty(s)));

            if (config.Environment != null)
            {
                args = DoSubstitutions(config.Environment, args);
            }
            return(args);
        }
コード例 #21
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))
                {
                    for (int retries = 10; retries > 0; --retries)
                    {
                        try {
                            using (new FileStream(outPath, FileMode.Open, FileAccess.Read, FileShare.None)) { }
                            break;
                        } catch (IOException) {
                            Thread.Sleep(100);
                        }
                    }
                    dte.ItemOperations.OpenFile(outPath);
                }
            };

            session.AddProfile(outPath);

            process.StartProfiling(outPath);
            _profilingProcess     = process;
            _stopCommand.Enabled  = true;
            _startCommand.Enabled = false;
        }
コード例 #22
0
        public async Task <CondaCreateDryRunResult> PreviewCreateAsync(string newEnvNameOrPath, IEnumerable <PackageSpec> packageSpecs, CancellationToken ct)
        {
            using (await _working.LockAsync(ct)) {
                var args = new[] {
                    "create",
                    IsAbsolutePath(newEnvNameOrPath) ? "-p" : "-n",
                    ProcessOutput.QuoteSingleArgument(newEnvNameOrPath),
                    "-y",
                    "--dry-run",
                    "--json",
                }.Union(packageSpecs.Select(s => s.FullSpec));

                return(await DoPreviewOperationAsync(args, ct));
            }
        }
コード例 #23
0
        public async Task Run()
        {
            var service = _project.Site.GetComponentModel().GetService <IInterpreterRegistryService>();

            IPythonInterpreterFactory factory;

            try {
                factory = await _project.CreateOrAddVirtualEnvironment(
                    service,
                    _create,
                    _virtualEnvPath,
                    _baseInterpreter,
                    _useVEnv
                    );
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                WriteError(ex.Message);
                factory = null;
            }

            if (factory == null)
            {
                return;
            }

            var txt = PathUtils.GetAbsoluteFilePath(_project.ProjectHome, "requirements.txt");

            if (!_installRequirements || !File.Exists(txt))
            {
                return;
            }

            WriteOutput(Strings.RequirementsTxtInstalling.FormatUI(txt));
            if (await Pip.Install(
                    _project.Site,
                    factory,
                    "-r " + ProcessOutput.QuoteSingleArgument(txt),
                    false, // never elevate for a virtual environment
                    _output
                    ))
            {
                WriteOutput(Strings.PackageInstallSucceeded.FormatUI(Path.GetFileName(txt)));
            }
            else
            {
                WriteOutput(Strings.PackageInstallFailed.FormatUI(Path.GetFileName(txt)));
            }
        }
コード例 #24
0
        public async Task <bool> CreateFromEnvironmentFileAsync(string newEnvNameOrPath, string sourceEnvFilePath, ICondaEnvironmentManagerUI ui, CancellationToken ct)
        {
            bool success = false;

            using (await _working.LockAsync(ct)) {
                await EnsureActivatedAsync();

                var args = new[] {
                    "env",
                    "create",
                    IsAbsolutePath(newEnvNameOrPath) ? "-p" : "-n",
                    ProcessOutput.QuoteSingleArgument(newEnvNameOrPath),
                    "-f",
                    ProcessOutput.QuoteSingleArgument(sourceEnvFilePath),
                };

                var operation = "conda " + string.Join(" ", args);

                ui?.OnOperationStarted(this, operation);
                ui?.OnOutputTextReceived(this, Strings.CondaCreateStarted.FormatUI(newEnvNameOrPath));
                try {
                    if (!PathUtils.IsValidPath(newEnvNameOrPath))
                    {
                        ui?.OnErrorTextReceived(this, Strings.CondaCreateInvalidNameOrPath.FormatUI(newEnvNameOrPath));
                        success = false;
                        return(success);
                    }

                    if (!File.Exists(sourceEnvFilePath))
                    {
                        ui?.OnErrorTextReceived(this, Strings.CondaFileNotFoundError.FormatUI(sourceEnvFilePath));
                        success = false;
                        return(success);
                    }

                    success = await DoOperationAsync(args, ui, ct);

                    return(success);
                } finally {
                    var msg = success ? Strings.CondaCreateSuccess : Strings.CondaCreateFailed;
                    ui?.OnOutputTextReceived(this, msg.FormatUI(newEnvNameOrPath));
                    ui?.OnOperationFinished(this, operation, success);
                }
            }
        }
コード例 #25
0
 public void ArgumentQuoting()
 {
     foreach (var testCase in new[] {
         new { Source = "Abc", Expected = "Abc" },
         new { Source = "Abc 123", Expected = "\"Abc 123\"" },
         // A"B"C => "A\"B\"C"
         new { Source = "A\"B\"C", Expected = "\"A\\\"B\\\"C\"" },
         // "AB\"C" => "AB\"C"
         new { Source = "\"AB\\\"C\"", Expected = "\"AB\\\"C\"" },
         // "AB"C" => "\"AB\"C\""
         new { Source = "\"AB\"C\"", Expected = "\"\\\"AB\\\"C\\\"\"" },
         // C:\Program Files\Application Path\ => "C:\Program Files\Application Path\\"
         new { Source = @"C:\Program Files\Application Path\", Expected = "\"C:\\Program Files\\Application Path\\\\\"" },
         // C:\Program Files\Application Path => "C:\Program Files\Application Path"
         new { Source = @"C:\Program Files\Application Path", Expected = "\"C:\\Program Files\\Application Path\"" },
     }) {
         Assert.AreEqual(testCase.Expected, ProcessOutput.QuoteSingleArgument(testCase.Source), string.Format("Source:<{0}>", testCase.Source));
     }
 }
コード例 #26
0
        public async Task Run()
        {
            var service = _project.Site.GetComponentModel().GetService <IInterpreterOptionsService>();

            var factory = await _project.CreateOrAddVirtualEnvironment(
                service,
                _create,
                _virtualEnvPath,
                _baseInterpreter,
                _useVEnv
                );

            if (factory == null)
            {
                return;
            }

            var txt = CommonUtils.GetAbsoluteFilePath(_project.ProjectHome, "requirements.txt");

            if (!_installRequirements || !File.Exists(txt))
            {
                return;
            }

            WriteOutput(SR.RequirementsTxtInstalling, txt);
            if (await Pip.Install(
                    _project.Site,
                    factory,
                    "-r " + ProcessOutput.QuoteSingleArgument(txt),
                    false, // never elevate for a virtual environment
                    _output
                    ))
            {
                WriteOutput(SR.PackageInstallSucceeded, Path.GetFileName(txt));
            }
            else
            {
                WriteOutput(SR.PackageInstallFailed, Path.GetFileName(txt));
            }
        }
コード例 #27
0
        private void SaveToFile(bool includeAnalysisLogs)
        {
            var path = PyService.Site.BrowseForFileSave(
                _window.Handle,
                Strings.DiagnosticsWindow_TextFileFilter,
                PathUtils.GetAbsoluteFilePath(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    Strings.DiagnosticsWindow_DefaultFileName.FormatUI(DateTime.Now)
                    )
                );

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            Cursor.Current = Cursors.WaitCursor;
            try {
                try {
                    var log = PyService.GetDiagnosticsLog(includeAnalysisLogs);
                    TaskDialog.CallWithRetry(
                        _ => File.WriteAllText(path, log),
                        PyService.Site,
                        Strings.ProductTitle,
                        Strings.FailedToSaveDiagnosticInfo,
                        Strings.ErrorDetail,
                        Strings.Retry,
                        Strings.Cancel
                        );

                    Process.Start("explorer.exe", "/select," + ProcessOutput.QuoteSingleArgument(path)).Dispose();
                } catch (OperationCanceledException) {
                }
            } finally {
                Cursor.Current = Cursors.Arrow;
            }
        }
コード例 #28
0
        public async Task InstallPackagesAsync()
        {
            WriteOutput(Strings.RequirementsTxtInstalling.FormatUI(_reqsPath));
            bool success = false;

            try {
                var ui = new VsPackageManagerUI(_site);
                if (!_pm.IsReady)
                {
                    await _pm.PrepareAsync(ui, CancellationToken.None);
                }
                success = await _pm.InstallAsync(
                    PackageSpec.FromArguments("-r " + ProcessOutput.QuoteSingleArgument(_reqsPath)),
                    ui,
                    CancellationToken.None
                    );
            } catch (InvalidOperationException ex) {
                WriteOutput(ex.Message);
                throw;
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                WriteOutput(ex.Message);
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
                throw;
            } finally {
                if (success)
                {
                    WriteOutput(Strings.PackageInstallSucceeded.FormatUI(Path.GetFileName(_reqsPath)));
                }
                else
                {
                    var msg = Strings.PackageInstallFailed.FormatUI(Path.GetFileName(_reqsPath));
                    WriteOutput(msg);
                    throw new ApplicationException(msg);
                }
            }
        }
コード例 #29
0
ファイル: EasyInstall.cs プロジェクト: zuokaihuang/PTVS
        private static async Task <int> ContinueRun(
            IPythonInterpreterFactory factory,
            Redirector output,
            bool elevate,
            params string[] cmd
            )
        {
            bool isScript;
            var  easyInstallPath = GetEasyInstallPath(factory, out isScript);

            if (easyInstallPath == null)
            {
                throw new FileNotFoundException("Cannot find setuptools ('easy_install.exe')");
            }

            var args = cmd.ToList();

            args.Insert(0, "--always-copy");
            args.Insert(0, "--always-unzip");
            if (isScript)
            {
                args.Insert(0, ProcessOutput.QuoteSingleArgument(easyInstallPath));
                easyInstallPath = factory.Configuration.InterpreterPath;
            }
            using (var proc = ProcessOutput.Run(
                       easyInstallPath,
                       args,
                       factory.Configuration.PrefixPath,
                       UnbufferedEnv,
                       false,
                       output,
                       false,
                       elevate
                       )) {
                return(await proc);
            }
        }
コード例 #30
0
        private static string BuildArguments(IEnumerable <string> values)
        {
            // Examples of valid results:
            // "C:\My Folder\"
            // C:\MyFolder\MyFile.txt /e:"Source Code (text) Editor"
            //
            // Examples of invalid results:
            // C:\My Folder
            // C:\MyFolder\MyFile.txt "/e:Source Code (text) Editor"
            // C:\MyFolder\MyFile.txt /e: "Source Code (text) Editor"
            // C:\MyFolder\MyFile.txt /e:Source Code (text) Editor
            StringBuilder args        = new StringBuilder();
            bool          insertSpace = false;

            foreach (var val in values)
            {
                if (insertSpace)
                {
                    args.Append(" ");
                }

                if (val.EndsWith(":"))
                {
                    args.Append(val);
                    // no space after a switch that takes a value
                    insertSpace = false;
                }
                else
                {
                    args.Append(ProcessOutput.QuoteSingleArgument(val));
                    insertSpace = true;
                }
            }

            return(args.ToString());
        }