Пример #1
0
        /// <summary>
        /// Push changes to branch
        /// </summary>
        /// <param name="teamProjectName"></param>
        /// <param name="gitRepoName"></param>
        /// <param name="branchRef"></param>
        /// <param name="branchOldId"></param>
        /// <param name="targetPath"></param>
        /// <param name="fileContent"></param>
        /// <param name="itemContentType"></param>
        /// <param name="versionControlChangeType"></param>
        /// <param name="commitComment"></param>
        private static void PushChanges(string teamProjectName, string gitRepoName, string branchRef, string branchOldId, string targetPath, string fileContent, ItemContentType itemContentType, VersionControlChangeType versionControlChangeType, string commitComment)
        {
            GitRefUpdate branch = new GitRefUpdate();

            branch.OldObjectId = branchOldId;
            branch.Name        = branchRef;

            GitCommitRef newCommit = new GitCommitRef();

            newCommit.Comment = commitComment;
            GitChange gitChange = new GitChange();

            gitChange.ChangeType = versionControlChangeType;
            gitChange.Item       = new GitItem()
            {
                Path = targetPath
            };
            gitChange.NewContent = new ItemContent()
            {
                Content = fileContent, ContentType = itemContentType
            };
            newCommit.Changes = new GitChange[] { gitChange };

            GitPush gitPush = new GitPush();

            gitPush.RefUpdates = new GitRefUpdate[] { branch };
            gitPush.Commits    = new GitCommitRef[] { newCommit };

            var pushResult = GitClient.CreatePushAsync(gitPush, teamProjectName, gitRepoName).Result;

            Console.WriteLine("Push id: " + pushResult.PushId);
        }
Пример #2
0
    public void GetChanges()
    {
        Process p      = GitManager.GitCommand("--no-pager log HEAD..FETCH_HEAD --format=\"%an%n%at\" --numstat " + path);
        string  output = p.StandardOutput.ReadToEnd(),
                error  = p.StandardError.ReadToEnd();

        if (error.Length > 0)
        {
            UnityEngine.Debug.Log(error);
        }

        string[]         lines    = output.Split(new char[] { System.Environment.NewLine[0], System.Environment.NewLine[1] });
        List <GitChange> changesL = new List <GitChange>();

        for (int i = 0; i < lines.Length - 4; i += 4)
        {
            GitChange change = new GitChange();
            change.author = lines[i];
            change.date   = lines[i + 1];
            string[] a = lines[i + 3].Split('	');
            change.additions = System.Convert.ToInt32(a[0]);
            change.deletions = System.Convert.ToInt32(a[1]);
            change.path      = a[2];
            changesL.Add(change);
        }
        changes = changesL.ToArray();
        p.WaitForExit();
        p.Close();
    }
Пример #3
0
        /// <summary>
        /// Push changes to remove, rename or move files
        /// </summary>
        /// <param name="teamProjectName"></param>
        /// <param name="gitRepoName"></param>
        /// <param name="branchRef"></param>
        /// <param name="branchOldId"></param>
        /// <param name="oldPath"></param>
        /// <param name="targetPath"></param>
        /// <param name="versionControlChangeType"></param>
        /// <param name="commitComment"></param>
        private static void PushChanges(string teamProjectName, string gitRepoName, string branchRef, string branchOldId, string oldPath, string targetPath, VersionControlChangeType versionControlChangeType, string commitComment)
        {
            GitRefUpdate branch = new GitRefUpdate();

            branch.OldObjectId = branchOldId;
            branch.Name        = branchRef;

            GitCommitRef newCommit = new GitCommitRef();

            newCommit.Comment = commitComment;
            GitChange gitChange = new GitChange();

            gitChange.ChangeType = versionControlChangeType;
            if (!string.IsNullOrEmpty(oldPath))
            {
                gitChange.SourceServerItem = oldPath;
            }
            gitChange.Item = new GitItem()
            {
                Path = targetPath
            };
            newCommit.Changes = new GitChange[] { gitChange };

            GitPush gitPush = new GitPush();

            gitPush.RefUpdates = new GitRefUpdate[] { branch };
            gitPush.Commits    = new GitCommitRef[] { newCommit };

            var pushResult = GitClient.CreatePushAsync(gitPush, teamProjectName, gitRepoName).Result;

            Console.WriteLine("Push id: " + pushResult.PushId);
        }
