public async Task <bool> Upload(GitInfo gitInfo, string tableReference)
        {
            // Validation data
            var validationData = gitInfo != null &&
                                 !string.IsNullOrEmpty(gitInfo.Username) &&
                                 !string.IsNullOrEmpty(gitInfo.Email) &&
                                 !string.IsNullOrEmpty(gitInfo.GitUrl) &&
                                 !string.IsNullOrEmpty(gitInfo.GitTestProjectPath) &&
                                 !string.IsNullOrEmpty(tableReference);

            if (!validationData)
            {
                return(false);
            }

            // Connection table
            //var connStr = CloudConfigurationManager.GetSetting(this.webSvc.QueueStorageConnectionString);
            var storageAccount = CloudStorageAccount.Parse(this.webSvc.QueueStorageConnectionString);
            var tableClient    = storageAccount.CreateCloudTableClient();
            var table          = tableClient.GetTableReference(tableReference);
            await table.CreateIfNotExistsAsync();

            // Insert data to table
            var data = new TableData(gitInfo)
            {
                PartitionKey = gitInfo.Username,
                RowKey       = Guid.NewGuid().ToString()
            };
            var insertOperation = TableOperation.Insert(data);
            await table.ExecuteAsync(insertOperation);

            return(true);
        }
 public TableData(GitInfo info)
 {
     this.Username           = info.Username;
     this.Email              = info.Email;
     this.GitUrl             = info.GitUrl;
     this.GitTestProjectPath = info.GitTestProjectPath;
 }
Beispiel #3
0
 public int perform()
 {
     Console.WriteLine("updater, version " + utility.Version.get());
     Console.WriteLine();
     Console.WriteLine("Version control commit: " + GitInfo.getCommit());
     Console.WriteLine("Version control date:   " + GitInfo.getCommitDate());
     return(0);
 }
Beispiel #4
0
        public void SuperTest()
        {
            var wd = @"F:\Projects\_GitHub\DependencyScanner\.git";

            var info = new GitInfo(wd, TestBase.Git, new HasInternetConnection(), _logger);

            //info.Checkout("mastesr");
        }
Beispiel #5
0
        public void SuperTest()
        {
            var wd = @"F:\Projects\_GitHub\DependencyScanner\.git";

            var info = new GitInfo(wd, TestBase.Git);

            //info.Checkout("mastesr");
        }
Beispiel #6
0
        public NewProjectDialog(GitInfo gitInfo, string solutionPath)
        {
            InitializeComponent();

            var viewModel = DataContext as NewProjectViewModel;

            viewModel.InitializeWithGitInfo(gitInfo, solutionPath);
        }
        public void StageChanges(GitInfo gitInfo)
        {
            _ = gitInfo ?? throw new ArgumentNullException(nameof(gitInfo));

            _messageHub.Publish("Staging changes...".ToMessage());
            Commands.Stage(gitInfo.Repo, "*");
            _messageHub.Publish("Changes are staged".ToSuccess());
        }
        static void Main(string[] args)
        {
            var profiles              = GitInfo.Deserialize();
            var allProfiles           = GitInfo.GetAllProfiles();
            var allRepos              = GitInfo.GetAllRepo();
            int countOfCSharpRepos    = GitInfo.GetCSharpRepos();
            var reposSortedByLanguage = GitInfo.SortByLanguages();
            var bestReposByStars      = GitInfo.SortByStars();
            var repo2019              = GitInfo.Get2019Repo();

            System.Console.WriteLine(new string('-', 30) + "\nURl Profiles.");

            foreach (Item item in profiles)
            {
                System.Console.WriteLine(item.html_url);
            }

            System.Console.WriteLine(new string('-', 30) + "\nURL Repositorys.");

            foreach (Repository item in allRepos)
            {
                System.Console.WriteLine(item.html_url);
            }

            System.Console.WriteLine(new string('-', 30) + "\nCount C# Repositorys: {0}", countOfCSharpRepos);
            System.Console.WriteLine(new string('-', 30) + "\nRepositorys sorted by languages.");

            foreach (var item in reposSortedByLanguage)
            {
                var q = item as Repository;
                try
                {
                    foreach (var item1 in (List <Repository>)item)
                    {
                        System.Console.WriteLine(new string(' ', 2) + $"Profile name: {item1.owner.login} // Repository URL: {item1.html_url}");
                    }
                }
                catch
                {
                    System.Console.WriteLine(item);
                }
            }

            System.Console.WriteLine(new string('-', 30) + "\nBest Repositorys by stars.");

            foreach (Repository item in bestReposByStars)
            {
                System.Console.WriteLine($"RepoURL: {item.html_url} {new string(' ', 20)} // Stars count: {item.stargazers_count}");
            }

            System.Console.WriteLine(new string('-', 30) + "\nURL Repositorys created at 2019.");

            foreach (string item in repo2019)
            {
                System.Console.WriteLine(item);
            }
        }
