Beispiel #1
0
        /// <summary>
        /// FillCommitDetails
        /// </summary>
        /// <param name="changeRequest"></param>
        /// <returns></returns>
        public static CommitObject FillCommitDetails(ChangeRequest changeRequest)
        {
            try
            {
                var refUpdate = new Refupdate
                {
                    name        = changeRequest.SourceBranchName,
                    oldObjectId = changeRequest.Lastcomitid
                };

                var commit = new Commit
                {
                    comment = changeRequest.Comments
                };
                Auther auther = new Auther
                {
                    date = changeRequest.CommitDate,
                    name = changeRequest.AutherName
                };
                commit.auther = auther;
                Change[] changes = new Change[changeRequest.RequestDetails.Count()];
                int      i       = 0;
                foreach (var item in changeRequest.RequestDetails)
                {
                    changes[i] = new Change
                    {
                        changeType = item.ChangeType,//"add",
                        item       = new Item {
                            path = @"/" + item.FileDestinationPath + @"/" + item.FileName
                        },
                        newContent = new Newcontent {
                            content = item.FileContent, contentType = item.ContentType
                        }
                    };
                    i = i + 1;
                }
                commit.changes = changes;

                var payload = new CommitObject {
                    refUpdates = new Refupdate[] { refUpdate }, commits = new Commit[] { commit }
                };

                return(payload);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Commit API Call
        /// </summary>
        /// <param name="commitInputDetails"></param>
        /// <returns></returns>
        public static async Task <string> Commit(string patToken, CommitObject commitInputDetails, Uri AzureDevopsBaseURL)
        {
            string responseContent = string.Empty;

            try
            {
                //use the httpclient
                using (var client = new HttpClient())
                {
                    if (AzureDevopsBaseURL != null)
                    {
                        HTTPClientHelper clientHelper = new HTTPClientHelper(AzureDevopsBaseURL.ToString());
                        client.BaseAddress = new Uri(clientHelper.GetAzureDevopsPushURL());
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", patToken);

                        // Serialize our concrete class into a JSON String
                        var stringPayload = JsonConvert.SerializeObject(commitInputDetails);

                        // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
                        var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");


                        //connect to the REST endpoint
                        HttpResponseMessage httpResponse = client.PostAsync("", httpContent).Result;
                        httpContent.Dispose();
                        //check to see if we have a successful response
                        //if (httpResponse.IsSuccessStatusCode)
                        {
                            responseContent = await httpResponse.Content.ReadAsStringAsync();
                        }
                    }
                }

                return(responseContent);
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #3
0
        public string CreateCommitObject(string treeHash)
        {
            var user = new User
            {
                UserName  = UserName,
                UserEmail = UserEmail,
                TimeStamp = TimeStamp
            };

            var commitObject = new CommitObject
            {
                CommitMessage = $"Commit {CommitCounter}",
                Author        = user,
                Committer     = user,
                Parent        = PreviousCommit,
                Tree          = treeHash
            };

            commitObject.SetHash();
            CommitObjects.Add(commitObject);

            return(commitObject.Hash);
        }
Beispiel #4
0
        public string Commit(CommitObject commits, [FromUri] string token)
        {
            string apikey = string.Empty;
            string result = string.Empty;

            CurrentUser = new UserDto(new User()
            {
                ProjectGroups = new List <ProjectGroupMembership>()
                {
                    new ProjectGroupMembership()
                    {
                        ProjectGroupId = Countersoft.Gemini.Commons.Constants.GlobalGroupAdministrators, UserId = 0
                    }
                }
            });
            UserContext.User               = CurrentUser;
            PermissionsManager             = PermissionsManager.Copy(CurrentUser);
            UserContext.PermissionsManager = PermissionsManager;

            if (Request.Headers.Authorization != null && Request.Headers.Authorization.Parameter != null)
            {
                var authDetails = Encoding.Default.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
                if (authDetails.Length == 2)
                {
                    apikey = authDetails[0];
                }
            }
            else if (token != null)
            {
                apikey = token;
            }

            if (apikey.Length == 0 || GeminiApp.Config.ApiKey.Length == 0 || !apikey.StartsWith(GeminiApp.Config.ApiKey, StringComparison.InvariantCultureIgnoreCase))
            {
                string error;

                if (GeminiApp.Config.ApiKey.Length == 0)
                {
                    error = "Web.config is missing API key";
                }
                else
                {
                    error = "Wrong API key: " + apikey;
                }

                GeminiApp.LogException(new Exception(error)
                {
                    Source = SourceControlProvider.GitHub.ToString()
                }, false);

                return(error);
            }

            if (commits == null)
            {
                try
                {
                    var body = Request.Content.ReadAsStringAsync();
                    body.Wait();
                    GeminiApp.LogException("Null CodeCommit", string.Concat("Null CodeCommit - ", body.Result), false);
                }
                catch
                {
                    try
                    {
                        GeminiApp.LogException("Null CodeCommit", "Null CodeCommit - Empty!", false);
                    }
                    catch
                    {
                    }
                }
                return(string.Empty);
            }

            foreach (var commit in commits.commits)
            {
                Regex           ex      = new Regex("GEM:(?<issueid>[0-9]+)", RegexOptions.IgnoreCase);
                MatchCollection matches = ex.Matches(commit.message);

                if (matches.Count > 0)
                {
                    var baseUrl = commits.repository.url.ReplaceIgnoreCase("https://github.com/", "https://api.github.com/");

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

                    var commitIndex = commit.url.IndexOf("commit");
                    if (commitIndex != -1)
                    {
                        var url = string.Concat(commit.url.Remove(commitIndex, commit.url.Length - commitIndex), "blob/master/");

                        for (int i = 0; i < commit.added.Length; i++)
                        {
                            filesModified.Add(string.Concat("{\"Filename\":\"", commit.added[i], "\", \"FileId\":\"", string.Empty, "\",\"PreviousFileRevisionId\":\"", string.Empty, "\" }"));
                        }

                        for (int i = 0; i < commit.modified.Length; i++)
                        {
                            filesModified.Add(string.Concat("{\"Filename\":\"", commit.modified[i], "\",\"FileId\":\"", string.Empty, "\",\"PreviousFileRevisionId\":\"", string.Empty, "\"}"));
                        }

                        for (int i = 0; i < commit.removed.Length; i++)
                        {
                            filesModified.Add(string.Concat("{\"Filename\":\"", commit.removed[i], "\",\"FileId\":\"", string.Empty, "\",\"PreviousFileRevisionId\":\"", string.Empty, "\"}"));
                        }
                    }

                    CodeCommit codeCommit = new CodeCommit();
                    codeCommit.Provider = SourceControlProvider.GitHub;
                    codeCommit.Comment  = commit.message;
                    codeCommit.Fullname = commit.author.name;
                    codeCommit.Data     = string.Concat("{\"RevisionId\":\"", commit.id, "\",\"PreviousRevisionId\":\"", string.Empty, "\",\"Files\":[", string.Join(",", filesModified.ToArray()), "],\"RepositoryName\":\"", commits.repository.name, "\",\"RepositoryUrl\":\"", baseUrl, "\",\"IsPrivate\":\"", commits.repository.PRIVATE, "\"}");

                    commit.message = ex.Replace(commit.message, string.Empty);

                    List <int> issuesAlreadyProcessed = new List <int>();

                    foreach (Match match in matches)
                    {
                        var issue = IssueManager.Get(match.ToString().Remove(0, 4).ToInt());

                        if (issue != null && !issuesAlreadyProcessed.Contains(issue.Id))
                        {
                            codeCommit.IssueId = issue.Id;
                            GeminiContext.CodeCommits.Create(codeCommit);
                            issuesAlreadyProcessed.Add(issue.Id);

                            try
                            {
                                if (match.Index + match.Length + 1 + 5 <= codeCommit.Comment.Length)
                                {
                                    var time   = codeCommit.Comment.Substring(match.Index + match.Length + 1, 5);
                                    var timeEx = new System.Text.RegularExpressions.Regex("[0-9][0-9]:[0-9][0-9]");
                                    var m      = timeEx.Match(time);
                                    if (m.Success)
                                    {
                                        // Okay, log time!
                                        var timeTypes = MetaManager.TimeTypeGetAll(issue.Project.TemplateId);
                                        if (timeTypes.Count > 0)
                                        {
                                            // Let's try and find the user
                                            var user = commit.author.email.HasValue() ? Cache.Users.Find(u => u.Username.Equals(commit.author.email, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                         u.Email.Equals(commit.author.email, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                         u.Fullname.Equals(commit.author.email, StringComparison.InvariantCultureIgnoreCase)) : null;

                                            if (user == null)
                                            {
                                                user = commit.author.name.HasValue() ? Cache.Users.Find(u => u.Username.Equals(commit.author.name, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                        u.Email.Equals(commit.author.name, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                        u.Fullname.Equals(commit.author.name, StringComparison.InvariantCultureIgnoreCase)) : null;
                                            }
                                            var timeEntry = new IssueTimeTracking();
                                            timeEntry.IssueId    = issue.Id;
                                            timeEntry.ProjectId  = issue.Entity.ProjectId;
                                            timeEntry.Comment    = codeCommit.Comment.ToMax(1990);
                                            timeEntry.EntryDate  = DateTime.Now;
                                            timeEntry.Hours      = m.Value.Substring(0, 2).ToInt();
                                            timeEntry.Minutes    = m.Value.Substring(3, 2).ToInt();
                                            timeEntry.TimeTypeId = timeTypes[0].Entity.Id;
                                            timeEntry.UserId     = user == null ? Countersoft.Gemini.Commons.Constants.SystemAccountUserId : user.Id;
                                            TimeTrackingManager.Create(timeEntry);
                                        }
                                    }
                                }
                            }
                            catch (Exception timeEx)
                            {
                                LogManager.LogError(timeEx, "GitHub - Time log");
                            }
                        }
                    }
                }
            }

            return(result);
        }