Esempio n. 1
0
        public void Awake()
        {
            var harmony = new Harmony(GUID);

            harmony.PatchAll();
            Settings = new PluginSettings(Config);
            InitialiseCommands();

            LastChatType.Set(Settings.DefaultChatChannel);
            CurrentInputChatType.Set(LastChatType);
            Log($"Initialised {Name} ({Version})");

            // Get the latest release from github and notify if there is a newer version.
            var latestReleaseVersion = GithubHelper.GetLatestGithubRelease(RepositoryAuthor, RepositoryName);

            if (!string.IsNullOrEmpty(latestReleaseVersion))
            {
                if (VersionHelper.IsNewerVersion(Version, latestReleaseVersion))
                {
                    LogWarning($"Version {latestReleaseVersion} of VChat has been released, please see {RepositoryUrl}");
                }
                else
                {
                    Log($"{Name} ({Version}) is up to date.");
                }
            }
        }
Esempio n. 2
0
        protected override async void OnStartup(StartupEventArgs e)
        {
#if DEBUG
            LogManager.AddDebugListener();
#endif
            Log.Info("Starting application");
            apphelper     = new WKitGlobal.AppHelper();
            discordhelper = new DiscordHelper();
            GithubHelper  = new GithubHelper();
            themehelper   = new ThemeHelper();

            await apphelper.InitializeMVVM();

            themehelper.InitializeThemeHelper();
            await apphelper.InitializeShell();

            discordhelper.InitDiscordRPC();



            Log.Info("Calling base.OnStartup");



            base.OnStartup(e);
            NNViewRegistrar.RegisterSplat();
        }
Esempio n. 3
0
        protected override async void OnViewLoaded()
        {
            Global.VMMain   = this;
            Global.Settings = Settings.Read();

            //Show search
            ShowPage("search");

            //Settings change
            Settings.Change(Global.Settings);

            //Show about
            if (Global.Settings.Version != VMAbout.Version)
            {
                Global.Settings.Version = VMAbout.Version;
                Global.Settings.Save();
                ShowPage("about");
            }

            //Update new version
            string version = await GithubHelper.getLastReleaseVersionAsync(Global.NAME_GITHUB_AUTHOR, Global.NAME_GITHUB_PROJECT);

            //if(version != null && version != VMAbout.Version)
            //{
            //    ShowPage("about");
            //}
        }
        /// <summary>
        /// Downloads the selected release file to a temporary file and starts
        /// the installation process.
        /// </summary>
        public async void DownloadInstall()
        {
            if (string.IsNullOrEmpty(this._downloadUrl))
            {
                return;
            }

            this.InstallStatus = _loc.GetLocalizationValue("InstallStatusDownloading");
            this.CanInstall    = false;

            var progress = new Progress <KeyValuePair <int, string> >(x =>
            {
                Dispatcher.UIThread.Post(() =>
                {
                    this.DownloadPercentage = x.Key;
                    this.InstallStatus      = x.Value;
                });
            });

            this._downloadedFileName = await GithubHelper.DownloadRelease(this.SelectedRelease, progress);

            Log.Information($"Download completed, file path is \"{this._downloadedFileName}\"");

            await InstallOnPlatform(this._downloadedFileName, this.SelectedRelease?.tag_name);
        }