Beispiel #9
0
        /// <inheritdoc/>
        public void Perform()
        {
            AssemblyName asm = Assembly.GetExecutingAssembly().GetName();

            HoneycombConsole.WriteInfoLine($"name: {asm.Name}");
            HoneycombConsole.WriteInfoLine($"version: {asm.Version}");
            HoneycombConsole.WriteInfoLine($"url: {GitInfo.GetAddress()}");
            HoneycombConsole.WriteInfoLine($"branch: {GitInfo.GetBranch()}");
            HoneycombConsole.WriteInfoLine($"commit: {GitInfo.GetCommit()}");
        }
Beispiel #10
0
        public bool BranchExists(GitInfo gitInfo, string branchName)
        {
            _ = gitInfo ?? throw new ArgumentNullException(nameof(gitInfo));
            _ = branchName ?? throw new ArgumentNullException(nameof(branchName));

            _logger.TraceFormat("Checking branch {0} exists...", branchName);
            var branchExists = gitInfo.Repo.Branches.Any(x => x.FriendlyName == branchName);

            _logger.DebugFormat("Branch {0} exists: {1}", branchName, branchExists);
            return(branchExists);
        }
Beispiel #11
0
        public void CommitChanges(GitInfo gitInfo, string message)
        {
            _ = gitInfo ?? throw new ArgumentNullException(nameof(gitInfo));
            _ = message ?? throw new ArgumentNullException(nameof(message));

            _messageHub.Publish("Committing changes...".ToMessage());
            var signature = gitInfo.Repo.Config.BuildSignature(DateTimeOffset.Now);

            gitInfo.Repo.Commit(message, signature, signature);
            _messageHub.Publish("Changes are committed".ToSuccess());
        }
Beispiel #12
0
        public void GetGitStatus_Test()
        {
            string     directory    = Environment.CurrentDirectory;
            IGitRunner gitRunner    = new GitCommandRunner(directory);
            string     expectedUser = "******";
            GitInfo    status       = GetCommitInfo.GetGitStatus(gitRunner, null);

            Assert.IsFalse(string.IsNullOrEmpty(status.Branch), $"Branch should not be null/empty.");
            Assert.IsFalse(string.IsNullOrEmpty(status.Modified));
            Assert.IsTrue(status.Modified == "Unmodified" || status.Modified == "Modified");
            Assert.AreEqual(expectedUser, status.GitUser);
        }
Beispiel #13
0
        public Branch CheckoutBranch(GitInfo gitInfo, string branchName)
        {
            _ = gitInfo ?? throw new ArgumentNullException(nameof(gitInfo));
            _ = branchName ?? throw new ArgumentNullException(nameof(branchName));

            _messageHub.Publish($"Checking branch {branchName} out...".ToMessage());
            var branch = gitInfo.Repo.Branches[branchName];
            var result = Commands.Checkout(gitInfo.Repo, branch);

            _messageHub.Publish($"Branch {branchName} is checked out".ToSuccess());
            return(result);
        }
