Esempio n. 1
0
        List <string> RunWithAccept(ProcessArgumentBuilder builder, TimeSpan timeout, bool moveToolsToTemp = false)
        {
            var sdkManager = FindToolPath(AndroidSdkHome);

            if (!(sdkManager?.Exists ?? false))
            {
                throw new FileNotFoundException("Could not locate sdkmanager", sdkManager?.FullName);
            }

            var ct = new CancellationTokenSource();

            if (timeout != TimeSpan.Zero)
            {
                ct.CancelAfter(timeout);
            }

            var p = new ShellProcessRunner(sdkManager.FullName, builder.ToString(), ct.Token, null, true);

            while (!p.HasExited)
            {
                Thread.Sleep(250);

                try
                {
                    p.Write("y");
                }
                catch { }
            }

            var r = p.WaitForExit();

            return(r.StandardOutput.Concat(r.StandardError).ToList());
        }
Esempio n. 2
0
        Task <XCodeInfo> GetInfo()
        {
            //Xcode 12.4
            //Build version 12D4e
            var r = ShellProcessRunner.Run("xcodebuild", "-version");

            var info = new XCodeInfo();

            foreach (var line in r.StandardOutput)
            {
                if (line.StartsWith("Xcode"))
                {
                    var vstr = line.Substring(5).Trim();
                    if (Version.TryParse(vstr, out var v))
                    {
                        info.Version = v;
                    }
                }
                else if (line.StartsWith("Build version"))
                {
                    info.Build = line.Substring(13)?.Trim();
                }
            }

            return(Task.FromResult(info));
        }
Esempio n. 3
0
        IEnumerable <string> run(bool interactive, params string[] args)
        {
            var adbManager = FindToolPath(AndroidSdkHome);

            if (adbManager == null || !File.Exists(adbManager.FullName))
            {
                throw new FileNotFoundException("Could not find avdmanager", adbManager?.FullName);
            }

            var builder = new ProcessArgumentBuilder();

            foreach (var arg in args)
            {
                builder.Append(arg);
            }

            var p = new ShellProcessRunner(new ShellProcessRunnerOptions(adbManager.FullName, builder.ToString())
            {
                RedirectOutput = !interactive,
            });

            var r = p.WaitForExit();

            if (r.StandardOutput.Concat(r.StandardError).Any(s => s.Contains("Exception")))
            {
                throw new Exception("Failed to create android avd");
            }

            return(r.StandardOutput);
        }
Esempio n. 4
0
        bool TryGetJavaJdkInfo(string javacFilename, out OpenJdkInfo javaJdkInfo)
        {
            var r = ShellProcessRunner.Run(javacFilename, "-version");
            var m = rxJavaCVersion.Match(r.GetOutput() ?? string.Empty);

            var v = m?.Value;

            if (!string.IsNullOrEmpty(v) && NuGetVersion.TryParse(v, out var version))
            {
                javaJdkInfo = new OpenJdkInfo(javacFilename, version);
                return(true);
            }

            javaJdkInfo = default;
            return(false);
        }
Esempio n. 5
0
        public override Task <DiagnosticResult> Examine(SharedState history)
        {
            var selected = GetSelectedXCode();

            if (selected.Version.IsCompatible(MinimumVersion, ExactVersion))
            {
                // Selected version is good
                ReportStatus($"Xcode.app ({VersionName})", Status.Ok);
                return(Task.FromResult(DiagnosticResult.Ok(this)));
            }

            XCodeInfo eligibleXcode = null;

            var xcodes = FindXCodeInstalls();

            foreach (var x in xcodes)
            {
                if (x.Version.IsCompatible(MinimumVersion, ExactVersion))
                {
                    eligibleXcode = x;
                    break;
                }
            }

            if (eligibleXcode != null)
            {
                // If this is the case, they need to run xcode-select -s
                ReportStatus($"No Xcode.app or an incompatible Xcode.app version is selected, but one was found at ({eligibleXcode.Path})", Status.Error);

                return(Task.FromResult(new DiagnosticResult(
                                           Status.Error,
                                           this,
                                           new Suggestion("Run xcode-select -s <Path>",
                                                          new Solutions.ActionSolution((sln, cancelToken) =>
                {
                    ShellProcessRunner.Run("xcode-select", "-s " + eligibleXcode.Path);
                    return Task.CompletedTask;
                })))));
            }

            ReportStatus($"Xcode.app ({VersionName}) not installed.", Status.Error);

            return(Task.FromResult(new DiagnosticResult(
                                       Status.Error,
                                       this,
                                       new Suggestion($"Download XCode {VersionName}"))));
        }
