Пример #1
0
        public override async Task <IEnumerable <IIssueTrackerIssue> > EnumerateIssuesAsync(IIssueSourceEnumerationContext context)
        {
            var credentials = this.TryGetCredentials <GitLabCredentials>();

            if (credentials == null)
            {
                throw new InvalidOperationException("Credentials must be supplied to enumerate GitLab issues.");
            }

            string projectName = AH.CoalesceString(this.ProjectName, credentials.ProjectName);

            if (string.IsNullOrEmpty(projectName))
            {
                throw new InvalidOperationException("A project name must be defined in either the issue source or associated GitLab credentials in order to enumerate GitLab issues.");
            }

            var client = new GitLabClient(credentials.ApiUrl, credentials.UserName, credentials.Password, credentials.GroupName);

            var filter = new GitLabIssueFilter
            {
                Milestone = this.MilestoneTitle,
                Labels    = this.Labels,
                CustomFilterQueryString = this.CustomFilterQueryString
            };

            var issues = await client.GetIssuesAsync(projectName, filter, CancellationToken.None).ConfigureAwait(false);

            return(from i in issues
                   select new GitLabIssue(i));
        }
Пример #2
0
 public void InitializeGitLabClient(string serverUrl, string token)
 {
     if (!string.IsNullOrWhiteSpace(serverUrl) && !string.IsNullOrWhiteSpace(token))
     {
         _gitLabClient = new GitLabClient(serverUrl, token);
     }
 }
        public async Task <DiscussionDto[]> GetDiscussionsAsync()
        {
            this.IsPending = true;
            try
            {
                if (this.SelectedProjectId == null)
                {
                    throw new InvalidOperationException("SelectedProjectId is null");
                }

                if (this.SelectedMergeRequestInternalId == null)
                {
                    throw new InvalidOperationException("SelectedMergeRequestInternalId is null");
                }

                using (var client = new GitLabClient(this.GitOptions))
                {
                    var discussions = await client.GetDiscussionsAsync(this.SelectedProjectId.Value, this.SelectedMergeRequestInternalId.Value);

                    return(discussions);
                }
            }
            catch (Exception ex)
            {
                this.errorService.AddError(ex);
            }
            finally
            {
                this.IsPending = false;
            }

            return(new DiscussionDto[0]);
        }
Пример #4
0
        public IGitLabClient CreateClient(string hostName)
        {
            var accessToken = m_Configuration.Integrations.GitLab.AccessToken ?? "";
            var client      = new GitLabClient($"https://{hostName}/", accessToken);

            return(client);
        }
Пример #5
0
        /// <summary>
        /// Получить последние коммиты репозиториев GitLab'а
        /// </summary>
        public async Task <IEnumerable <RepositoryLastCommitDto> > GetRepositoriesLastCommit()
        {
            var configReposUrls = _repositoriesConfig.ReposInfo
                                  .Select(ri => ri.Url.ToLower())
                                  .ToList();

            var client = new GitLabClient(_gitLabConfig.ApiUrl, _gitLabConfig.PrivateToken);

            var projects = (await client.Projects.GetAsync())
                           .Where(pr => configReposUrls.Contains(pr.HttpUrlToRepo.ToLower()))
                           .Select(pr => new { pr.Id, pr.Name, pr.HttpUrlToRepo });

            var result = new ConcurrentBag <RepositoryLastCommitDto>();

            await Task.WhenAll(projects.Select(async pr =>
            {
                var lastCommit = (await client.Commits.GetAsync(pr.Id))[0];

                result.Add(new RepositoryLastCommitDto
                {
                    RepositoryName = pr.Name,
                    RepositoryUrl  = pr.HttpUrlToRepo,
                    Hash           = lastCommit.Id,
                    Date           = lastCommit.CommittedDate
                });
            }));

            return(result.OrderBy(r => r.RepositoryName).ToList());
        }