Beispiel #14
0
        public void GetGitStatus_Test()
        {
            string     directory = Environment.CurrentDirectory;
            IGitRunner gitRunner = new GitCommandRunner(directory);
            //string expectedUser = "******";
            MockTaskLogger logger     = new MockTaskLogger("GitCommandRunner");
            GitInfo        status     = GetCommitInfo.GetGitStatus(gitRunner, logger);
            string         logEntries = string.Join('\n', logger.LogEntries.Select(e => e.ToString()));

            Assert.IsFalse(string.IsNullOrEmpty(status.Branch), $"Branch should not be null/empty.\n{logEntries}");
            Assert.IsFalse(string.IsNullOrEmpty(status.Modified), $"'Modified' should not be null/empty.\n{logEntries}");
            Assert.IsTrue(status.Modified == "Unmodified" || status.Modified == "Modified", $"'Modified' has an unrecognized value.\n{logEntries}");
            Assert.IsFalse(string.IsNullOrWhiteSpace(status.GitUser), $"GitUser should not be null/empty.\n{logEntries}");
            //Assert.AreEqual(expectedUser, status.GitUser);
        }
Beispiel #15
0
        public void AddCommentToExistingCommit(GitInfo gitInfo, string message)
        {
            _ = gitInfo ?? throw new ArgumentNullException(nameof(gitInfo));
            _ = message ?? throw new ArgumentNullException(nameof(message));

            _messageHub.Publish($"Adding {message} to the commit message...".ToMessage());
            var lastCommit = gitInfo.Branch.Tip;

            try
            {
                gitInfo.Repo.Refs.RewriteHistory(
                    new RewriteHistoryOptions
                {
                    BackupRefsNamespace = Guid.NewGuid().ToString(),
                    OnError             = exception =>
                    {
                        _messageHub.Publish(exception);
                        _messageHub.Publish("Cannot rewrite comment".ToWarning());
                    },
                    OnSucceeding         = () => _messageHub.Publish("Successfully rewritten last commit message".ToMessage()),
                    CommitHeaderRewriter = c =>
                    {
                        if (c.Message.Contains(message))
                        {
                            message = c.Message;
                        }
                        else
                        {
                            if (c.Message.EndsWith("\n", StringComparison.OrdinalIgnoreCase))
                            {
                                message = c.Message + message;
                            }
                            else
                            {
                                message = c.Message + "\n" + message;
                            }
                        }

                        return(CommitRewriteInfo.From(c, message));
                    }
                },
                    lastCommit);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
        }
Beispiel #16
0
        public async Task <GitInfo> GetGitInfo(string url, string gitProjectname, string gitTestProjectPath)
        {
            var validate = !string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(gitProjectname);

            if (!validate)
            {
                throw new Exception("ข้อมูลไม่ถูกต้อง กรุณาลองอีกครั้ง");
            }


            var urlSplited = url.Split("/", StringSplitOptions.RemoveEmptyEntries);

            if (urlSplited.Count() != 4)
            {
                throw new Exception("ข้อมูลไม่ถูกต้อง กรุณาลองอีกครั้ง");
            }

            if (string.IsNullOrEmpty(urlSplited[GitstringValuPlattern.projectName]) ||
                urlSplited[GitstringValuPlattern.projectName].Replace(".git", "").ToLower() != gitProjectname.ToLower())
            {
                throw new Exception("Project ไม่ถูกต้อง กรุณากรอก git url ของโปรเจคให้ถูกต้อง");
            }

            var client = new GitHubClient(new ProductHeaderValue(webConfig.UserAgent));
            //Auth
            var basicAuth = new Credentials(webConfig.Username, webConfig.Password);

            client.Credentials = basicAuth;
            //Get user
            var username = urlSplited[GitstringValuPlattern.username];
            var user     = await client.User.Get(username);

            if (string.IsNullOrEmpty(user.Email))
            {
                throw new Exception("ระบบไม่พบ e-mail ของคุณ กรุณาตั้งค่าให้ e-mail ของคุณเป็นสาธารณะ");
            }

            var result = new GitInfo
            {
                Email              = user.Email,
                Username           = username,
                GitUrl             = url,
                GitTestProjectPath = gitTestProjectPath
            };

            return(result);
        }
        public static string GetGitValue(GitInfo gitInfo, string path)
        {
            var psInfo = new ProcessStartInfo("git", Arguments[(int)gitInfo])
            {
                UseShellExecute        = false,
                WorkingDirectory       = path,
                RedirectStandardOutput = true,
                StandardOutputEncoding = Encoding.UTF8,
                WindowStyle            = ProcessWindowStyle.Hidden,
                CreateNoWindow         = true,
            };

            Process process;

            try
            {
                process = Process.Start(psInfo);
                process?.WaitForExit();
                if (process?.ExitCode != 0)
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }

            var value = process.StandardOutput.ReadToEnd().Trim();

            if (gitInfo == GitInfo.BranchName)
            {
                var list = value.Split('\n');
                foreach (var item in list)
                {
                    if (item[0] != '*')
                    {
                        continue;
                    }
                    value = item.Substring(2);
                    break;
                }
            }

            return(value);
        }
Beispiel #18
0
        /// <summary>
        /// 收到post信息,首先对分支进行切换,然后git pull拉取本分支的最新代码,最后再进行项目的编译工作
        /// </summary>
        /// <param name="projectInfo">项目信息</param>
        /// <param name="pushBranch">操作的分支</param>
        /// <param name="CIConfigPath">项目config路径</param>
        /// <returns></returns>
        public ProjectInfo buildProject(ProjectInfo projectInfo, string pushBranch, string CIConfigPath)
        {
            //进行分支切换操作
            bool switchBranch = _gitlabController.git_checkout("git checkout " + pushBranch, projectInfo.WorkDirectory);

            //若是分支切换成功,进行项目编译
            if (switchBranch)
            {
                //获取gitlab信息
                GitInfo gitlabInfo = _configController.GitInfoQuery("config/GitLabInfo", CIConfigPath);

                Boolean gitPullResult = _gitlabController.Libgit2_GitPull(projectInfo.WorkDirectory, gitlabInfo.Username, gitlabInfo.Password, gitlabInfo.Emailaddress);
                if (gitPullResult)
                {
                    string     buildResult; //存储编译是否成功
                    string     error;       //存储编译的日志文件
                    string     log;         //存储编译的所有信息
                    string     time;
                    ConfigInfo configInfo = _configController.ConfigQuery("config/preferences",
                                                                          CIConfigPath);
                    projectInfo.BuildTime = DateTime.Now.ToString();
                    projectInfo.StartTime = DateTime.Now.ToString();
                    if (projectInfo.Nameproperty == "LuckyCI")
                    {
                        projectInfo.WorkDirectory += "\\Project";
                    }
                    if (projectInfo.Nameproperty == "fundbook.rn")
                    {
                        projectInfo.WorkDirectory += "\\android";
                    }
                    if (projectInfo.Nameproperty == "FirstProject")
                    {
                        projectInfo.WorkDirectory += "\\android";
                    }
                    log = _projectController.Build(projectInfo.BuildCommand, projectInfo.WorkDirectory,
                                                   out buildResult, out error, out time);
                    projectInfo.Duration = time;
                    projectInfo.EndTime  = DateTime.Now.ToString();
                    projectInfo.Log      = (configInfo.StandarOutput == "true")
                        ? ("\n" + log + "\n" + error)
                        : ("\n" + error);
                    projectInfo.Result = buildResult;
                }
            }
            return(projectInfo);
        }
        public void ExtractGitDataFromFolder(TestItem testItem)
        {
            Assert.True(Directory.Exists(testItem.GitFolderPath));

            var gitInfo = GitInfo.GetFrom(testItem.GitFolderPath);

            Assert.Equal(testItem.AuthorDate, gitInfo.AuthorDate.Value.ToString("u"));
            Assert.Equal(testItem.AuthorEmail, gitInfo.AuthorEmail);
            Assert.Equal(testItem.AuthorName, gitInfo.AuthorName);
            Assert.Equal(testItem.Branch, gitInfo.Branch);
            Assert.Equal(testItem.Commit, gitInfo.Commit);
            Assert.Equal(testItem.CommitterDate, gitInfo.CommitterDate.Value.ToString("u"));
            Assert.Equal(testItem.CommitterEmail, gitInfo.CommitterEmail);
            Assert.Equal(testItem.CommitterName, gitInfo.CommitterName);
            Assert.NotNull(gitInfo.Message);
            Assert.NotNull(gitInfo.PgpSignature);
            Assert.Equal(testItem.Repository, gitInfo.Repository);
            Assert.Equal(testItem.SourceRoot, gitInfo.SourceRoot);
        }
        /// <summary>
        /// 获取gitlab信息
        /// </summary>
        /// <param name="dataPath">节点路径</param>
        /// <param name="xmlConfigPath">xml路径</param>
        /// <returns></returns>
        public GitInfo GitInfoQuery(string dataPath, string xmlConfigPath)
        {
            GitInfo gitlabInfo = new GitInfo();
            XmlDao  xmlDao     = new XmlDao();

            try
            {
                XmlNodeList xmlNodeList = xmlDao.XmlQuery(dataPath, xmlConfigPath);
                gitlabInfo.Username     = xmlNodeList[0].SelectSingleNode("Username").InnerText;
                gitlabInfo.Password     = xmlNodeList[0].SelectSingleNode("Password").InnerText;
                gitlabInfo.Emailaddress = xmlNodeList[0].SelectSingleNode("Email").InnerText;
                gitlabInfo.Gitreversion = xmlNodeList[0].SelectSingleNode("GitReversion").InnerText;
                return(gitlabInfo);
            }
            catch (Exception)
            {
                return(gitlabInfo);
            }
        }
Beispiel #21
0
        public async Task <object> ActionTest(TimersFilter filter)
        {
            var stopWatch = TickTock.StartNew("Json parse");
            var json      = Mongo.GroupTimers(
                filter.info.Test,
                filter.info.Mesh,
                filter.info.Benchmark,
                "whole-program",
                filter.info.Branch ?? "master"
                );

            stopWatch.Start("MongoDB Aggregate");
            var items = await _dbService.ColTimers
                        .Aggregate <GroupedTimer>(json.AsBsonArray())
                        .ToListAsync();

            stopWatch.Start("Welch Compute");
            TimerUtils.ComputeWelch(items);
            TimerUtils.SmoothDetections(items);

            stopWatch.Start("Transform Timer");
            var result = items
                         .Select(i => new SimpleTimers
            {
                Durations = i.Durations.ToArray(),
                Commit    = i.Commit,
                Branch    = i.Info.Branch,
                Welch     = i.Welch,
                Left      = i.Left,
                Right     = i.Right,
                Info      = GitInfo.From(i.Info),
                isBroken  = false,
            })
                         .ToList();

            stopWatch.Stop();

            return(new
            {
                Data = result,
                Ratio = 0.2
            });
        }
Beispiel #22
0
        public UnshelveViewModel(
            [NotNull] string directoryPath,
            [NotNull] GitInfo gitInfo,
            [NotNull] TfsInfo tfsInfo,
            [NotNull] IMessageHub messageHub,
            [NotNull] IGitUtility gitUtility,
            [NotNull] ICmdUtility cmdUtility,
            [NotNull] IGitTfsUtility gitTfsUtility,
            [NotNull] ITfsUtility tfsUtility,
            [NotNull] SynchronizationContext synchronizationContext,
            [NotNull] Func <string, bool, ConfirmationViewModel> confirmationViewModelFactory,
            [NotNull] Func <ConfirmationViewModel, IConfirmationWindow> confirmationWindowFactory,
            [NotNull] ICommandManager commandManager,
            [NotNull] IRateLimiter rateLimiter)
            : base(commandManager)
        {
            _messageHub                   = messageHub ?? throw new ArgumentNullException(nameof(messageHub));
            _gitUtility                   = gitUtility ?? throw new ArgumentNullException(nameof(gitUtility));
            _cmdUtility                   = cmdUtility ?? throw new ArgumentNullException(nameof(cmdUtility));
            _gitTfsUtility                = gitTfsUtility ?? throw new ArgumentNullException(nameof(gitTfsUtility));
            _tfsUtility                   = tfsUtility ?? throw new ArgumentNullException(nameof(tfsUtility));
            _synchronizationContext       = synchronizationContext ?? throw new ArgumentNullException(nameof(synchronizationContext));
            _confirmationViewModelFactory = confirmationViewModelFactory ?? throw new ArgumentNullException(nameof(confirmationViewModelFactory));
            _confirmationWindowFactory    = confirmationWindowFactory ?? throw new ArgumentNullException(nameof(confirmationWindowFactory));
            _rateLimiter                  = rateLimiter ?? throw new ArgumentNullException(nameof(rateLimiter));
            _gitInfo       = gitInfo ?? throw new ArgumentNullException(nameof(gitInfo));
            _tfsInfo       = tfsInfo ?? throw new ArgumentNullException(nameof(tfsInfo));
            _directoryPath = directoryPath ?? throw new ArgumentNullException(nameof(directoryPath));

            UnshelveCommand = AddCommand(Unshelve, () => CanExecute);
            CancelCommand   = AddCommand(Cancel, () => !IsLoading);
            OpenShelvesetInBrowserCommand   = AddCommand(OpenShelvesetInBrowser, () => ShelvesetName != null);
            CopyShelvesetToClipboardCommand = AddCommand(CopyShelvesetToClipboard, () => ShelvesetName != null);

            if (User == null)
            {
                UsersSearchPattern = string.Empty; // sets current user
            }

            _messageHub.Publish(DialogType.Unshelve);
            _subscriptionTokens.Add(messageHub.Subscribe <TaskState>(OnTaskAction));
        }
Beispiel #23
0
        public static void Main(string[] args)
        {
            var esUrl      = Environment.GetEnvironmentVariable("ES_URL");
            var esPassword = Environment.GetEnvironmentVariable("ES_PASS");
            var esUser     = Environment.GetEnvironmentVariable("ES_USER");

            ElasticsearchBenchmarkExporterOptions options;

            if (!string.IsNullOrEmpty(esUrl) && !string.IsNullOrEmpty(esPassword) && !string.IsNullOrEmpty(esUser))
            {
                Console.WriteLine($"Setting ElasticsearchBenchmarkExporterOptions based on environment variables - es URL: {esUrl}");
                options = new ElasticsearchBenchmarkExporterOptions(esUrl)
                {
                    Username = esUser, Password = esPassword
                };
            }
            else
            {
                Console.WriteLine(
                    "Setting ElasticsearchBenchmarkExporterOptions to export data to http://localhost:9200 - to change this set following environment variables: ES_URL, ES_PASS, ES_USER");
                options = new ElasticsearchBenchmarkExporterOptions("http://localhost:9200");
            }

            using (var gitInfo = new GitInfo())
            {
                try
                {
                    options.GitBranch    = gitInfo.BranchName;
                    options.GitCommitSha = gitInfo.CommitHash;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed reading git info");
                    Console.WriteLine(e);
                }
            }

            var exporter = new ElasticsearchBenchmarkExporter(options);
            var config   = DefaultConfig.Instance.With(exporter);

            BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config);
        }
        private async Task GoNext()
        {
            var result = CommonDialogDisplayer.ShowInfoDialog("We will now clone and build the project. Are you sure? ");

            if (!result)
            {
                return;
            }

            try
            {
                _loadingDisplayer.ShowLoading("Cloning project and building project..");
                await _gitCloner.CloneSolutionAsync(RepositoryUrl, BranchName, Username, Password, LocalPath);

                _loadingDisplayer.ShowLoading("Looking for solution..");
                var solutionPath = _solutionFinder.FindSolution(LocalPath);

                if (solutionPath == null)
                {
                    throw new Exception($"Could not find any solution file in the {LocalPath} directory or subdirectories.");
                }

                var gitInfo = new GitInfo
                {
                    RepositoryUrl = RepositoryUrl,
                    Branch        = BranchName,
                    LocalPath     = LocalPath,
                    Username      = Username,
                    Password      = Password
                };

                _loadingDisplayer.HideLoading();

                _startModuleTabOpener.OpenNewProjectTab(gitInfo, solutionPath);
            }
            catch (Exception ex)
            {
                _loadingDisplayer.HideLoading();
                CommonDialogDisplayer.ShowErrorDialog("Error when cloning project", ex.Message, ex.ToString());
            }
        }
