コード例 #1
0
        private async Task UpdateIsReadyAsync(bool alreadyHasLock, CancellationToken cancellationToken)
        {
            IDisposable workingLock = null;

            if (!alreadyHasLock)
            {
                try {
                    workingLock = await _working.LockAsync(cancellationToken);
                } catch (ObjectDisposedException ex) {
                    throw new OperationCanceledException("Package manager has already closed", ex);
                }
            }
            try {
                using (var proc = ProcessOutput.Run(
                           _factory.Configuration.InterpreterPath,
                           _commands.CheckIsReady(),
                           _factory.Configuration.PrefixPath,
                           UnbufferedEnv,
                           false,
                           null
                           )) {
                    try {
                        IsReady = (await proc == 0);
                    } catch (OperationCanceledException) {
                        IsReady = false;
                        return;
                    }
                }
            } finally {
                workingLock?.Dispose();
            }
        }
コード例 #2
0
ファイル: ProcessOutputTests.cs プロジェクト: wqhbuaa/PTVS
        public void ProcessOutputEncoding()
        {
            var testDataPath = TestData.GetTempPath();
            var testData     = Path.Combine(testDataPath, "ProcessOutputEncoding.txt");

            for (int i = 1; File.Exists(testData); ++i)
            {
                testData = Path.Combine(testDataPath, string.Format("ProcessOutputEncoding{0}.txt", i));
            }

            const string testString = "‚‡”¾‰œðÝ";

            File.WriteAllText(testData, testString, new UTF8Encoding(false));

            using (var output = ProcessOutput.Run(
                       "cmd.exe",
                       new[] { "/C", "type " + Path.GetFileName(testData) },
                       testDataPath,
                       null,
                       false,
                       null,
                       outputEncoding: new UTF8Encoding(false)
                       )) {
                output.Wait();
                Assert.AreEqual(0, output.ExitCode);

                foreach (var line in output.StandardOutputLines.Concat(output.StandardErrorLines))
                {
                    Console.WriteLine(line);
                }

                Assert.AreEqual(testString, output.StandardOutputLines.Single());
            }
        }
コード例 #3
0
ファイル: Pip.cs プロジェクト: zuokaihuang/PTVS
        private static ProcessOutput Run(
            IPythonInterpreterFactory factory,
            Redirector output,
            bool elevate,
            params string[] cmd
            )
        {
            factory.ThrowIfNotRunnable("factory");

            IEnumerable <string> args;

            if (factory.Configuration.Version >= SupportsDashMPip)
            {
                args = new[] { "-m", "pip" }.Concat(cmd);
            }
            else
            {
                // Manually quote the code, since we are passing false to
                // quoteArgs below.
                args = new[] { "-c", "\"import pip; pip.main()\"" }.Concat(cmd);
            }

            return(ProcessOutput.Run(
                       factory.Configuration.InterpreterPath,
                       args,
                       factory.Configuration.PrefixPath,
                       UnbufferedEnv,
                       false,
                       output,
                       quoteArgs: false,
                       elevate: elevate
                       ));
        }
コード例 #4
0
        /// <summary>
        /// Checks whether a given package is installed and satisfies the
        /// version specification.
        /// </summary>
        /// <param name="package">
        /// Name, and optionally the version of the package to install, in
        /// setuptools format.
        /// </param>
        /// <remarks>
        /// This method requires setuptools to be installed to correctly detect
        /// packages and verify their versions. If setuptools is not available,
        /// the method will always return <c>false</c> for any package name.
        /// </remarks>
        public static async Task <bool> IsInstalled(IPythonInterpreterFactory factory, string package)
        {
            if (!factory.IsRunnable())
            {
                return(false);
            }

            var code = string.Format("import pkg_resources; pkg_resources.require('{0}')", package);

            using (var proc = ProcessOutput.Run(
                       factory.Configuration.InterpreterPath,
                       new[] { "-c", code },
                       factory.Configuration.PrefixPath,
                       UnbufferedEnv,
                       visible: false,
                       redirector: null,
                       quoteArgs: true)
                   ) {
                try {
                    return(await proc == 0);
                } catch (NoInterpretersException) {
                    return(false);
                }
            }
        }