Esempio n. 5
0
        /// <summary>
        /// Check if an update to Mefino is available, if so prompt the user to close this version and view the update page.
        /// </summary>
        /// <returns><see langword="true" /> if there is an update and user wants to close and view page, otherwise <see langword="false" /></returns>
        internal static bool CheckUpdatedWanted()
        {
            var fetchedVersion = GithubHelper.GetLatestReleaseVersion(MEFINO_RELEASE_API_QUERY);

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

            if (new Version(fetchedVersion) > new Version(MefinoApp.VERSION))
            {
                var result = MessageBox.Show(
                    $"A new version of Mefino is available for download: {fetchedVersion}" +
                    $"\n\n" +
                    $"Close this version and open the download page?",
                    "Update Available",
                    MessageBoxButtons.YesNo);

                if (result == DialogResult.Yes)
                {
                    Process.Start(MEFINO_RELEASE_URL);
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 6
0
        public static async Task DoWork(CrnCommandSettings settings, CommonSettings commonSettings, Parameters parameters, Jira jira)
        {
            throw new CcException("Crn command isn't implemented yet");

            var prUrl = parameters.GetPrUrl();

            GithubHelper.ParsePrUrl(prUrl, out var repoName, out var prNumber);

            Console.Write("Getting PR... ");
            var query = @"query {
                repository(owner:""trilogy-group"", name:""" + repoName + @"""){
                    pullRequest(number: " + prNumber + @"){
                        headRefName
                    }
                }  
            }";

            var repoData = await GithubHelper.Query(query, commonSettings.GithubToken);

            var branchName = repoData["repository"]["pullRequest"]["headRefName"].Value <string>();

            Console.WriteLine("done");

            //Console.Write($"Checkout branch {branchName}... ");
            //GitHelper.Exec($"git checkout {branchName}", repoName, commonSettings.ProjectsPath);
            //Console.WriteLine("done");
        }
Esempio n. 7
0
        protected override async void OnViewLoaded()
        {
            Global.VMMain   = this;
            Global.Settings = Settings.Read();

            //Show search
            ShowPage("search");

            //Settings change
            Settings.Change(Global.Settings);

            //Show about
            VMAbout.MainVM = this;
            if (Global.Settings.Version != VMAbout.Version)
            {
                Global.Settings.Version = VMAbout.Version;
                Global.Settings.Save();
                ShowPage("about");
            }

            //Update new version
            VMAbout.LastVersion = await GithubHelper.getLastReleaseVersionAsync(Global.NAME_GITHUB_AUTHOR, Global.NAME_GITHUB_PROJECT);

            if (VMAbout.LastVersion != null && VMAbout.LastVersion != VMAbout.Version)
            {
                VMAbout.EnableUpdate = Visibility.Visible;
                ShowPage("about");
            }
        }
Esempio n. 8
0
        public static async Task DoWork(RebaseCommandSettings settings, CommonSettings commonSettings, Parameters parameters, Jira jira)
        {
            var prUrl = parameters.Get("PR url: ");

            GithubHelper.ParsePrUrl(prUrl, out var repoName, out var prNumber);

            Console.Write("Getting PR... ");
            var query = @"query {
                repository(owner:""trilogy-group"", name:""" + repoName + @"""){
                    pullRequest(number: " + prNumber + @"){
                        headRefName
                    }
                }  
            }";

            var repoData = await GithubHelper.Query(query, commonSettings.GithubToken);

            var branchName = repoData["repository"]["pullRequest"]["headRefName"].Value <string>();

            Console.WriteLine("done");

            var repoSettings = SettingsHelper.GetRepoSettings(commonSettings, repoName);
            var mainBranch   = SettingsHelper.GetMainBranch(repoSettings);

            Console.Write($"Rebase {mainBranch} to {branchName}... ");
            GitHelper.Exec(
                $"git checkout {mainBranch} && git pull && git checkout {branchName} && git pull && git merge develop --no-edit && git push",
                repoSettings,
                commonSettings.ProjectsPath);
            Console.WriteLine("done");

            Console.Write($"Checkout {mainBranch}... ");
            GitHelper.Exec($"git checkout {mainBranch}", repoSettings, commonSettings.ProjectsPath);
            Console.WriteLine("done");
        }
Esempio n. 9
0
        private static async Task AssignLabelToPR(CommonSettings commonSettings, string repoName, string reviewLabel, JToken jPullRequest)
        {
            Console.Write("Get CRN review label id... ");

            var getRepoLabels = string.Format(QueryGetRepoLabelsFormat, "trilogy-group", repoName);
            var repoLabels    = await GithubHelper.Query(getRepoLabels, commonSettings.GithubToken);

            var repoLabelsNode = repoLabels["repository"]["labels"]["nodes"] as JArray;
            var prId           = jPullRequest["id"].Value <string>();

            if (repoLabelsNode == null)
            {
                Console.Write("No labels found in repo");
                return;
            }

            if (!repoLabelsNode.Any(
                    x => x["name"].Value <string>().Equals(reviewLabel, StringComparison.OrdinalIgnoreCase)))
            {
                Console.Write("No review label found in repo");
                return;
            }

            var crnReviewLabelId = repoLabelsNode.First(
                x => x["name"].Value <string>().Equals(reviewLabel, StringComparison.OrdinalIgnoreCase))
                                   ["id"]
                                   .Value <string>();

            Console.WriteLine("done");

            var labelNodes = jPullRequest["labels"]["nodes"] as JArray ?? new JArray();

            if (labelNodes.Any())
            {
                if (labelNodes.Any(x => x["id"].Value <string>().Equals(crnReviewLabelId)))
                {
                    Console.Write($@"""{reviewLabel}"" already assigned... ");
                    Console.WriteLine("done");
                    return;
                }

                Console.Write("Clear labels... ");
                var mutationClearLabels = string.Format(MutationClearLabelsPRFormat, prId);
                await GithubHelper.Query(mutationClearLabels, commonSettings.GithubToken);

                Console.WriteLine("done");
            }

            Console.Write("Add label... ");
            var mutationAddLabels = string.Format(MutationAddLabelsFormat, prId, crnReviewLabelId);
            await GithubHelper.Query(mutationAddLabels, commonSettings.GithubToken);

            Console.WriteLine("done");
        }
        //Update
        public void StartUpdate(string sVersion)
        {
            string url = GithubHelper.getFileUrl(Global.NAME_GITHUB_AUTHOR, Global.NAME_GITHUB_PROJECT, sVersion, Global.NAME_GITHUB_FILE);

            if (PathHelper.Mkdirs(Global.PATH_UPDATE) == false)
            {
                Dialog.Show(new MessageView(MessageBoxImage.Error, "Creat folder falied!", false));
                return;
            }

            DownloadFileHepler.StartAsync(url, Global.PATH_UPDATE + Global.NAME_GITHUB_FILE, null, UpdateDownloadNotify, CompleteDownloadNotify, ErrDownloadNotify, 3);
        }
Esempio n. 11
0
        /// <summary>
        /// Called after the loading, register the hook (for single-process) and check for new releases.
        /// </summary>
        private async void AppLoaded(object sender, RoutedEventArgs e)
        {
            _source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
            _source.AddHook(new HwndSourceHook(SettingsHelper.WndProc));

            GithubRelease githubRelease = await GithubHelper.GetLatestRelease();

            if (githubRelease.IsLatest)
            {
                this.InformNewVersion(githubRelease.Url, githubRelease.Version, githubRelease.Current);
            }
        }
        /// <summary>
        /// Fetches available releases from Github.
        /// </summary>
        /// <param name="fromFile">If set to <c>true</c>, the releases will not be fetched
        /// from Github, but instead be read from a local file.</param>
        private async Task GetReleases(bool fromFile = false)
        {
            this.Releases = await GithubHelper.GetReleases(this.EnablePreReleases, fromFile);

            this.HasReleases = this.Releases.Length > 0;
            if (!this.HasReleases)
            {
                return;
            }

            Log.Information($"Found {this.Releases?.Count()} releases");
            this.SelectedRelease = this.Releases.OrderByDescending(r => r.published_at).FirstOrDefault();
        }
        /// <summary>
        /// Sets the download size and URL for the selected release.
        /// </summary>
        public void SelectedReleaseChanged()
        {
            if (SelectedRelease == null)
            {
                return;
            }

            var downloadInfo = GithubHelper.GetDownloadInfoForAsset(SelectedRelease);

            this.DownloadSize = downloadInfo?.DownloadSize;
            this._downloadUrl = downloadInfo?.DownloadUrl;

            Log.Information($"Selected release changed to {SelectedRelease.tag_name}");
            Log.Information($"Current release asset download size is : {this.DownloadSize} MB");
            Log.Information($"Current release asset download URL is : {this._downloadUrl}");
        }
Esempio n. 14
0
        /// <summary>
        /// Actually fetch and process web packages.
        /// </summary>
        private static bool TryFetchMefinoGithubPackages()
        {
            var githubQuery = GithubHelper.QueryForMefinoPackages();

            if (githubQuery == null)
            {
                Console.WriteLine("GITHUB QUERY RETURNED NULL! (are you offline?)");
                return(false);
            }

            var items = ((JsonValue)githubQuery).AsJsonObject["items"].AsJsonArray;

            foreach (var result in items)
            {
                CheckRepoSearchResult(result);
            }

            //Console.WriteLine($"Found {WebManifestManager.s_cachedWebManifests.Count} Mefino packages!");
            return(true);
        }
Esempio n. 15
0
        /// <summary>
        /// Check new version
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        {
            new Thread(async() =>
            {
                var result         = await Task.WhenAll(GithubHelper.CheckGitHubLatestVersion(), GithubHelper.CheckGitHublatestBuild());
                var currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
                currentVersion     = new Version(currentVersion.Major, currentVersion.Minor, currentVersion.Build);
                var isNewAvailable = result[0] != null && (currentVersion.CompareTo(result[0]) < 0);

                using (var form = new NewRelease())
                {
                    form.IsNewVersion = isNewAvailable;

                    form.CurrentVersion = currentVersion;
                    form.LatestVersion  = result[0] ?? currentVersion;
                    form.LatestBuild    = result[1] ?? currentVersion;

                    _ = form.ShowDialog();
                }
            }).Start();
        }
Esempio n. 16
0
        #pragma warning disable 1998
        public async Task Install(string archiveFilePath, string installPath, string versionTag)
        {
            // The "async" in the delegate is needed, otherwise exceptions within
            // the delegate won't "bubble up" to the exception handlers upstream.
            await Task.Run(async() =>
            {
                Inventory.Instance.Load();
                Log.Information($"Installing on macOS to {installPath}");

                string fileName = Path.GetTempFileName().Replace(".tmp", ".zip");

                // Download an extract initial SQRL application template
                Log.Information("Downloading Mac app folder structure from Github");
                GithubHelper.DownloadFile("https://github.com/sqrldev/SQRLDotNetClient/raw/PlatformInstaller/Installers/MacOsX/SQRL.app.zip", fileName);
                Log.Information("Creating initial SQRL application template");
                CommonUtils.ExtractZipFile(fileName, string.Empty, installPath);
                File.Delete(fileName);

                // Extract main installation archive
                Log.Information($"Extracting main installation archive");
                CommonUtils.ExtractZipFile(archiveFilePath, string.Empty, Path.Combine(installPath, "SQRL.app/Contents/MacOS"));

                // Check if a database exists in the installation directory
                // (which is bad) and if it does, move it to user space.
                if (File.Exists(Path.Combine(installPath, "SQRL.app/Contents/MacOS", PathConf.DBNAME)))
                {
                    Utils.MoveDb(Path.Combine(installPath, "SQRL.app/Contents/MacOS", PathConf.DBNAME));
                }

                Inventory.Instance.AddDirectory(Path.Combine(installPath, "SQRL.app"));

                // Set executable bit on executables
                Log.Information("Changing executable file to be executable a+x");
                _shell.Term($"chmod a+x {GetClientExePath(installPath)}", Output.Internal);
                _shell.Term($"chmod a+x {Path.Combine(installPath, "SQRL.app/Contents/MacOS", Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName))}", Output.Internal);

                Inventory.Instance.Save();
            });
        }
        //Update
        public void StartUpdate()
        {
            Progress.ValueInt  = 0;
            CountIncreSize     = 0;
            ShowProgress       = Visibility.Visible;
            DownloadStatusInfo = Language.Get("strmsgGetNewVersionUrl");

            string url = GithubHelper.getFileUrl(Global.NAME_GITHUB_AUTHOR, Global.NAME_GITHUB_PROJECT, LastVersion, Global.NAME_GITHUB_FILE);

            if (PathHelper.Mkdirs(Global.PATH_UPDATE) == false)
            {
                DownloadStatusInfo = Language.Get("strmsgCreatUpdateFolderFailed");
                EndUpdate();
                return;
            }

            DownloadStatusInfo = Language.Get("strmsgStartUpdate");
            Progress.SetStatus(ProgressHelper.STATUS.RUNNING);
            StartTime = TimeHelper.GetCurrentTime();
            LoginKey key = Tools.GetKey();

            DownloadFileHepler.StartAsync(url, Global.PATH_UPDATE + Global.NAME_GITHUB_FILE, null, UpdateDownloadNotify, CompleteDownloadNotify, ErrDownloadNotify, 3, Proxy: key.Proxy);
        }
Esempio n. 18
0
        private async void Initialize()
        {
            ToggleWindow(false);
            try {
                _log.Info("Initializing...");

                ConfigFile = await IniFile.LoadAsync(App.ExecutableName + ".ini");

                MainConfig     = ConfigFile[App.ExecutableName];
                CurrentVersion = MainConfig["CurrentVersion"];
                _log.Info("Config loaded.");

                IniSection githubSection = ConfigFile["Github"];
                _githubHelper = new GithubHelper(
                    githubSection["UserName"],
                    githubSection["RepoName"],
                    githubSection["BaseUri"],
                    githubSection["BaseApiUri"]
                    );
                _log.Info("Github helper initialized.");

                _httpClient = new AdvancedHttpClient();
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                // Required to use GitHub API.
                _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(App.ExecutableName, App.CurrentVersion));
                _log.Info("HTTP client initalized.");

                SetCurrentStage(OperationStage.Check);
            }
            catch (Exception e) {
                string errorMessage = string.Format("Failed to initialize: {0}", e.Message);
                _log.Error(errorMessage);
                App.ExitWithMessage(errorMessage, MessageBoxImage.Error);
            }
            ToggleWindow(true);
        }
Esempio n. 19
0
        /// <summary>
        /// Checks the free space.
        /// </summary>
        /// <param name="repoUrl">The repo URL.</param>
        /// <param name="outDir">The out dir.</param>
        private static void CheckFreeSpace(string repoUrl, string outDir)
        {
            Logger.LogInfo("Checking free space...", false);
            int ourSize  = (Properties.Resources.docfx.Length + Properties.Resources.mstemplate.Length) * 4 / 1024;
            int repoSize = 0;

            try
            {
                repoSize = GithubHelper.GetSizeOfRepo(repoUrl);
            }
            catch (Exception)
            {
                // ignored
            }

            DriveInfo dest = new DriveInfo(Directory.GetDirectoryRoot(outDir));

            if (ourSize + repoSize > dest.AvailableFreeSpace / 1024)
            {
                Logger.LogError(Error, false);
                Logger.LogError(String.Format(FreeSpaceError, Path.GetPathRoot(outDir), (ourSize + repoSize) / 1024));
                Exit(ExitCodeEnum.Error);
            }

            string    tempPath = Path.GetTempPath();
            DriveInfo system   = new DriveInfo(Path.GetPathRoot(tempPath));

            if (ourSize > system.AvailableFreeSpace / 1024)
            {
                Logger.LogError(Error, false);
                Logger.LogError(String.Format(FreeSpaceError, Path.GetPathRoot(tempPath), (ourSize / 1024)));
                Exit(ExitCodeEnum.Error);
            }

            Logger.LogInfo(Completed);
        }
Esempio n. 20
0
        public static async Task DoWork(PrCommandSettings settings, CommonSettings commonSettings, Parameters parameters, Jira jira)
        {
            var ticketUrl = parameters.Get("Enter Jira ticket: ");
            var issueKey  = JiraHelper.GetIssueKey(ticketUrl);

            var comment = GetComment(settings, parameters);

            var noteForReviewer = parameters.Get("Note for reviewer: ");

            if (settings.NotesAliases.ContainsKey(noteForReviewer))
            {
                noteForReviewer = settings.NotesAliases[noteForReviewer];
            }

            bool isOnlyPr = false;

            if (parameters.Any())
            {
                var str = parameters.Get(string.Empty);
                if (str == "--onlyPr")
                {
                    isOnlyPr = true;
                }
                else
                {
                    throw new CcException($"Unknown argument: {str}");
                }
            }

            Console.Write("Get ticket... ");
            var issue = await jira.Issues.GetIssueAsync(issueKey);

            var repoUrl = issue.GetScmUrl();

            if (string.IsNullOrWhiteSpace(repoUrl))
            {
                Console.WriteLine("Can't get repo name");
                return;
            }

            Console.WriteLine("done");

            var repoName = repoUrl.Split('/')[4];

            if (repoName.EndsWith(".git", StringComparison.OrdinalIgnoreCase))
            {
                repoName = Path.GetFileNameWithoutExtension(repoName);
            }

            var repoSettings = SettingsHelper.GetRepoSettings(commonSettings, repoName);
            var branchPrefix = string.IsNullOrWhiteSpace(repoSettings?.BranchPrefix)
                ? "feature"
                : repoSettings.BranchPrefix;

            var mainBranch = SettingsHelper.GetMainBranch(repoSettings);

            var key        = issue.Key.ToString();
            var ticketType = GetTicketType(issue);

            if (!isOnlyPr)
            {
                var stagedFiles  = GitHelper.Exec("git diff --name-only --cached", repoSettings, commonSettings.ProjectsPath);
                var changedFiles = GitHelper.Exec("git diff --name-only", repoSettings, commonSettings.ProjectsPath);

                if (!stagedFiles.Any() && !changedFiles.Any())
                {
                    throw new CcException("No changed files found");
                }

                var filesForCheck = stagedFiles.Any() ? stagedFiles : changedFiles;

                if (filesForCheck.Any(f => f.EndsWith(".sln", StringComparison.OrdinalIgnoreCase)))
                {
                    ConsoleHelper.WriteColor("You are going to commit changes in sln-file. Do you really want to do it? [y/N]: ", ConsoleColor.Yellow);
                    var answer = Console.ReadLine() ?? string.Empty;

                    if (!answer.Equals("y", StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }
                }

                var currentBranch = GitHelper.GetCurrentBranch(repoSettings, commonSettings.ProjectsPath);

                if (currentBranch != mainBranch)
                {
                    ConsoleHelper.WriteColor(
                        $"Your current branch is {currentBranch}, but usually it should be {mainBranch}. Do you really want to create new branch from this one? [y/N]: ",
                        ConsoleColor.Yellow);
                    var answer = Console.ReadLine() ?? string.Empty;

                    if (!answer.Equals("y", StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }
                }

                Console.Write("Set assignee... ");

                if (issue.Assignee == null)
                {
                    issue.Assignee = commonSettings.JiraUserName;
                    await issue.SaveChangesAsync();

                    Console.WriteLine("done");
                }
                else
                {
                    if (issue.Assignee != commonSettings.JiraUserName)
                    {
                        throw new CcException($"Ticket is already assigned to \"{issue.Assignee}\"!");
                    }
                    else
                    {
                        Console.WriteLine("already assigned");
                    }
                }

                Console.Write("Move ticket to \"In progress\"... ");
                if (issue.Status.ToString().Equals("To Do", StringComparison.InvariantCultureIgnoreCase))
                {
                    await issue.WorkflowTransitionAsync("Not False Positive");
                }

                if (issue.Status.ToString().Equals("Writing Test Code", StringComparison.InvariantCultureIgnoreCase))
                {
                    await issue.WorkflowTransitionAsync("Test coverage available");
                }

                if (issue.Status.ToString().Equals("Ready to refactor", StringComparison.InvariantCultureIgnoreCase))
                {
                    await issue.WorkflowTransitionAsync("Start progress");
                }

                Console.WriteLine("done");

                Console.Write("Push changes... ");
                var createBranchCommand = $"git checkout -b {branchPrefix}/{key}";
                var commitOption        = stagedFiles.Any() ? string.Empty : "a";
                var commitCommand       = $"git commit -{commitOption}m  \"{key}: Fixes {ticketType}\"";
                var pushCommand         = $"git push --set-upstream origin {branchPrefix}/{key}";
                GitHelper.Exec(
                    $"{createBranchCommand} && {commitCommand} && {pushCommand}",
                    repoSettings,
                    commonSettings.ProjectsPath);

                Console.WriteLine("done");

                Console.Write($"Checkout {mainBranch}... ");
                try
                {
                    GitHelper.Exec($"git checkout {mainBranch} && git pull", repoSettings, commonSettings.ProjectsPath);
                    Console.WriteLine("done");
                }
                catch (GitException)
                {
                    ConsoleHelper.WriteLineColor("failed", ConsoleColor.Yellow);
                }

                Console.Write("Waiting... ");
                Thread.Sleep(TimeSpan.FromSeconds(3));
                Console.WriteLine("done");
            }

            Console.Write("Create PR... ");
            var query    = @"query { repository(owner:""trilogy-group"", name:""" + repoName + @"""){ id }}";
            var repoData = await GithubHelper.Query(query, commonSettings.GithubToken);

            var repoId = repoData["repository"]["id"].Value <string>();

            var fullNote = string.IsNullOrWhiteSpace(noteForReviewer)
                ? string.Empty
                : $@"# Note for Reviewers\r\n- {noteForReviewer}\r\n\r\n";

            var(testCoverageMessage, coverageWarning) = GetTestCoverageMessage(issue);

            var mutation = @"mutation
                {
                  createPullRequest(input:{
                    title:""[" + key + "] " + issue.Summary.Replace("\"", "\\\"") + @""", 
                    baseRefName: """ + mainBranch + @""", 
                    body: ""# Links\r\nhttps://jira.devfactory.com/browse/" + key + @"\r\n\r\n# Changes\r\n- " + comment + @"\r\n\r\n" + fullNote + testCoverageMessage + @""", 
                    headRefName: """ + branchPrefix + "/" + key + @""", 
                    repositoryId: """ + repoId + @"""
                  }){
                    pullRequest{
                      id,
                      url
                    }
                  }
                }";

            var resultJson = await GithubHelper.Query(mutation, commonSettings.GithubToken);

            var jPullRequest = resultJson["createPullRequest"]["pullRequest"];
            var prUrl        = jPullRequest["url"].Value <string>();

            Console.WriteLine("done");

            if (coverageWarning)
            {
                Console.WriteLine("Please don't forget to fill test coverage manually");
            }

            if (settings.AssignPr)
            {
                Console.Write("Assign PR... ");

                var prId = jPullRequest["id"].Value <string>();

                var currentUserIdJson = await GithubHelper.Query("query {viewer {id}}", commonSettings.GithubToken);

                var userId = currentUserIdJson["viewer"]["id"].Value <string>();

                var assignPrMutation = @"mutation
                    {
                      addAssigneesToAssignable(input: {
                        assignableId: """ + prId + @""", 
                        assigneeIds: [""" + userId + @"""]}) { clientMutationId }}";

                await GithubHelper.Query(assignPrMutation, commonSettings.GithubToken);

                Console.WriteLine("done");
            }

            Console.Write("Write PR url to ticket... ");
            const string codeReviewUrl = "Code Review Ticket URL";

            if (issue.CustomFields.Any(f => f.Name == codeReviewUrl))
            {
                issue.CustomFields[codeReviewUrl].Values = new [] { prUrl };
            }
            else
            {
                issue.CustomFields.Add(codeReviewUrl, prUrl);
            }

            issue.SaveChanges();
            Console.WriteLine("done");

            Console.WriteLine("New PR url: " + prUrl);
        }
Esempio n. 21
0
        public static async Task DoWork(ReviewCommandSettings settings, CommonSettings commonSettings, Parameters parameters, Jira jira)
        {
            var prUrl = parameters.Get("PR url: ");

            GithubHelper.ParsePrUrl(prUrl, out var repoName, out var prNumber);

            var timeSpent = parameters.Get("Time spent: ");

            if (string.IsNullOrWhiteSpace(timeSpent) || timeSpent.Trim() == "0")
            {
                throw new CcException("Time spent should not be empty");
            }

            //var coverage = parameters.Get("Coverage percentage: ");
            //if (string.IsNullOrWhiteSpace(coverage))
            //{
            //    throw new CcException("Coverage should not be empty");
            //}

            Console.Write("Getting PR... ");
            var prDetails = string.Format(QueryGetPRDetailsFormat, repoName, prNumber);
            var prInfo    = await GithubHelper.Query(prDetails, commonSettings.GithubToken);

            var jPullRequest = prInfo["repository"]["pullRequest"];
            var bodyHtml     = jPullRequest["bodyHTML"].Value <string>();

            Console.WriteLine("done");
            Console.Write("Getting ticket... ");
            var regex = new Regex(@"https://jira\.devfactory\.com/browse/(CC-\d+)");
            var m     = regex.Match(bodyHtml);

            if (!m.Success)
            {
                throw new CcException("Ticket not found");
            }

            var issue = await jira.Issues.GetIssueAsync(m.Groups[1].Value);

            Console.WriteLine("done");

            var issueStatus = issue.Status.ToString();

            if (!issueStatus.Equals("In progress", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new CcException("Ticket should be in \"In progress\" state");
            }

            var repoSettings = SettingsHelper.GetRepoSettings(commonSettings, repoName);

            if (string.IsNullOrWhiteSpace(repoSettings?.Pca))
            {
                throw new CcException($"PCA isn't defined for repo \"{repoName}\" in settings.json");
            }

            Console.Write("Moving to review... ");
            SetCustomField(issue, "Reviewer", repoSettings.Pca);
            SetCustomField(issue, "Code Review Ticket URL", prUrl);
            await issue.WorkflowTransitionAsync("Submit for Review", new WorkflowTransitionUpdates()
            {
                TimeSpent = timeSpent
            });

            Console.WriteLine("done");

            if (settings.AssignPr)
            {
                Console.Write("Assigning PR... ");

                var currentUserIdJson = await GithubHelper.Query("query {viewer {id}}", commonSettings.GithubToken);

                var userId = currentUserIdJson["viewer"]["id"].Value <string>();
                var nodes  = jPullRequest["assignees"]["nodes"] as JArray ?? new JArray();

                if (nodes.Any(node => node["id"].Value <string>() == userId))
                {
                    Console.WriteLine("already assigned");
                }
                else
                {
                    var assignPrMutation = string.Format(MutationAddAssigneePRFormat, jPullRequest["id"].Value <string>(), userId);
                    await GithubHelper.Query(assignPrMutation, commonSettings.GithubToken);

                    Console.WriteLine("done");
                }
            }

            if (settings.AssignReviewLabel)
            {
                await AssignLabelToPR(commonSettings, repoName, settings.ReviewLabelName, jPullRequest);
            }
        }
Esempio n. 22
0
        private async Task <bool> ReviewPr(string qbLink, bool approve, IReadOnlyCollection <string> failedItems)
        {
            // Get user login
            var loginQuery = @"query { viewer { login }}";
            var loginData  = await GithubHelper.Query(loginQuery, _settings.GithubToken);

            var login = loginData["viewer"]["login"].Value <string>();


            // Get pending review
            var pendingReviewQuery = @"query q { 
  repository(owner:""" + _prInfo.OwnerName + @""", name:""" + _prInfo.RepoName + @""") {
            pullRequest(number: " + _prInfo.PrNumber + @") {
                id
                reviews(last: 20, author: """ + login + @""") {
                    nodes{
                        id
                        state
                    }
                }
            }
        }
    }";
            var pendingReviewData  = await GithubHelper.Query(pendingReviewQuery, _settings.GithubToken);

            var pendingReviews = pendingReviewData["repository"]["pullRequest"]["reviews"]["nodes"] as JArray;
            var pendingReview  = pendingReviews?.FirstOrDefault(r => r["state"].Value <string>() == "PENDING");

            string reviewId;

            if (pendingReview == null)
            {
                var prId = pendingReviewData["repository"]["pullRequest"]["id"].Value <string>();

                var addReviewMutation = @"mutation w{ 
                addPullRequestReview(input: {pullRequestId: """ + prId + @"""}) { 
                    pullRequestReview {id}
                }
            }";

                var reviewData = await GithubHelper.Query(addReviewMutation, _settings.GithubToken);

                reviewId = reviewData["addPullRequestReview"]["pullRequestReview"]["id"].Value <string>();
            }
            else
            {
                reviewId = pendingReview["id"].Value <string>();
            }

            string reviewBody;
            string reviewEvent;

            if (approve)
            {
                if (_settings.ApprovePrAction == "approve")
                {
                    reviewBody  = $"body: \"QB: {qbLink}\"";
                    reviewEvent = "APPROVE";
                }
                else
                {
                    reviewBody  = $"body: \"Approved\\r\\nQB: {qbLink}\"";
                    reviewEvent = "COMMENT";
                }
            }
            else
            {
                reviewEvent = "REQUEST_CHANGES";
                var failedItemsText = string.Join("\\r\\n", failedItems.Select(i => $"**{i}**"));
                reviewBody = $"body: \"{failedItemsText}\\r\\nQB: {qbLink}\"";
            }

            var submitReviewMutation = @"mutation e { 
                submitPullRequestReview(input: {
                    " + reviewBody + @"
                    pullRequestReviewId: """ + reviewId + @""",
                    event: " + reviewEvent + @"}) { 
                        clientMutationId
                }
            }";

            var submitData = await GithubHelper.Query(submitReviewMutation, _settings.GithubToken);

            return(submitData["submitPullRequestReview"]["clientMutationId"] != null);
        }