Beispiel #25
0
        public static GitInfo Info()
        {
            var gitPath      = $"{Application.dataPath}/../.git";
            var headFilePath = $"{gitPath}/HEAD";

            // そもそも狙っているファイルが無ければnull
            if (!File.Exists(headFilePath))
            {
                return(null);
            }

            var head = Text.Read(headFilePath, true);

            // branchを参照している
            if (head.Contains("ref:"))
            {
                // "ref: refs/heads/hogeBranch"みたいな感じなので、Pathだけにする
                head = head.Replace("ref: ", "").Replace("\r", "").Replace("\n", "");

                var branchPath = $"{gitPath}/{head}";
                var hash       = Text.Read(branchPath, true);

                var info = new GitInfo()
                {
                    branch = head, hash = hash
                };
                return(info);
            }
            // branchを参照していない
            else
            {
                // headにhashが入ってる
                var info = new GitInfo()
                {
                    branch = "no referencing branch", hash = head
                };
                return(info);
            }
        }
        public async Task <IActionResult> Index(string url)
        {
            try
            {
                var startIndex = url.ToLower().IndexOf("unlocking-ep");
                var ep         = url.Substring(startIndex, 14);

                GitInfo gitInfo = null;
                if (ep == "unlocking-ep24")
                {
                    gitInfo = await gSvc.GetGitInfo(url, ProjectsInfo.EP24.ProjectName, ProjectsInfo.EP24.ProjectTestPath);
                }
                else if (ep == "unlocking-ep27")
                {
                    gitInfo = await gSvc.GetGitInfo(url, ProjectsInfo.EP27.ProjectName, ProjectsInfo.EP27.ProjectTestPath);
                }

                if (gitInfo != null)
                {
                    var msg     = JsonConvert.SerializeObject(gitInfo);
                    var reasult = await qSvc.EnQueue(msg, ProjectsInfo.EP24.ProjectQueuename);

                    // Upload data to table
                    const string tableReference = "earntest";
                    await tableSvc.Upload(gitInfo, tableReference);

                    return(RedirectToAction(nameof(Success)));
                }
                else
                {
                    return(RedirectToAction(nameof(Error), new { errorMsg = "เกิดข้อผิดพลาดในระหว่างดำเนินการ กรุณาลองอีกครั้ง" }));
                }
            }
            catch (Exception e)
            {
                return(RedirectToAction(nameof(Error), new { errorMsg = e.Message }));
            }
        }