コード例 #5
0
        private async Task <bool> DoOperationAsync(
            IEnumerable <string> args,
            ICondaEnvironmentManagerUI ui,
            CancellationToken ct,
            Redirector redirector = null
            )
        {
            bool success = false;

            try {
                using (var output = ProcessOutput.Run(
                           _condaPath,
                           args,
                           Path.GetDirectoryName(_condaPath),
                           UnbufferedEnv,
                           false,
                           redirector ?? CondaEnvironmentManagerUIRedirector.Get(this, ui),
                           quoteArgs: false,
                           elevate: false
                           )) {
                    if (!output.IsStarted)
                    {
                        return(false);
                    }
                    var exitCode = await output;
                    success = exitCode == 0;
                }
                return(success);
            } catch (IOException) {
                return(false);
            }
        }
コード例 #6
0
ファイル: CondaPackageManager.cs プロジェクト: PeezoSlug/PTVS
        private async Task UpdateIsReadyAsync(bool alreadyHasLock, CancellationToken cancellationToken)
        {
            var args        = new[] { "-h" };
            var workingLock = alreadyHasLock ? null : await _working.LockAsync(cancellationToken);

            try {
                using (var proc = ProcessOutput.Run(
                           _condaPath,
                           args,
                           _factory.Configuration.GetPrefixPath(),
                           UnbufferedEnv,
                           false,
                           null
                           )) {
                    try {
                        IsReady = (await proc == 0);
                    } catch (OperationCanceledException) {
                        IsReady = false;
                        return;
                    }
                }
            } finally {
                workingLock?.Dispose();
            }
        }
コード例 #7
0
        public async Task <DateTime?> GetLastCommitDateAsync(string repoFolderPath, string branch)
        {
            var arguments = new List <string>()
            {
                "log", "-1", "--date=iso"
            };

            if (!string.IsNullOrEmpty(branch))
            {
                arguments.Add(branch);
            }

            using (var output = ProcessOutput.Run(_gitExeFilePath, arguments, repoFolderPath, GetEnvironment(), false, null)) {
                await output;
                foreach (var line in output.StandardOutputLines)
                {
                    // Line with date starts with 'Date'. Example:
                    // Date:   2016-07-28 10:03:07 +0200
                    if (line.StartsWith("Date:"))
                    {
                        try {
                            var text = line.Substring("Date:".Length);
                            return(Convert.ToDateTime(text).ToUniversalTime());
                        } catch (FormatException) {
                            return(null);
                        }
                    }
                }
            }
            return(null);
        }
コード例 #8
0
        private async Task CreateVenvWithoutPipThenInstallPip()
        {
            RemoveExistingVenv();

            _redirector.WriteLine(Strings.InstallingCookiecutterCreateEnvWithoutPip.FormatUI(_envFolderPath));
            var output = ProcessOutput.Run(
                _interpreter.InterpreterExecutablePath,
                new[] { "-m", "venv", _envFolderPath, "--without-pip" },
                null,
                null,
                false,
                _redirector
                );

            await WaitForOutput(_interpreter.InterpreterExecutablePath, output);

            _redirector.WriteLine(Strings.InstallingCookiecutterInstallPip.FormatUI(_envFolderPath));
            var pipScriptPath = PythonToolsInstallPath.GetFile("pip_downloader.py");

            output = ProcessOutput.Run(
                _envInterpreterPath,
                new[] { pipScriptPath },
                _interpreter.PrefixPath,
                null,
                false,
                _redirector
                );
            await WaitForOutput(_interpreter.InterpreterExecutablePath, output);
        }