Esempio n. 23
0
        private async Task StartReview(string date, string ticketUrl)
        {
            ticketUrl = ticketUrl.Trim();
            var match = JiraUrlRegex.Match(ticketUrl);

            if (!match.Success)
            {
                match = JiraKeyRegex.Match(ticketUrl);
                if (!match.Success)
                {
                    throw new ReviewException("Unknown jira ticket or jira issue key");
                }

                ticketUrl = $"https://jira.devfactory.com/browse/{ticketUrl}";
            }

            var issueKey = match.Groups[1].Value;

            Console.Write("Get ticket... ");
            _issue = await _jira.Issues.GetIssueAsync(issueKey);

            if (string.IsNullOrWhiteSpace(_issue.Assignee))
            {
                Console.WriteLine("done");
                throw new ReviewException("Assignee is empty");
            }

            _prAuthor = await _jira.Users.GetUserAsync(_issue.Assignee);

            Console.WriteLine("done");

            var issueStatus = _issue.Status.ToString();

            if (issueStatus != "Ready For Review" && issueStatus != "Code Review")
            {
                throw new ReviewException($"Unknown ticket state: {_issue.Status}");
            }

            Console.Write("Make checks... ");
            var failedChecks = AdditionalChecks.Make(_issue);

            Console.WriteLine("done");

            if (failedChecks.Any())
            {
                ConsoleHelper.WriteLineColor("Failed checks: ", ConsoleColor.Yellow);

                foreach (var failedCheck in failedChecks)
                {
                    ConsoleHelper.WriteLineColor(" * " + failedCheck, ConsoleColor.Yellow);
                }
            }

            Console.Write("Set peer reviewer... ");
            if (_issue.CustomFields["Peer reviewer"] == null)
            {
                _issue.CustomFields.Add("Peer reviewer", _jiraUser.Username);
                await _jira.Issues.UpdateIssueAsync(_issue);

                // Need to reload ticket. Otherwise we can't move it forward to the next status
                _issue = await _jira.Issues.GetIssueAsync(issueKey);

                Console.WriteLine("done");
            }
            else
            {
                var reviewer = _issue.CustomFields["Peer reviewer"].Values.First();
                Console.WriteLine($"already set to {reviewer}");
                if (reviewer != _jiraUser.Username)
                {
                    throw new ReviewException($"Ticket is already assigned to {reviewer}");
                }
            }

            if (issueStatus == "Ready For Review")
            {
                Console.Write("Start review... ");
                await _issue.WorkflowTransitionAsync("Start Review");

                Console.WriteLine("done");
            }

            var prUrl = _issue["Code Review Ticket URL"].ToString();

            if (!GithubHelper.ParsePrUrl(prUrl, out _prInfo))
            {
                throw new ReviewException($"Invalid PR url: {prUrl}");
            }

            var qbFolder   = _prInfo.RepoName;
            var qbFileName = $"{_issue.Key} {date}";

            if (!_googleDriveFolders.ContainsKey(qbFolder))
            {
                Console.Write("Get QB folder id... ");
                var qbFolderId = GetQbFolderId(qbFolder);
                _googleDriveFolders.Add(qbFolder, qbFolderId);
                Console.WriteLine("done");
            }

            Console.Write("Create QB file... ");
            _qbFile = CreateQbFile(qbFolder, qbFileName);
            Console.WriteLine("done");

            Console.Write("Fill QB file... ");
            FillQbSummary(ticketUrl, prUrl, _prAuthor.DisplayName);
            FillQbSheets(_issue.Type.ToString(), _issue.Summary.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ? "csharp" : "java");
            Console.WriteLine("done");
        }
        public void ThreadUpdateFunc()
        {
            string PATH     = Path.GetFullPath("./tidal_new/");
            string VERF     = PATH + "version";
            string BATF     = PATH + "update.bat";
            string sSelfVer = VersionHelper.GetSelfVersion();

            //Get Already Download Ver
            string sDlVer = FileHelper.Read(VERF);

            if (sDlVer.IsNotBlank() && VersionHelper.Compare(sSelfVer, sDlVer) < 0 && File.Exists(PATH + "tidal-gui.exe") && File.Exists(BATF))
            {
                MessageBoxResult ret = MessageBox.Show("Update new version?", "Info", MessageBoxButton.YesNo);
                if (ret == MessageBoxResult.No)
                {
                    return;
                }

                if (Application.Current != null)
                {
                    Application.Current.Dispatcher.BeginInvoke((Action) delegate()
                    {
                        CmdHelper.StartExe(BATF, null, IsShowWindow: false);
                        WindowClose();
                    });
                }
                return;
            }

            //Get Github Last Ver
            string sLastVer = GithubHelper.getLastReleaseVersion("yaronzz", "Tidal-Media-Downloader");

            if (VersionHelper.Compare(sSelfVer, sLastVer) >= 0)
            {
                return;
            }

            if (Directory.Exists(PATH))
            {
                Directory.Delete(PATH, true);
            }
            PathHelper.Mkdirs(PATH);
            if (GithubHelper.getLastReleaseFile("yaronzz", "Tidal-Media-Downloader", "tidal-gui.zip", PATH + "tidal-gui.zip"))
            {
                FastZip fz = new FastZip();
                try
                {
                    fz.ExtractZip(PATH + "tidal-gui.zip", PATH, null);
                    if (File.Exists(PATH + "tidal-gui.exe"))
                    {
                        string sBat = "ping -n 5 127.0.0.1\n";
                        sBat += string.Format("move {0}tidal-gui.exe {0}..\\tidal-gui.exe\n", PATH);
                        sBat += string.Format("start {0}..\\tidal-gui.exe\n", PATH);
                        FileHelper.Write(sBat, true, BATF);
                        FileHelper.Write(sLastVer, true, VERF);
                    }
                }
                catch
                {
                    return;
                }
            }
        }