Beispiel #27
0
        public ShelveViewModel(
            [NotNull] string directoryPath,
            [NotNull] GitInfo gitInfo,
            [NotNull] TfsInfo tfsInfo,
            [NotNull] IMessageHub messageHub,
            [NotNull] IGitUtility gitUtility,
            [NotNull] ICmdUtility cmdUtility,
            [NotNull] IGitTfsUtility gitTfsUtility,
            [NotNull] ITfsUtility tfsUtility,
            [NotNull] SynchronizationContext synchronizationContext,
            [NotNull] Func <string, bool, ConfirmationViewModel> confirmationViewModelFactory,
            [NotNull] Func <ConfirmationViewModel, IConfirmationWindow> confirmationWindowFactory,
            [NotNull] ICommandManager commandManager)
            : base(commandManager)
        {
            _messageHub                   = messageHub ?? throw new ArgumentNullException(nameof(messageHub));
            _gitUtility                   = gitUtility ?? throw new ArgumentNullException(nameof(gitUtility));
            _cmdUtility                   = cmdUtility ?? throw new ArgumentNullException(nameof(cmdUtility));
            _gitTfsUtility                = gitTfsUtility ?? throw new ArgumentNullException(nameof(gitTfsUtility));
            _tfsUtility                   = tfsUtility ?? throw new ArgumentNullException(nameof(tfsUtility));
            _synchronizationContext       = synchronizationContext ?? throw new ArgumentNullException(nameof(synchronizationContext));
            _confirmationViewModelFactory = confirmationViewModelFactory ?? throw new ArgumentNullException(nameof(confirmationViewModelFactory));
            _confirmationWindowFactory    = confirmationWindowFactory ?? throw new ArgumentNullException(nameof(confirmationWindowFactory));
            _gitInfo       = gitInfo ?? throw new ArgumentNullException(nameof(gitInfo));
            _tfsInfo       = tfsInfo ?? throw new ArgumentNullException(nameof(tfsInfo));
            _directoryPath = directoryPath ?? throw new ArgumentNullException(nameof(directoryPath));

            ShelveOrCheckinCommand = AddCommand(ShelveOrCheckin, () => CanExecute);
            CancelCommand          = AddCommand(Cancel, () => !IsLoading);

            IsDirty        = CommitDirty = _gitInfo.IsDirty;
            ShelvesetName  = GetShelvesetName();
            CommitMessage  = _gitInfo.CommitMessage ?? string.Empty;
            CommitMessages = _gitInfo.CommitMessages;
            _messageHub.Publish(DialogType.Shelve);
            _subscriptionTokens.Add(messageHub.Subscribe <TaskState>(OnTaskAction));
        }
        public IActionResult GitGet(string access_token)
        {
            ResponseModel response = new GitInfo().AuthoriseGit(access_token);

            return(Ok(response));
        }