コード例 #9
0
        public async Task <string> CloneAsync(string repoUrl, string targetParentFolderPath)
        {
            Directory.CreateDirectory(targetParentFolderPath);

            string localTemplateFolder = GetClonedFolder(repoUrl, targetParentFolderPath);

            if (Directory.Exists(localTemplateFolder))
            {
                ShellUtils.DeleteDirectory(localTemplateFolder);
            }

            var arguments = new string[] { "clone", repoUrl };

            using (var output = ProcessOutput.Run(_gitExeFilePath, arguments, targetParentFolderPath, null, false, _redirector)) {
                await output;

                var r = new ProcessOutputResult()
                {
                    ExeFileName = _gitExeFilePath,
                    ExitCode    = output.ExitCode,
                };

                if (r.ExitCode < 0)
                {
                    throw new ProcessException(r);
                }

                if (!Directory.Exists(localTemplateFolder))
                {
                    throw new ProcessException(r);
                }

                return(localTemplateFolder);
            }
        }
コード例 #10
0
        private async Task <bool> DoOperationAsync(
            IEnumerable <string> args,
            ICondaEnvironmentManagerUI ui,
            CancellationToken ct,
            Redirector redirector = null
            )
        {
            bool success = false;

            try {
                var envVars = await GetEnvironmentVariables();

                // Note: conda tries to write temporary files to the current working directory
                using (var output = ProcessOutput.Run(
                           CondaPath,
                           args,
                           Path.GetTempPath(),
                           envVars,
                           false,
                           redirector ?? CondaEnvironmentManagerUIRedirector.Get(this, ui),
                           quoteArgs: false,
                           elevate: false
                           )) {
                    if (!output.IsStarted)
                    {
                        return(false);
                    }
                    var exitCode = await output;
                    success = exitCode == 0;
                }
                return(success);
            } catch (IOException) {
                return(false);
            }
        }
コード例 #11
0
        private async Task UpdateIsReadyAsync(bool alreadyHasLock, CancellationToken cancellationToken)
        {
            var args = _extraInterpreterArgs
                       .Concat(new[] { "-c", "import pip" });

            var workingLock = alreadyHasLock ? null : await _working.LockAsync(cancellationToken);

            try {
                using (var proc = ProcessOutput.Run(
                           _factory.Configuration.InterpreterPath,
                           args,
                           _factory.Configuration.PrefixPath,
                           UnbufferedEnv,
                           false,
                           null
                           )) {
                    try {
                        IsReady = (await proc == 0);
                    } catch (OperationCanceledException) {
                        IsReady = false;
                        return;
                    }
                }
            } finally {
                workingLock?.Dispose();
            }
        }
コード例 #12
0
        private async Task <CondaCreateDryRunResult> DoPreviewOperationAsync(IEnumerable <string> args, CancellationToken ct)
        {
            using (var output = ProcessOutput.Run(CondaPath, args.ToArray(), Path.GetDirectoryName(CondaPath), _activatedEnvironmentVariables, false, null)) {
                if (!output.IsStarted)
                {
                    return(null);
                }

                // It is safe to kill a conda dry run
                var exitCode = await WaitAndKillOnCancelAsync(output, ct);

                if (exitCode >= 0)
                {
                    var json = string.Join(Environment.NewLine, output.StandardOutputLines);
                    try {
                        return(JsonConvert.DeserializeObject <CondaCreateDryRunResult>(json));
                    } catch (JsonException ex) {
                        Debug.WriteLine("Failed to parse: {0}".FormatInvariant(ex.Message));
                        Debug.WriteLine(json);
                        return(null);
                    }
                }
            }

            return(null);
        }