Пример #6
0
        static void Main(string[] args)
        {
            var options = dotnetCampus.Cli.CommandLine.Parse(args).As <Options>();

            var directoryInfo = new DirectoryInfo(@"f:\temp\WalhallchogehaiKirerlibarlerho\");
            var git           = new Git(directoryInfo);

            git.ExecuteCommand("add .");
            var(success, output) = git.ExecuteCommand("commit -m \"Format Code\"");
            if (success)
            {
                var branchName = $"t/bot/FormatCode_{DateTime.Now:yyMMddhhmmssfff}";

                git.CheckoutNewBranch(branchName);
                git.ExecuteCommand("push");

                var gitLabClient = new GitLabClient(options.GitlabUrl, options.GitlabToken);
                gitLabClient.MergeRequests.CreateAsync("",
                                                       new CreateMergeRequest(branchName, "dev", "[Bot] Automated PR to fix formatting errors"));
            }
            else
            {
                Console.WriteLine($"Do nothing.");
            }
        }
Пример #7
0
        public override async Task <PersistedConfiguration> CollectAsync(IOperationCollectionContext context)
        {
            var gitlab     = new GitLabClient(this.Template.ApiUrl, this.Template.UserName, this.Template.Password, this.Template.GroupName);
            var milestones = await gitlab.GetMilestonesAsync(this.Template.ProjectName, null, context.CancellationToken).ConfigureAwait(false);

            var milestone = milestones.FirstOrDefault(m => string.Equals(m["title"]?.ToString() ?? string.Empty, this.Template.Title, StringComparison.OrdinalIgnoreCase));

            if (milestone == null)
            {
                return(new GitLabMilestoneConfiguration
                {
                    Exists = false
                });
            }

            return(new GitLabMilestoneConfiguration
            {
                Exists = true,
                Title = milestone["title"]?.ToString() ?? string.Empty,
                Description = milestone["description"]?.ToString() ?? string.Empty,
                StartDate = milestone["start_date"]?.ToString(),
                DueDate = milestone["due_date"]?.ToString(),
                State = (GitLabMilestoneConfiguration.OpenOrClosed)Enum.Parse(typeof(GitLabMilestoneConfiguration.OpenOrClosed), milestone["state"]?.ToString())
            });
        }
Пример #8
0
        static async Task Main(string[] args)
        {
            var client = new GitLabClient("https://gitlab.com", "pYeZ6b5FFR9_nttV1xEx");

            //var client = new GitLabClient("https://gitlab.com");
            //await client.LoginAsync("libgit2sharp", "pYeZ6b5FFR9_nttV1xEx");
            //Use it:
            // create a new issue.
            //await client.Issues.CreateAsync(new CreateIssueRequest("projectId", "issue title"));

            var projects = await client.Projects.GetAsync(options => options.IsMemberOf = true);

            var projectNames = projects.Select(p => p.Name);

            // list issues for a project  with specified assignee and labels.
            var issues = await client.Issues.GetAsync("12098724", o =>
            {
                //o.AssigneeId = 100
            });

            // create a new merge request featureBranch -> master.
            await client.MergeRequests.CreateAsync(new CreateMergeRequest("projectId", "featureBranch", "master", "Merge request title")
            {
                Labels      = new[] { "bugfix" },
                Description = "Implement feature"
            });
        }
Пример #9
0
        async internal Task ModifyNoteBodyAsync(MergeRequestDescriptor mrd, string discussionId, int noteId, string body)
        {
            GitLabClient client = new GitLabClient(mrd.HostName, Tools.Tools.GetAccessToken(mrd.HostName, Settings));

            try
            {
                await client.RunAsync(async (gitlab) =>
                                      await gitlab.Projects.Get(mrd.ProjectName).MergeRequests.Get(mrd.IId).
                                      Discussions.Get(discussionId).ModifyNoteTaskAsync(noteId,
                                                                                        new ModifyDiscussionNoteParameters
                {
                    Type = ModifyDiscussionNoteParameters.ModificationType.Body,
                    Body = body
                }));
            }
            catch (Exception ex)
            {
                Debug.Assert(!(ex is GitLabClientCancelled));
                if (ex is GitLabSharpException || ex is GitLabRequestException)
                {
                    ExceptionHandlers.Handle(ex, "Cannot update discussion text");
                    throw new OperatorException(ex);
                }
                throw;
            }
        }
Пример #10
0
        async internal Task ReplyAsync(MergeRequestDescriptor mrd, string discussionId, string body)
        {
            GitLabClient client = new GitLabClient(mrd.HostName, Tools.Tools.GetAccessToken(mrd.HostName, Settings));

            try
            {
                await client.RunAsync(async (gitlab) =>
                                      await gitlab.Projects.Get(mrd.ProjectName).MergeRequests.Get(mrd.IId).
                                      Discussions.Get(discussionId).CreateNewNoteTaskAsync(
                                          new CreateNewNoteParameters
                {
                    Body = body
                }));
            }
            catch (Exception ex)
            {
                Debug.Assert(!(ex is GitLabClientCancelled));
                if (ex is GitLabSharpException || ex is GitLabRequestException)
                {
                    ExceptionHandlers.Handle(ex, "Cannot create a reply to discussion");
                    throw new OperatorException(ex);
                }
                throw;
            }
        }
Пример #11
0
        public async Task <bool> Connect()
        {
            var cfg   = _configProvider.GitCfg;
            var token = _configProvider.AccessToken;

            try
            {
                _client = new GitLabClient($"{cfg.Url}", $"{token.PrivateToken}");

                // No method to check if client connected, so checking for projects
                var projects = await _client.Projects.GetAsync();

                if (!projects.Any())
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                _logger.Error($"Could not find any projects on host: {cfg.Url}");
                _logger.Error($"{e.Message}");
                return(false);
            }

            return(true);
        }
        public async Task <DiscussionDto> AddDiscussion(CreateDiscussionDto createDiscussionDto, string body)
        {
            this.IsPending = true;
            try
            {
                if (this.SelectedProjectId == null)
                {
                    throw new InvalidOperationException("SelectedProjectId is null");
                }

                if (this.SelectedMergeRequestInternalId == null)
                {
                    throw new InvalidOperationException("SelectedMergeRequestInternalId is null");
                }

                using (var client = new GitLabClient(this.GitOptions))
                {
                    return(await client.AddDiscussion(this.GitOptions.SelectedProjectId.Value, this.SelectedMergeRequestInternalId.Value, createDiscussionDto, body));
                }
            }
            catch (Exception ex)
            {
                this.errorService.AddError(ex);
                return(null);
            }
            finally
            {
                this.IsPending = false;
            }
        }
        public async Task <IEnumerable <string> > GetSuggestionsAsync(IComponentConfiguration config)
        {
            var credentialName = config["CredentialName"];

            if (string.IsNullOrEmpty(credentialName))
            {
                return(Enumerable.Empty <string>());
            }

            var credentials = ResourceCredentials.Create <GitLabCredentials>(credentialName);

            string ownerName      = AH.CoalesceString(credentials.GroupName, credentials.UserName);
            string repositoryName = AH.CoalesceString(config["ProjectName"], credentials.ProjectName);

            if (string.IsNullOrEmpty(ownerName) || string.IsNullOrEmpty(repositoryName))
            {
                return(Enumerable.Empty <string>());
            }

            var client = new GitLabClient(credentials.ApiUrl, credentials.UserName, credentials.Password, credentials.GroupName);

            var milestones = await client.GetMilestonesAsync(repositoryName, "open", CancellationToken.None).ConfigureAwait(false);

            var titles = from m in milestones
                         let title = m["title"]?.ToString()
                                     where !string.IsNullOrEmpty(title)
                                     select title;

            if (SDK.ProductName == "BuildMaster")
            {
                titles = new[] { "$ReleaseName", "$ReleaseNumber" }.Concat(titles);
            }

            return(titles);
        }
Пример #14
0
        public async Task <IEnumerable <string> > GetSuggestionsAsync(IComponentConfiguration config)
        {
            var credentialName = config["CredentialName"];

            if (string.IsNullOrEmpty(credentialName))
            {
                return(Enumerable.Empty <string>());
            }

            var credentials = ResourceCredentials.Create <GitLabCredentials>(credentialName);

            string ownerName = AH.CoalesceString(credentials.GroupName, credentials.UserName);

            if (string.IsNullOrEmpty(ownerName))
            {
                return(Enumerable.Empty <string>());
            }

            var client = new GitLabClient(credentials.ApiUrl, credentials.UserName, credentials.Password, credentials.GroupName);
            var repos  = await client.GetProjectsAsync(CancellationToken.None).ConfigureAwait(false);


            var names = from m in repos
                        let name = m["path_with_namespace"]?.ToString()
                                   where !string.IsNullOrEmpty(name)
                                   select name;

            if (SDK.ProductName == "BuildMaster")
            {
                names = new[] { $"{ownerName}/$ApplicationName" }.Concat(names);
            }
            return(names);
        }
        public async Task <IEnumerable <MergeRequestDto> > GetMergeRequestsAsync()
        {
            this.IsPending = true;
            try
            {
                if (this.SelectedProjectId == null)
                {
                    throw new InvalidOperationException("SelectedProjectId is null");
                }

                using (var client = new GitLabClient(this.GitOptions))
                {
                    var requests = await client.GetMergeRequestsAsync(this.GitOptions.SelectedProjectId.Value);

                    return(requests);
                }
            }
            catch (Exception ex)
            {
                this.errorService.AddError(ex);
                return(new MergeRequestDto[0]);
            }
            finally
            {
                this.IsPending = false;
            }
        }
Пример #16
0
        public override async Task ExecuteAsync(IOperationExecutionContext context)
        {
            var gitlab = new GitLabClient(this.ApiUrl, this.UserName, this.Password, this.GroupName);
            var data   = new Dictionary <string, object> {
                ["title"] = this.Title
            };

            if (this.AdditionalProperties != null)
            {
                foreach (var p in this.AdditionalProperties)
                {
                    data.Add(p.Key, p.Key == "confidential" ? bool.Parse(p.Value?.ToString()) : p.Key == "weight" ? int.Parse(p.Value?.ToString()) : p.Value);
                }
            }
            if (!string.IsNullOrEmpty(this.Body))
            {
                data.Add("description", this.Body);
            }
            if (this.Labels != null)
            {
                data.Add("labels", string.Join(",", this.Labels));
            }
            if (this.Assignees != null)
            {
                data.Add("assignee_ids", (await Task.WhenAll(this.Assignees.Select(name => gitlab.FindUserAsync(name, context.CancellationToken))).ConfigureAwait(false)).Where(id => id.HasValue));
            }
            if (!string.IsNullOrEmpty(this.Milestone))
            {
                data.Add("milestone_id", await gitlab.CreateMilestoneAsync(this.Milestone, this.ProjectName, context.CancellationToken).ConfigureAwait(false));
            }
            this.IssueId = await gitlab.CreateIssueAsync(this.ProjectName, data, context.CancellationToken).ConfigureAwait(false);
        }
        public async Task <Pipeline> FetchPipeLineByBranch(string apiHost, string apiKey, string apiProjectId, string branchName)
        {
            var apiClient  = new GitLabClient(apiHost, apiKey);
            var branchPipe = await apiClient.GetPipelineByBranch(apiProjectId, branchName);

            return(await FetchPipelineById(apiHost, apiKey, apiProjectId, branchPipe.Id));
        }
Пример #18
0
        async internal Task AddSpanAsync(bool add, TimeSpan span, MergeRequestDescriptor mrd)
        {
            GitLabClient client = new GitLabClient(mrd.HostName, Tools.Tools.GetAccessToken(mrd.HostName, Settings));

            try
            {
                await client.RunAsync(async (gitlab) =>
                                      await gitlab.Projects.Get(mrd.ProjectName).MergeRequests.Get(mrd.IId).AddSpentTimeAsync(
                                          new AddSpentTimeParameters
                {
                    Add  = add,
                    Span = span
                }));
            }
            catch (Exception ex)
            {
                Debug.Assert(!(ex is GitLabClientCancelled));
                if (ex is GitLabSharpException || ex is GitLabRequestException)
                {
                    ExceptionHandlers.Handle(ex, "Cannot send tracked time to GitLab");
                    throw new OperatorException(ex);
                }
                throw;
            }
        }
        public async Task <IEnumerable <string> > GetSuggestionsAsync(IComponentConfiguration config)
        {
            string ownerName = AH.CoalesceString(config[nameof(GitLabCredentials.GroupName)], config[nameof(GitLabCredentials.UserName)]);

            if (string.IsNullOrEmpty(ownerName))
            {
                return(Enumerable.Empty <string>());
            }

            GitLabClient client;

            try
            {
                client = new GitLabClient(config[nameof(GitLabCredentials.ApiUrl)], config[nameof(GitLabCredentials.UserName)], AH.CreateSecureString(config[nameof(GitLabCredentials.Password)].ToString()), config[nameof(GitLabCredentials.GroupName)]);
            }
            catch (InvalidOperationException)
            {
                return(Enumerable.Empty <string>());
            }

            var groups = await client.GetGroupsAsync(CancellationToken.None).ConfigureAwait(false);

            var names = from m in groups
                        let name = m["full_path"]?.ToString()
                                   where !string.IsNullOrEmpty(name)
                                   select name;

            return(names);
        }
Пример #20
0
        async internal Task ResolveDiscussionAsync(MergeRequestDescriptor mrd, string discussionId, bool resolved)
        {
            GitLabClient client = new GitLabClient(mrd.HostName, Tools.Tools.GetAccessToken(mrd.HostName, Settings));

            try
            {
                await client.RunAsync(async (gitlab) =>
                                      await gitlab.Projects.Get(mrd.ProjectName).MergeRequests.Get(mrd.IId).
                                      Discussions.Get(discussionId).ResolveTaskAsync(
                                          new ResolveThreadParameters
                {
                    Resolve = resolved
                }));
            }
            catch (Exception ex)
            {
                Debug.Assert(!(ex is GitLabClientCancelled));
                if (ex is GitLabSharpException || ex is GitLabRequestException)
                {
                    ExceptionHandlers.Handle(ex, "Cannot toggle 'Resolved' state of a discussion");
                    throw new OperatorException(ex);
                }
                throw;
            }
        }
Пример #21
0
        public async Task <Graph> GetOneGroupMapAsync(string groupName, Graph map, GitLabClient client)
        {
            var group = await client.Groups.GetAsync(groupName);

            foreach (var project in group.Projects)
            {
                if (project.Name == "HelloAPI")
                {
                    continue; //template project shouldn't be counted
                }
                try
                {
                    var packages = await ProcessXmlAsync(client, project, Helper.NeedNoPublicPackages);

                    map = Helper.AddPackagesInMap(project.Name, packages, map);
                    Console.WriteLine($" Archived: {project.Name}");
                }
                catch (Exception e)
                {
                    // log projects cannot be read dependency this way
                    Console.WriteLine($"Failed: {project.Name}, {e.Message}");
                }
            }

            return(map);
        }
Пример #22
0
        public override async Task ConfigureAsync(IOperationExecutionContext context)
        {
            var gitlab = new GitLabClient(this.Template.ApiUrl, this.Template.UserName, this.Template.Password, this.Template.GroupName);
            var id     = await gitlab.CreateMilestoneAsync(this.Template.Title, this.Template.ProjectName, context.CancellationToken).ConfigureAwait(false);

            var data = new Dictionary <string, object> {
                ["title"] = this.Template.Title
            };

            if (this.Template.StartDate != null)
            {
                data.Add("start_date", AH.NullIf(this.Template.StartDate, string.Empty));
            }
            if (this.Template.DueDate != null)
            {
                data.Add("due_date", AH.NullIf(this.Template.DueDate, string.Empty));
            }
            if (this.Template.Description != null)
            {
                data.Add("description", this.Template.Description);
            }
            if (this.Template.State.HasValue)
            {
                data.Add("state_event", this.Template.State == GitLabMilestoneConfiguration.OpenOrClosed.open ? "activate" : "close");
            }

            await gitlab.UpdateMilestoneAsync(id, this.Template.ProjectName, data, context.CancellationToken).ConfigureAwait(false);
        }
        public async Task <string> GetFileContentAsync(string branch, string path)
        {
            this.IsPending = true;
            try
            {
                if (string.IsNullOrWhiteSpace(branch))
                {
                    throw new ArgumentNullException(nameof(branch));
                }

                if (string.IsNullOrWhiteSpace(path))
                {
                    throw new ArgumentNullException(nameof(path));
                }

                using (var client = new GitLabClient(this.GitOptions))
                {
                    var file = await client.GetFileAsync(this.SelectedProjectId.Value, branch, path);

                    var fileBlob = await client.GetFileBlobAsync(this.SelectedProjectId.Value, file.BlobId);

                    var fileContent = Encoding.UTF8.GetString(Convert.FromBase64String(fileBlob.Content));
                    return(fileContent);
                }
            }
            catch (Exception ex)
            {
                this.errorService.AddError(ex);
                return(null);
            }
            finally
            {
                this.IsPending = false;
            }
        }
Пример #24
0
        public async Task <IEnumerable <string> > GetSuggestionsAsync(IComponentConfiguration config)
        {
            var credentialName = config["CredentialName"];

            if (string.IsNullOrEmpty(credentialName))
            {
                return(Enumerable.Empty <string>());
            }

            var credentials = ResourceCredentials.Create <GitLabCredentials>(credentialName);

            string ownerName = AH.CoalesceString(credentials.GroupName, credentials.UserName);

            if (string.IsNullOrEmpty(ownerName))
            {
                return(Enumerable.Empty <string>());
            }

            var client = new GitLabClient(credentials.ApiUrl, credentials.UserName, credentials.Password, credentials.GroupName);
            var groups = await client.GetGroupsAsync(CancellationToken.None).ConfigureAwait(false);

            var names = from m in groups
                        let name = m["full_path"]?.ToString()
                                   where !string.IsNullOrEmpty(name)
                                   select name;

            return(names);
        }
Пример #25
0
        // Purpose: find public packages used in github projects (.net framework/.net core)
        // => to generate KnownPublicPackages
        public async Task PrintAllPackagesAsync()
        {
            var client = new GitLabClient(serviceBase, token);

            var searchResult = new List <string>();

            foreach (string groupName in gitlabGroups)
            {
                var group = await client.Groups.GetAsync(groupName);

                foreach (var project in group.Projects)
                {
                    try
                    {
                        var packages = await ProcessXmlAsync(client, project, Helper.NeedAllPackages);

                        AddPackages(searchResult, packages);
                        Console.WriteLine($" Checked: {project.Name}");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Failed to get csproj: {project.Name}, {e.Message}");
                    }
                }
            }

            Console.WriteLine("Final Result: ");
            foreach (string r in searchResult.OrderBy(r => r))
            {
                Console.WriteLine(r);
            }
        }
Пример #26
0
        public IGitLabClient CreateClient(string hostName, string?accessToken)
        {
            accessToken ??= "";
            var client = new GitLabClient($"https://{hostName}/", accessToken);

            return(client);
        }
Пример #27
0
        private async Task QueryGitLab()
        {
            GitLabClient client;

            if (string.IsNullOrEmpty(username.Text))
            {
                client = new GitLabClient(host.Text, password.Text);
            }
            else
            {
                client = new GitLabClient(host.Text);
                var session = await client.LoginAsync(username.Text, password.Text);
            }
            var list = await client.Projects.GetAsync();

            repositories.Items.Clear();
            foreach (var project in list)
            {
                if (ssh.Checked)
                {
                    repositories.Items.Add(project.SshUrlToRepo);
                }
                else
                {
                    repositories.Items.Add(project.HttpUrlToRepo);
                }
            }
        }
 public GitlabClientRepository(IPgmSettingManagerService pgmSettingManagerService)
 {
     _pgmSettingManagerService = pgmSettingManagerService;
     if (Settings != null)
     {
         _client = new GitLabClient("https://gitlab.com/", Settings.GitLabApiKey ?? "");
     }
 }
Пример #29
0
        public override async Task <IEnumerable <string> > EnumerateValuesAsync(ValueEnumerationContext context)
        {
            this.SetValues(environmentId: null, applicationId: context.ProjectId);

            var client = new GitLabClient(this.ApiUrl, this.UserName, this.Password, this.GroupName);

            return(await client.GetBranchesAsync(this.ProjectName, CancellationToken.None));
        }
 private GitLabModel(string gitLabAddress, string gitLabKey, GitLabClient gitLabCLient, Project project, string favoriteGroupFullPath)
 {
     _gitLabAddress         = gitLabAddress;
     _gitLabKey             = gitLabKey;
     _gitLabCLient          = gitLabCLient;
     _project               = project;
     _favoriteGroupFullPath = favoriteGroupFullPath;
 }