Esempio n. 6
0
        public override async Task Implement(SharedState sharedState, CancellationToken cancellationToken)
        {
            await base.Implement(sharedState, cancellationToken);

            string sdkRoot = default;

            if (sharedState != null && sharedState.TryGetEnvironmentVariable("DOTNET_ROOT", out var envSdkRoot))
            {
                if (Directory.Exists(envSdkRoot))
                {
                    sdkRoot = envSdkRoot;
                }
            }

            if (string.IsNullOrEmpty(sdkRoot))
            {
                sdkRoot = Util.IsWindows
                                        ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "dotnet")
                                        : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".dotnet");
            }

            var scriptUrl  = Util.IsWindows ? installScriptPwsh : installScriptBash;
            var scriptPath = Path.Combine(Path.GetTempPath(), Util.IsWindows ? "dotnet-install.ps1" : "dotnet-install.sh");

            Util.Log($"Downloading dotnet-install script: {scriptUrl}");

            var http = new HttpClient();
            var data = await http.GetStringAsync(scriptUrl);

            File.WriteAllText(scriptPath, data);

            var exe  = Util.IsWindows ? "powershell" : "sh";
            var args = Util.IsWindows
                                        ? $"{scriptPath} -InstallDir {sdkRoot} -Version {Version}"
                                        : $"{scriptPath} --install-dir {sdkRoot} --version {Version}";

            Util.Log($"Executing dotnet-install script...");
            Util.Log($"\t{exe} {args}");

            // Launch the process
            var p = new ShellProcessRunner(new ShellProcessRunnerOptions(exe, args));

            p.WaitForExit();
        }
		Task<IEnumerable<VisualStudioInfo>> GetWindowsInfo()
		{
			var items = new List<VisualStudioInfo>();

			var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
				"Microsoft Visual Studio", "Installer", "vswhere.exe");


			if (!File.Exists(path))
				Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
				"Microsoft Visual Studio", "Installer", "vswhere.exe");

			if (!File.Exists(path))
				return default;

			var r = ShellProcessRunner.Run(path,
				"-all -requires Microsoft.Component.MSBuild -format json -prerelease");

			var str = r.GetOutput();

			var json = JsonDocument.Parse(str);

			foreach (var vsjson in json.RootElement.EnumerateArray())
			{
				if (!vsjson.TryGetProperty("catalog", out var vsCat) || !vsCat.TryGetProperty("productSemanticVersion", out var vsSemVer))
					continue;

				if (!NuGetVersion.TryParse(vsSemVer.GetString(), out var semVer))
					continue;

				if (!vsjson.TryGetProperty("installationPath", out var installPath))
					continue;

				items.Add(new VisualStudioInfo
				{
					Version = semVer,
					Path = installPath.GetString()
				});
			}

			return Task.FromResult<IEnumerable<VisualStudioInfo>>(items);
		}
Esempio n. 8
0
        public bool RequiresLicenseAcceptance()
        {
            var sdkManager = FindToolPath(AndroidSdkHome);

            if (!(sdkManager?.Exists ?? false))
            {
                throw new FileNotFoundException("Could not locate sdkmanager", sdkManager?.FullName);
            }

            var requiresAcceptance = false;

            var cts = new CancellationTokenSource();
            var spr = new ShellProcessRunner(sdkManager.FullName, "--licenses", cts.Token, rx =>
            {
                if (rx.ToLowerInvariant().Contains("licenses not accepted"))
                {
                    requiresAcceptance = true;
                    cts.Cancel();
                }
            }, true);

            spr.WaitForExit();
            return(requiresAcceptance);
        }