コード例 #13
0
        public async Task <bool> ExecuteAsync(string arguments, IPackageManagerUI ui, CancellationToken cancellationToken)
        {
            AbortOnInvalidConfiguration();
            await AbortIfNotReady(cancellationToken);

            using (await _working.LockAsync(cancellationToken)) {
                bool   success = false;
                string args;

                if (!SupportsDashMPip)
                {
                    args = "-c \"import pip; pip.main()\" ";
                }
                else
                {
                    args = "-m pip ";
                }

                args += arguments;

                var operation = args;
                ui?.OnOutputTextReceived(operation);
                ui?.OnOperationStarted(Strings.ExecutingCommandStarted.FormatUI(arguments));

                try {
                    using (var output = ProcessOutput.Run(
                               _factory.Configuration.InterpreterPath,
                               new[] { args },
                               _factory.Configuration.PrefixPath,
                               UnbufferedEnv,
                               false,
                               PackageManagerUIRedirector.Get(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 pip is missing
                        UpdateIsReadyAsync(true, CancellationToken.None).DoNotWait();
                    }

                    var msg = success ? Strings.ExecutingCommandSucceeded : Strings.ExecutingCommandFailed;
                    ui?.OnOutputTextReceived(msg.FormatUI(arguments));
                    ui?.OnOperationFinished(operation, success);
                    await CacheInstalledPackagesAsync(true, cancellationToken);
                }
            }
        }
コード例 #14
0
ファイル: VirtualEnv.cs プロジェクト: zyxws012/PTVS
        private static async Task ContinueCreate(IServiceProvider provider, IPythonInterpreterFactory factory, string path, bool useVEnv, Redirector output)
        {
            path = PathUtils.TrimEndSeparator(path);
            var name = Path.GetFileName(path);
            var dir  = Path.GetDirectoryName(path);

            if (output != null)
            {
                output.WriteLine(Strings.VirtualEnvCreating.FormatUI(path));
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }

            // Ensure the target directory exists.
            Directory.CreateDirectory(dir);

            using (var proc = ProcessOutput.Run(
                       factory.Configuration.InterpreterPath,
                       new[] { "-m", useVEnv ? "venv" : "virtualenv", name },
                       dir,
                       UnbufferedEnv,
                       false,
                       output
                       )) {
                var exitCode = await proc;

                if (output != null)
                {
                    if (exitCode == 0)
                    {
                        output.WriteLine(Strings.VirtualEnvCreationSucceeded.FormatUI(path));
                    }
                    else
                    {
                        output.WriteLine(Strings.VirtualEnvCreationFailedExitCode.FormatUI(path, exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate)
                    {
                        output.ShowAndActivate();
                    }
                    else
                    {
                        output.Show();
                    }
                }

                if (exitCode != 0 || !Directory.Exists(path))
                {
                    throw new InvalidOperationException(Strings.VirtualEnvCreationFailed.FormatUI(path));
                }
            }
        }
コード例 #15
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);
                }
            }
        }
コード例 #16
0
ファイル: PipExtensionProvider.cs プロジェクト: krus/PTVS
        public async Task UninstallPackage(string package)
        {
            List <string> args;

            if (_factory.Configuration.Version < SupportsDashMPip)
            {
                args = new List <string> {
                    "-c", "import pip; pip.main()", "uninstall", "-y"
                };
            }
            else
            {
                args = new List <string> {
                    "-m", "pip", "uninstall", "-y"
                };
            }

            using (await WaitAndLockPip()) {
                OnOperationStarted(string.Format(Resources.UninstallingPackageStarted, package));
                using (var output = ProcessOutput.Run(
                           _factory.Configuration.InterpreterPath,
                           QuotedArgumentsWithPackageName(args, package),
                           _factory.Configuration.PrefixPath,
                           UnbufferedEnv,
                           false,
                           _output,
                           quoteArgs: false,
                           elevate: ShouldElevate
                           )) {
                    if (!output.IsStarted)
                    {
                        OnOperationFinished(string.Format(Resources.UninstallingPackageFailed, package));
                        return;
                    }
                    bool success = true;
                    try {
                        var exitCode = await output;
                        if (exitCode != 0)
                        {
                            // Double check whether the package has actually
                            // been uninstalled, to avoid reporting errors
                            // where, for all practical purposes, there is no
                            // error.
                            if ((await GetInstalledPackagesAsync()).Any(p => p.Name == package))
                            {
                                success = false;
                                throw new PipException(Resources.UninstallationFailed);
                            }
                        }
                    } finally {
                        OnOperationFinished(string.Format(
                                                success ? Resources.UninstallingPackageSuccess : Resources.UninstallingPackageFailed,
                                                package
                                                ));
                    }
                }
            }
        }