Пример #4
0
        public async Task CopyFolderToRepository(GitRepository sourceRepository, string directoryName, GitRepository targetRepository, ContentReplacer replacer)
        {
            string        refId             = new string('0', 40);
            string        defaultBranchName = "heads/master";
            List <GitRef> refs = null;

            try
            {
                refs = await Git.GetRefsAsync(targetRepository.Id, filter : defaultBranchName);

                if (refs.Count > 0)
                {
                    GitRef defaultBranch = refs.First();
                    refId = defaultBranch.ObjectId;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not get master ref", ex);
            }

            GitRefUpdate refUpdate = new GitRefUpdate()
            {
                Name        = "refs/heads/master",
                OldObjectId = refId
            };

            List <GitChange> changes = new List <GitChange>();

            List <GitItem> items = null;

            try
            {
                items = await Git.GetItemsAsync(sourceRepository.Id, scopePath : directoryName, recursionLevel : VersionControlRecursionType.Full);

                foreach (GitItem item in items)
                {
                    if (item.GitObjectType == GitObjectType.Blob)
                    {
                        Stream stream = await Git.GetItemContentAsync(repositoryId : sourceRepository.Id, path : item.Path);

                        StreamReader reader  = new StreamReader(stream);
                        string       content = reader.ReadToEnd();
                        string       newPath = item.Path.Remove(0, directoryName.Length);

                        if (replacer != null)
                        {
                            content = replacer.ReplaceContent(newPath, content);
                        }

                        GitChange change = new GitChange
                        {
                            ChangeType = VersionControlChangeType.Add,
                            Item       = new GitItem()
                            {
                                Path = newPath
                            },
                            NewContent = new ItemContent()
                            {
                                Content     = content,
                                ContentType = ItemContentType.RawText,
                            }
                        };
                        changes.Add(change);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error copying files", ex);
            }

            GitCommitRef newCommit = new GitCommitRef()
            {
                Comment = $"Copying files from {sourceRepository.Name}",
                Changes = changes.ToArray()
            };

            try
            {
                _ = await Git.CreatePushAsync(new GitPush()
                {
                    RefUpdates = new GitRefUpdate[] { refUpdate },
                    Commits    = new GitCommitRef[] { newCommit },
                }, targetRepository.Id);
            }
            catch (Exception ex)
            {
                throw new Exception("Error pushing commit", ex);
            }
        }
Пример #5
0
        async void ChurnFileStats(string url, string projName, string repoId, string repoName, GitChange gitChange, string pat, string currentcommit, string previouscommit, string email, string name)
        {
            string valuesjson = "";

            // Different valuesjson created based on whether file exists in currentcommit and previouscommit
            if (gitChange.Item.OriginalObjectId == null)
            {
                var values = new Dictionary <string, string>
                {
                    { "originalVersion", "GC" + previouscommit },
                    { "modifiedPath", gitChange.Item.Path },
                    { "modifiedVersion", "GC" + currentcommit },
                    { "partialDiff", "true" },
                    { "includeCharDiffs", "true" }
                };

                valuesjson = JsonConvert.SerializeObject(values, Formatting.Indented);
            }
            else if (gitChange.Item.ObjectId == null || gitChange.Item.ObjectId == "")
            {
                var values = new Dictionary <string, string>
                {
                    { "originalPath", gitChange.Item.Path },
                    { "originalVersion", "GC" + previouscommit },
                    { "modifiedVersion", "GC" + currentcommit },
                    { "partialDiff", "true" },
                    { "includeCharDiffs", "true" }
                };

                valuesjson = JsonConvert.SerializeObject(values, Formatting.Indented);
            }
            else
            {
                var values = new Dictionary <string, string>
                {
                    { "originalPath", gitChange.Item.Path },
                    { "originalVersion", "GC" + previouscommit },
                    { "modifiedPath", gitChange.Item.Path },
                    { "modifiedVersion", "GC" + currentcommit },
                    { "partialDiff", "true" },
                    { "includeCharDiffs", "true" }
                };
                var content = new FormUrlEncodedContent(values);
                valuesjson = JsonConvert.SerializeObject(values, Formatting.Indented);
            }

            string endpoint = url + projName + "/_api/_versioncontrol/fileDiff?__v=5&diffParameters=" + valuesjson + "&repositoryId=" + repoId;


            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                           Convert.ToBase64String(
                                                                                               System.Text.ASCIIEncoding.ASCII.GetBytes(
                                                                                                   string.Format("{0}:{1}", "", pat))));

                using (HttpResponseMessage response = client.GetAsync(endpoint).Result)
                {
                    try
                    {
                        response.EnsureSuccessStatusCode();

                        string responseBody = await response.Content.ReadAsStringAsync();

                        // Read response into a FileDiff object
                        var result = JsonConvert.DeserializeObject <FileDiff>(responseBody);

                        if (result != null)
                        {
                            foreach (var block in result.blocks)
                            {
                                if (block.changeType == 1)
                                {
                                    var diff = block.mLinesCount - block.oLinesCount;

                                    var obj = userStats.FirstOrDefault(x => x.email == email && x.projectName == projName && x.repoName == repoName);
                                    if (obj != null)
                                    {
                                        obj.linesAdded = obj.linesAdded + diff;
                                    }
                                    else
                                    {
                                        UserStat user = new UserStat();
                                        user.projectName = projName;
                                        user.repoName    = repoName;
                                        user.email       = email;
                                        user.name        = name;
                                        user.linesAdded  = diff;
                                        userStats.Add(user);
                                    }
                                }
                                else if (block.changeType == 2)
                                {
                                    var diff = block.oLinesCount - block.mLinesCount;

                                    var obj = userStats.FirstOrDefault(x => x.email == email && x.projectName == projName && x.repoName == repoName);
                                    if (obj != null)
                                    {
                                        obj.linesRemoved = obj.linesRemoved + diff;
                                    }
                                    else
                                    {
                                        UserStat user = new UserStat();
                                        user.projectName  = projName;
                                        user.repoName     = repoName;
                                        user.email        = email;
                                        user.name         = name;
                                        user.linesRemoved = diff;
                                        userStats.Add(user);
                                    }
                                }
                                else if (block.changeType == 3)
                                {
                                    var obj = userStats.FirstOrDefault(x => x.email == email && x.projectName == projName && x.repoName == repoName);
                                    if (obj != null)
                                    {
                                        obj.linesModified = obj.linesModified + block.mLinesCount;
                                    }
                                    else
                                    {
                                        UserStat user = new UserStat();
                                        user.projectName   = projName;
                                        user.repoName      = repoName;
                                        user.email         = email;
                                        user.name          = name;
                                        user.linesModified = block.mLinesCount;
                                        userStats.Add(user);
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        // An error occured, one possibility is that a non success status code returned
                    }
                }
            }
        }
Пример #6
0
 internal GitChangedPath(string path, GitChange change)
 {
     Path   = path;
     Change = change;
 }