Esempio n. 25
0
 private void HyperlinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
 {
     GithubHelper.OpenBrowserWithPrefilledIssue();
     e.Handled = true;
 }
Esempio n. 26
0
        public static IEnumerator ProcessAsync(string text)
        {
            didProcessAsync = false;
            if (rootEmojiAsset == null)
            {
                yield break;
            }

            if (string.IsNullOrEmpty(text))
            {
                yield break;
            }

            List <string> detectedEmojis = new List <string>();

            string emojiText = null;

            while ((emojiText = EmojiTexture.GetFirstEmoji(text)) != null)
            {
                text = text.Substring(text.IndexOf(emojiText, System.StringComparison.Ordinal));

                if (!string.IsNullOrEmpty(emojiText))
                {
                    int             spriteIndex = -1;
                    TMP_SpriteAsset spriteAsset = TMP_SpriteAsset
                                                  .SearchForSpriteByUnicode(rootEmojiAsset, char.ConvertToUtf32(emojiText, 0), true, out spriteIndex);
                    if (spriteAsset == null)
                    {
                        detectedEmojis.Add(emojiText);
                    }
                    text = text.Substring(emojiText.Length);
                }
                else
                {
                    break;
                }
            }

            if (detectedEmojis.Count > 0)
            {
                yield return(GithubHelper.Initialize());
            }

            foreach (var detectedEmoji in detectedEmojis)
            {
                string hex = char.ConvertToUtf32(detectedEmoji, 0).ToString("X");

                if (GithubHelper.IsValid(hex))
                {
                    yield return(emojiTexture.SetGithubEmoji(hex));

                    if (emojiTexture.didDownloadTexture)
                    {
                        PushSprite(emojiTexture);
                        didProcessAsync = true;
                    }
                }
            }

            //If the texture has unsaved changes, we apply them here
            //And make it non readable if it is full
            if (textureNeedsApply)
            {
                var makeNoLongerReadable = currentEmojiIndex == SHEET_TILES * SHEET_TILES;
                ((Texture2D)currentEmojiAsset.spriteSheet).Apply(false, makeNoLongerReadable);
                textureNeedsApply = false;
            }
        }