コード例 #17
0
        private async Task <bool> DownloadTypings(IEnumerable <string> packages, Redirector redirector)
        {
            if (!packages.Any())
            {
                return(true);
            }

            string tsdPath = await EnsureTsdInstalled();

            if (string.IsNullOrEmpty(tsdPath))
            {
                if (redirector != null)
                {
                    redirector.WriteErrorLine(SR.GetString(SR.TsdNotInstalledError));
                }
                return(false);
            }

            using (var process = ProcessOutput.Run(
                       tsdPath,
                       TsdInstallArguments(packages),
                       _pathToRootProjectDirectory,
                       null,
                       false,
                       redirector,
                       quoteArgs: true)) {
                if (!process.IsStarted)
                {
                    // Process failed to start, and any exception message has
                    // already been sent through the redirector
                    if (redirector != null)
                    {
                        redirector.WriteErrorLine("could not start tsd");
                    }
                    return(false);
                }
                var i = await process;
                if (i == 0)
                {
                    if (redirector != null)
                    {
                        redirector.WriteLine(SR.GetString(SR.TsdInstallCompleted));
                    }
                    return(true);
                }
                else
                {
                    process.Kill();
                    if (redirector != null)
                    {
                        redirector.WriteErrorLine(SR.GetString(SR.TsdInstallErrorOccurred));
                    }
                    return(false);
                }
            }
        }