Esempio n. 9
0
        XCodeInfo GetSelectedXCode()
        {
            var r = ShellProcessRunner.Run("xcode-select", "-p");

            var xcodeSelectedPath = r.GetOutput().Trim();

            if (!string.IsNullOrEmpty(xcodeSelectedPath))
            {
                if (xcodeSelectedPath.Equals(BugCommandLineToolsPath))
                {
                    throw new InvalidDataException();
                }

                var infoPlist = Path.Combine(xcodeSelectedPath, "..", "Info.plist");
                if (File.Exists(infoPlist))
                {
                    return(GetXcodeInfo(
                               Path.GetFullPath(
                                   Path.Combine(xcodeSelectedPath, "..", "..")), true));
                }
            }

            return(null);
        }
        public async Task <bool> InstallWorkloadPack(string sdkRoot, Manifest.DotNetSdkPack sdkPack, CancellationToken cancelToken)
        {
            WorkloadResolver.PackInfo packInfo;

            if (sdkPack.SkipManifestCheck && NuGetVersion.TryParse(sdkPack.Version, out var packVersion))
            {
                var kind = sdkPack?.PackKind?.ToLowerInvariant() switch
                {
                    "sdk" => WorkloadPackKind.Sdk,
                    "framework" => WorkloadPackKind.Framework,
                    "library" => WorkloadPackKind.Library,
                    "template" => WorkloadPackKind.Template,
                    "tool" => WorkloadPackKind.Tool,
                    _ => WorkloadPackKind.Sdk
                };

                var path = kind == WorkloadPackKind.Template ?
                           Path.Combine(Path.GetTempPath(), $"{sdkPack.Id}.{sdkPack.Version}.nupkg")
                                        : Path.Combine(sdkRoot, "sdk", $"{sdkPack.Id}", sdkPack.Version);

                packInfo = new WorkloadResolver.PackInfo(sdkPack.Id, sdkPack.Version, kind, path);
            }
            else
            {
                packInfo = workloadResolver.TryGetPackInfo(sdkPack.Id);
            }

            if (packInfo != null && NuGetVersion.TryParse(packInfo.Version, out var version))
            {
                if (packInfo.Kind == WorkloadPackKind.Template)
                {
                    var r = await AcquireNuGet(packInfo.Id, version, packInfo.Path, false, cancelToken, false);

                    // Short circuit the installation into the template-packs dir since this one might not
                    // be a part of any workload manifest, so we need to install with dotnet new -i
                    if (sdkPack.SkipManifestCheck)
                    {
                        var dotnetExe = Path.Combine(sdkRoot, DotNetSdk.DotNetExeName);

                        var p  = new ShellProcessRunner(new ShellProcessRunnerOptions(dotnetExe, $"new -i \"{packInfo.Path}\""));
                        var pr = p.WaitForExit();

                        if (pr.GetOutput().Contains("permission denied", StringComparison.InvariantCultureIgnoreCase))
                        {
                            throw new ApplicationException($"Your templates cache folder has some invalid permissions.  Please try to delete the folder and try again: "
                                                           + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".templateengine", "dotnetcli"));
                        }

                        return(pr?.ExitCode == 0);
                    }

                    return(r);
                }

                var actualPackId = GetAliasToPackId(packInfo);

                if (!string.IsNullOrEmpty(actualPackId))
                {
                    var packsRoot = Path.Combine(SdkRoot, "packs");

                    return(await AcquireNuGet(actualPackId, version, packsRoot, true, cancelToken, true));
                }
            }

            return(false);
        }
        public override async Task Implement(SharedState sharedState, CancellationToken cancelToken)
        {
            await base.Implement(sharedState, cancelToken);

            var    filename = Path.GetFileName(Url.AbsolutePath);
            string tmpExe   = null;

            var http = new HttpClient();

            http.Timeout = TimeSpan.FromMinutes(45);

            await Policy
            .Handle <ObjectDisposedException>()
            .Or <OperationCanceledException>()
            .Or <IOException>()
            .Or <InvalidDataException>()
            .RetryAsync(3)
            .ExecuteAsync(async() =>
            {
                tmpExe = Path.Combine(Path.GetTempPath(), filename);

                ReportStatus($"Downloading {Title ?? Url.ToString()}...");

                using (var fs = File.Create(tmpExe))
                    using (var response = await http.GetAsync(Url, HttpCompletionOption.ResponseHeadersRead))
                    {
                        var contentLength = response.Content.Headers.ContentLength;

                        using (var download = await response.Content.ReadAsStreamAsync())
                        {
                            // Short circuit if no length
                            if (!contentLength.HasValue)
                            {
                                await download.CopyToAsync(fs);
                                return;
                            }

                            var buffer        = new byte[81920];
                            long totalReadLen = 0;
                            var readLen       = 0;

                            var lastPercent = 0;

                            while ((readLen = await download.ReadAsync(buffer, 0, buffer.Length, cancelToken)) != 0)
                            {
                                await fs.WriteAsync(buffer, 0, readLen, cancelToken).ConfigureAwait(false);
                                totalReadLen += readLen;

                                var percent = (int)(((double)totalReadLen / (double)contentLength) * 100d);

                                if (percent % 10 == 0 && percent != lastPercent)
                                {
                                    lastPercent = percent;
                                    ReportStatus($"Downloading... {percent}%...");
                                }
                            }
                        }
                    }

                ReportStatus($"Downloaded {Title ?? Url.ToString()}.");
            });

            var logFile = Path.GetTempFileName();

            ReportStatus($"Installing {Title ?? Url.ToString()}...");

            var p = new ShellProcessRunner(new ShellProcessRunnerOptions(tmpExe, $"/install /quiet /norestart /log \"{logFile}\""));

            var r = p.WaitForExit();

            if (r.ExitCode == 0)
            {
                ReportStatus($"Installed {Title ?? Url.ToString()}.");
            }
            else
            {
                ReportStatus($"Installation failed for {Title ?? Url.ToString()}.  See log file for more details: {logFile}");
            }
        }