Beispiel #29
0
        public IList <MutationDocumentFilterItem> CreateGitFilterItems(string solutionPath, GitInfo gitInfo, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            var filterItems = new List <MutationDocumentFilterItem>();

            if (gitInfo != null && gitInfo.GenerateFilterFromDiffWithMaster)
            {
                Log.Info("Creating filter items from git diff with master");
                filterItems.AddRange(_diffCreator.GetFilterItemsFromDiff(Path.GetDirectoryName(solutionPath)));
            }

            return(filterItems);
        }
Beispiel #30
0
        public async Task <GitInfo> GetInfoAsync(string directoryPath)
        {
            _ = directoryPath ?? throw new ArgumentNullException(nameof(directoryPath));

            return(await Task.Run(
                       () =>
            {
                _logger.Trace("Getting Git info...");
                if (!Repository.IsValid(directoryPath))
                {
                    _logger.Debug("Not a Git repository...");
                    return null;
                }

                var repo = new Repository(directoryPath);

                var branches = repo.Branches.Where(x => !x.IsRemote).OrderByDescending(x => x.Tip.Author.When).ToList();
                var status = repo.RetrieveStatus();
                var isDirty = status.IsDirty;
                var branch = branches.Single(x => x.CanonicalName == repo.Head.CanonicalName);
                var uncommittedFilesCount = 0;
                string[] commitMessages;
                if (branch.CanonicalName != "master")
                {
                    _logger.Trace("Calculating commits count...");
                    uncommittedFilesCount = status.Added.Count() + status.Modified.Count() + status.Removed.Count();
                    _logger.Trace("Getting commits messages...");
                    commitMessages = GetCommitMessagesFromBranchAsync(branch, repo).ToArray();
                    _logger.Debug("Got commit messages and count");
                }
                else
                {
                    commitMessages = new string[0];
                }

                // var master = repo.Branches["master"];
                // var nonMergeCommits = GetCommitsDiff(repo, master)
                // .Where(x => x.Parents.Count() == 1)
                // .Where(
                // x =>
                // {
                // var branches = ListBranchesContainingCommit(repo, x.Sha).ToArray();
                // return branches.Length == 1 && branches.Single().CanonicalName == repo.Head.CanonicalName;
                // })
                // .ToArray();
                // commitMessages = nonMergeCommits.Select(x => BeautifyMessage(x.Message)).Distinct().ToArray();
                // nonMergeBranchCommitsCount = nonMergeCommits.Length;
                // }
                // else
                // {
                // nonMergeBranchCommitsCount = repo.Head.Commits.Count();
                // commitMessages = new[]
                // {
                // BeautifyMessage(repo.Head.Tip.Message)
                // };
                // }

                var conflictsCount = repo.Index.Conflicts.Count();
                var gitInfo = new GitInfo(repo, commitMessages.Distinct().ToArray(), branch, uncommittedFilesCount, isDirty, commitMessages.Length, conflictsCount, branches);

                _logger.Debug("Got Git info");
                return gitInfo;
            })
                   .ConfigureAwait(false));
        }