コード例 #18
0
        public string Run(IEnumerable <TestCase> tests, string coveragePath)
        {
            string ouputFile = "";

            try {
                DetachFromSillyManagedProcess(_app, _debugMode);

                var env = InitializeEnvironment(tests);
                ouputFile = GetJunitXmlFile();
                var arguments = GetArguments(tests, ouputFile, coveragePath, _projectSettings);

                var testRedirector = new TestRedirector(_frameworkHandle);

                using (var proc = ProcessOutput.Run(
                           _projectSettings.InterpreterPath,
                           arguments,
                           _projectSettings.WorkingDirectory,
                           env,
                           visible: false,
                           testRedirector,
                           quoteArgs: true,
                           elevate: false,
                           System.Text.Encoding.UTF8,
                           System.Text.Encoding.UTF8
                           )) {
                    LogInfo("cd " + _projectSettings.WorkingDirectory);
                    LogInfo("set " + _projectSettings.PathEnv + "=" + env[_projectSettings.PathEnv]);
                    LogInfo(proc.Arguments);

                    if (!proc.ExitCode.HasValue)
                    {
                        try {
                            if (_debugMode != PythonDebugMode.None)
                            {
                                AttachDebugger(_app, proc, _debugMode, _debugSecret, _debugPort);
                            }

                            proc.Wait();
                        } catch (COMException ex) {
                            Error(Strings.Test_ErrorConnecting);
                            DebugError(ex.ToString());
                            try {
                                proc.Kill();
                            } catch (InvalidOperationException) {
                                // Process has already exited
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Error(e.ToString());
            }

            return(ouputFile);
        }
コード例 #19
0
        private void InitConnection(string serverScriptPath)
        {
            // Client sends requests, receives responses and events
            // Server receives requests, sends back responses and events
            // Client creates the socket on an available port,
            // passes the port number to the server which connects back to it.
            var portNum = StartClient();

            if (!StartPythonProcessManually)
            {
                Assert.IsTrue(File.Exists(serverScriptPath), "Python test data script '{0}' was not found.".FormatUI(serverScriptPath));

                var workingDir = Path.GetDirectoryName(serverScriptPath);

                var searchPaths = new HashSet <string>();
                searchPaths.Add(PtvsdSearchPath);
                searchPaths.Add(workingDir);

                var env = new List <KeyValuePair <string, string> >();
                env.Add(new KeyValuePair <string, string>("PYTHONPATH", string.Join(";", searchPaths)));

                var arguments = new List <string>();
                arguments.Add(serverScriptPath);
                arguments.Add("-r");
                arguments.Add(portNum.ToString());
                using (var proc = ProcessOutput.Run(
                           PythonPaths.Python27.InterpreterPath,
                           arguments,
                           workingDir,
                           env,
                           false,
                           null
                           )) {
                    if (proc.ExitCode.HasValue)
                    {
                        // Process has already exited
                        proc.Wait();
                        if (proc.StandardErrorLines.Any())
                        {
                            Assert.Fail(String.Join(Environment.NewLine, proc.StandardErrorLines));
                        }
                    }
                }
            }
            else
            {
                // Check the port number variable assigned above if you want to
                // start the python process manually
                Debugger.Break();
            }

            _connected.WaitOne();
        }
コード例 #20
0
ファイル: FastCgiTests2x.cs プロジェクト: PeezoSlug/PTVS
 public void StartServer()
 {
     _process = ProcessOutput.Run(
         IisExpressPath,
         new[] { "/config:" + Path.Combine(_dir, "applicationHost.config"), "/systray:false" },
         null,
         null,
         false,
         new OutputRedirector("IIS")
         );
     Console.WriteLine("Server started: {0}", _process.Arguments);
 }
コード例 #21
0
ファイル: NpmWorker.cs プロジェクト: kevinnet37/nodejstools
        // TODO: This is duplicated from Npm project
        // We should integrate this into the NpmCommander
        internal static async Task <IEnumerable <string> > ExecuteNpmCommandAsync(
            string pathToNpm,
            string executionDirectory,
            string[] arguments,
            bool visible          = false,
            Redirector redirector = null)
        {
            IEnumerable <string> standardOutputLines = null;

            using (var process = ProcessOutput.Run(
                       pathToNpm,
                       arguments,
                       executionDirectory,
                       /*env*/ null,
                       visible,
                       redirector,
                       quoteArgs: false,
                       outputEncoding: redirector == null ? null : Encoding.UTF8))
            {
                var whnd = process.WaitHandle;
                if (whnd == null)
                {
                    // Process failed to start, and any exception message has
                    // already been sent through the redirector
                    redirector?.WriteErrorLine("Error - cannot start npm");
                }
                else
                {
                    var finished = await Task.Run(() => whnd.WaitOne());

                    if (finished)
                    {
                        Debug.Assert(process.ExitCode.HasValue, "npm process has not really exited");
                        // there seems to be a case when we're signalled as completed, but the
                        // process hasn't actually exited
                        process.Wait();
                        if (process.StandardOutputLines != null)
                        {
                            standardOutputLines = process.StandardOutputLines.ToList();
                        }
                    }
                    else
                    {
                        process.Kill();
                        redirector?.WriteErrorLine("\r\n==== npm command cancelled ====\r\n\r\n");

                        throw new OperationCanceledException();
                    }
                }
            }
            return(standardOutputLines);
        }
コード例 #22
0
        private static async Task <bool> CompileAsync(string arguments, string workingDir, Redirector redirector)
        {
            Debug.Assert(!string.IsNullOrEmpty(arguments), $"{nameof(arguments)} should not be empty.");

            var pathToTsc = Path.Combine(TypeScriptCompilerLocator.GetDefaultVersion(), CompilerExe);

            redirector?.WriteLine($"=== {Resources.TscBuildStarted}: {pathToTsc} {arguments} ===");

            using (var process = ProcessOutput.Run(
                       pathToTsc,
                       new[] { arguments },
                       workingDir,
                       env: null,
                       visible: false,
                       redirector: redirector,
                       quoteArgs: false,
                       outputEncoding: Encoding.UTF8))
            {
                var whnd = process.WaitHandle;
                if (whnd == null)
                {
                    // Process failed to start, and any exception message has
                    // already been sent through the redirector
                    redirector.WriteErrorLine(string.Format(Resources.TscBuildError, pathToTsc));
                    return(false);
                }
                else
                {
                    var finished = await Task.Run(() => whnd.WaitOne());

                    if (finished)
                    {
                        Debug.Assert(process.ExitCode.HasValue, "tsc.exe process has not really exited");
                        // there seems to be a case when we're signalled as completed, but the
                        // process hasn't actually exited
                        process.Wait();

                        redirector.WriteErrorLine($"==== {Resources.TscBuildCompleted} ====");

                        return(process.ExitCode == 0);
                    }
                    else
                    {
                        process.Kill();
                        redirector.WriteErrorLine($"==== {Resources.TscBuildCanceled} ====");

                        return(false);
                    }
                }
            }
        }
コード例 #23
0
ファイル: PipPackageManager.cs プロジェクト: int19h/PTVS
        public async Task <bool> ExecuteAsync(string arguments, IPackageManagerUI ui, CancellationToken cancellationToken)
        {
            AbortOnInvalidConfiguration();
            await AbortIfNotReady(cancellationToken);

            using (await _working.LockAsync(cancellationToken)) {
                bool success = false;

                var args      = string.Join(" ", _commands.Base().Select(ProcessOutput.QuoteSingleArgument)) + " " + arguments;
                var operation = args.Trim();
                ui?.OnOutputTextReceived(this, operation);
                ui?.OnOperationStarted(this, Strings.ExecutingCommandStarted.FormatUI(arguments));

                var envVars = await GetEnvironmentVariables();

                try {
                    using (var output = ProcessOutput.Run(
                               _factory.Configuration.InterpreterPath,
                               new[] { args.Trim() },
                               _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 pip is missing
                        UpdateIsReadyAsync(true, CancellationToken.None).DoNotWait();
                    }

                    var msg = success ? Strings.ExecutingCommandSucceeded : Strings.ExecutingCommandFailed;
                    ui?.OnOutputTextReceived(this, msg.FormatUI(arguments));
                    ui?.OnOperationFinished(this, operation, success);
                    await CacheInstalledPackagesAsync(true, false, cancellationToken);
                }
            }
        }
コード例 #24
0
ファイル: PipPackageManager.cs プロジェクト: vyktor90/PTVS
        public async Task <bool> InstallAsync(PackageSpec package, IPackageManagerUI ui, CancellationToken cancellationToken)
        {
            AbortOnInvalidConfiguration();
            await AbortIfNotReady(cancellationToken);

            bool success = false;

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

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

                try {
                    using (var output = ProcessOutput.Run(
                               _factory.Configuration.InterpreterPath,
                               args,
                               _factory.Configuration.PrefixPath,
                               UnbufferedEnv,
                               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 pip 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);
                }
            }
        }
コード例 #25
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;
     }
 }
コード例 #26
0
        public async Task InstallPackage()
        {
            _redirector.WriteLine(Strings.InstallingCookiecutterInstallPackages.FormatUI(_envFolderPath));
            var output = ProcessOutput.Run(
                _envInterpreterPath,
                new[] { "-m", "pip", "install", "cookiecutter<1.5" },
                null,
                null,
                false,
                _redirector
                );

            await WaitForOutput(_envInterpreterPath, output);
        }
コード例 #27
0
ファイル: CookiecutterClient.cs プロジェクト: int19h/PTVS
        private async Task CreateVenvWithoutPipThenInstallPip()
        {
            // check for redirection
            await UpdateEnvPathForRedirection(_expectedEnvFolderPath);

            // The venv is not guaranteed to be created where expected, see GetRealPath() for more information.

            // Also, Python has a bug (https://bugs.python.org/issue45337) where it doesn't
            // keep track of the real location of the redirected venv when creating a venv with pip installed.
            // In this case, the call to python.exe will have an exit code of 106.

            // Therefore, the workaround is the following:
            // 1. Create the venv WITHOUT PIP every time
            // 2. Run python and check os.path.realpath against the expected venv path
            // 3. If the real path comes back different, that's the real venv path.
            // 5. Install pip using python.exe and the real venv path.

            RemoveExistingVenv(_envFolderPath);

            // create the venv without pip installed
            _redirector.WriteLine(Strings.InstallingCookiecutterCreateEnvWithoutPip.FormatUI(_expectedEnvFolderPath));
            var output = ProcessOutput.Run(
                _interpreter.InterpreterExecutablePath,
                new[] { "-m", "venv", _expectedEnvFolderPath, "--without-pip" },
                null,
                null,
                false,
                _redirector
                );

            await WaitForOutput(_interpreter.InterpreterExecutablePath, output);

            // If we get here, the environment was created successfully.
            // Check for redirection again, overwriting the existing value if there is
            await UpdateEnvPathForRedirection(_expectedEnvFolderPath, true);

            // install pip in the new environment, wherever it is
            _redirector.WriteLine(Strings.InstallingCookiecutterInstallPip.FormatUI(_envFolderPath));
            var pipScriptPath = PythonToolsInstallPath.GetFile("pip_downloader.py");

            output = ProcessOutput.Run(
                _envInterpreterPath,
                new[] { pipScriptPath },
                _interpreter.PrefixPath,
                null,
                false,
                _redirector
                );
            await WaitForOutput(_interpreter.InterpreterExecutablePath, output);
        }
コード例 #28
0
ファイル: Pip.cs プロジェクト: zuokaihuang/PTVS
        public static async Task InstallPip(IServiceProvider provider, IPythonInterpreterFactory factory, bool elevate, Redirector output = null)
        {
            factory.ThrowIfNotRunnable("factory");

            var pipDownloaderPath = PythonToolsInstallPath.GetFile("pip_downloader.py");

            if (output != null)
            {
                output.WriteLine(Strings.PipInstalling);
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }
            using (var proc = ProcessOutput.Run(
                       factory.Configuration.InterpreterPath,
                       new[] { pipDownloaderPath },
                       factory.Configuration.PrefixPath,
                       null,
                       false,
                       output,
                       elevate: elevate
                       )) {
                var exitCode = await proc;
                if (output != null)
                {
                    if (exitCode == 0)
                    {
                        output.WriteLine(Strings.PipInstallSucceeded);
                    }
                    else
                    {
                        output.WriteLine(Strings.PipInstallFailedExitCode.FormatUI(exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                    {
                        output.ShowAndActivate();
                    }
                    else
                    {
                        output.Show();
                    }
                }
            }
        }
コード例 #29
0
        public async Task MergeAsync(string repoFolderPath)
        {
            var arguments = new string[] { "merge" };

            using (var output = ProcessOutput.Run(_gitExeFilePath, arguments, repoFolderPath, GetEnvironment(), false, _redirector)) {
                if (await output < 0)
                {
                    throw new ProcessException(new ProcessOutputResult()
                    {
                        ExeFileName = _gitExeFilePath,
                        ExitCode    = output.ExitCode,
                    });
                }
            }
        }
コード例 #30
0
ファイル: FastCgiTests.cs プロジェクト: krus/PTVS
 private Action CollectStaticFiles(string location)
 {
     return(() => {
         using (var p = ProcessOutput.Run(
                    InterpreterPath,
                    new[] { Path.Combine(location, "manage.py"), "collectstatic", "--noinput" },
                    location,
                    null,
                    false,
                    new OutputRedirector("manage.py")
                    )) {
             p.Wait();
             Assert.AreEqual(0, p.ExitCode);
         }
     });
 }