Esempio n. 27
0
#pragma warning disable 1998
        public async Task Install(string archiveFilePath, string installPath, string versionTag)
        {
            // The "async" in the delegate is needed, otherwise exceptions within
            // the delegate won't "bubble up" to the exception handlers upstream.
            await Task.Run(async() =>
            {
                Inventory.Instance.Load();
                Log.Information($"Installing on Linux to {installPath}");

                // Extract main installation archive
                Log.Information($"Extracting main installation archive");
                CommonUtils.ExtractZipFile(archiveFilePath, string.Empty, installPath);

                // Check if a database exists in the installation directory
                // (which is bad) and if it does, move it to user space.
                if (File.Exists(Path.Combine(installPath, PathConf.DBNAME)))
                {
                    Utils.MoveDb(Path.Combine(installPath, PathConf.DBNAME));
                }

                Inventory.Instance.AddDirectory(installPath);

                // Create icon, register sqrl:// scheme etc.
                Log.Information("Creating Linux desktop icon, application and registering SQRL invokation scheme");
                GithubHelper.DownloadFile(@"https://github.com/sqrldev/SQRLDotNetClient/raw/master/SQRLDotNetClientUI/Assets/SQRL_icon_normal_64.png",
                                          Path.Combine(installPath, "SQRL.png"));

                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"[Desktop Entry]");
                sb.AppendLine("Name=SQRL");
                sb.AppendLine("Type=Application");
                sb.AppendLine($"Icon={(Path.Combine(installPath, "SQRL.png"))}");
                sb.AppendLine($"Exec={GetClientExePath(installPath)} %u");
                sb.AppendLine("Categories=Internet");
                sb.AppendLine("Terminal=false");
                sb.AppendLine("MimeType=x-scheme-handler/sqrl");
                File.WriteAllText(Path.Combine(installPath, "sqrldev-sqrl.desktop"), sb.ToString());


                SystemAndShellUtils.Chmod(installPath, Recursive: true);

                SystemAndShellUtils.SetExecutableBit(GetClientExePath(installPath));
                SystemAndShellUtils.SetExecutableBit(Path.Combine(installPath, "sqrldev-sqrl.desktop"));
                SystemAndShellUtils.SetExecutableBit(Path.Combine(installPath, Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)));
                _shell.Term($"xdg-desktop-menu install {Path.Combine(installPath, "sqrldev-sqrl.desktop")}", Output.Internal);
                _shell.Term($"gio mime x-scheme-handler/sqrl sqrldev-sqrl.desktop", Output.Internal);
                _shell.Term($"xdg-mime default sqrldev-sqrl.desktop x-scheme-handler/sqrl", Output.Internal);

                _shell.Term($"update-desktop-database {SystemAndShellUtils.GetHomePath()}/.local/share/applications/", Output.Internal);



                // Change owner of database dir/file to the actual user behind the "sudo"
                var user           = SystemAndShellUtils.GetCurrentUser();
                string chownDbFile = $"chown -R {user}:{user} {PathConf.ClientDBPath}";
                Log.Information($"Determined username for chown: \"{user}\"");
                Log.Information($"Running command: {chownDbFile}");
                _shell.Term(chownDbFile, Output.Internal);

                Log.Information("All is good up to this point, lets setup Linux for UAC (if we can)");


                // Creates the required file and system changes for SQRL to be available
                // ubiquitous throughout the system via a new environment variable SQRL_HOME
                // and the addition of this variable to the system PATH.
                // Note that the latter won't take effect until the user logs out or reboots.

                if (SystemAndShellUtils.IsPolKitAvailable())
                {
                    Log.Information("Creating SQRL_HOME environment variable and adding SQRL_HOME to PATH");
                    string sqrlvarsFile = "/etc/profile.d/sqrl-vars.sh";
                    using (StreamWriter sw = new StreamWriter(sqrlvarsFile))
                    {
                        sw.WriteLine($"export SQRL_HOME={installPath}");
                        sw.WriteLine("export PATH=$PATH:$SQRL_HOME");
                        sw.Close();
                    }
                    Inventory.Instance.AddFile(sqrlvarsFile);
                    Log.Information("Creating polkit rule for SQRL");
                    var assets = AvaloniaLocator.Current.GetService <IAssetLoader>();
                    string sqrlPolkitPolicyFile = Path.Combine("/usr/share/polkit-1/actions",
                                                               "org.freedesktop.policykit.SQRLPlatformAwareInstaller_linux.policy");
                    using (StreamWriter sw = new StreamWriter(sqrlPolkitPolicyFile))
                    {
                        string policyFile = "";
                        using (var stream = new StreamReader(assets.Open(new Uri("resm:SQRLPlatformAwareInstaller.Assets.SQRLPlatformAwareInstaller_linux.policy"))))
                        {
                            policyFile = stream.ReadToEnd();
                        }
                        policyFile = policyFile.Replace("INSTALLER_PATH", "/tmp/SQRLPlatformAwareInstaller_linux");
                        sw.Write(policyFile);
                        sw.Close();
                    }
                    _shell.Term("export SQRL_HOME={installPath}", Output.Internal);
                    _shell.Term("export PATH=$PATH:$SQRL_HOME", Output.Internal);
                    Inventory.Instance.AddFile(sqrlPolkitPolicyFile);
                }
                else
                {
                    Log.Warning("pkexec was not found, we can't automatically elevate permissions UAC style, user will have to do manually");
                }

                Inventory.Instance.Save();
            });
        }
Esempio n. 28
0
        private static void Postfix(ref Chat __instance)
        {
            var chat = __instance;

            // Listen on value changed, this updated the input field and carrot text color to match the targeted channel.
            __instance.m_input.onValueChanged.AddListener((text) =>
            {
                if (chat.m_input != null)
                {
                    VChatPlugin.UpdateCurrentChatTypeAndColor(chat.m_input, text);
                }
            });

            // Listen when the chat field is closed, this resets the position of the message history (arrow up & down handler)
            __instance.m_input.onEndEdit.AddListener((text) =>
            {
                if (string.IsNullOrEmpty(chat.m_input.text))
                {
                    VChatPlugin.MessageSendHistoryIndex = 0;
                }
            });

            // Enable chat window click-through.
            if (VChatPlugin.Settings.EnableClickThroughChatWindow && __instance.m_chatWindow != null)
            {
                __instance.m_chatWindow.ChangeClickThroughInChildren(VChatPlugin.Settings.EnableClickThroughChatWindow);
            }

            // Set the hide delay.
            __instance.m_hideDelay = VChatPlugin.Settings.ChatHideDelay;

            // Update the input colour since we may not be on local.
            VChatPlugin.UpdateChatInputColor(__instance.m_input, VChatPlugin.LastChatType);

            // Get the latest release of VChat and notify the user when the chat is starting up for the first time.
            var latestReleaseVersion = GithubHelper.GetLatestGithubRelease(VChatPlugin.RepositoryAuthor, VChatPlugin.RepositoryName);

            if (!string.IsNullOrEmpty(latestReleaseVersion))
            {
                List <string> messages = new();
                if (VersionHelper.IsNewerVersion(VChatPlugin.Version, latestReleaseVersion))
                {
                    messages.AddRange(new[] {
                        $"You are running on an older version of {VChatPlugin.Name} ({VChatPlugin.Version}).",
                        $"version {latestReleaseVersion} has been released, see {VChatPlugin.RepositoryUrl}",
                    });
                }
                else
                {
                    messages.Add($"{VChatPlugin.Name} {VChatPlugin.Version} is loaded and up to date.");
                }

                foreach (var msg in messages)
                {
                    __instance.AddString($"[{VChatPlugin.Name}] {msg}");
                }
            }

            // Reset the server plugin status as we may have changed server from a single player world to a dedicated server.
            PlayerPatchOnSpawned.HasSentServerPluginStatusMessage = false;
        }