public async Task FetchPullRequestChangesAsync( string project, string repositoryId, GitPullRequest pullRequest) { var pullRequestId = pullRequest.PullRequestId; var outputFile = $"{pullRequestId.ToString()}-changes.json"; var mergeCommitId = pullRequest.LastMergeCommit?.CommitId; if (mergeCommitId == null) { // A completed PR won't merge if the commit is already in the target branch info.Trace($"{pullRequestId} has no merge commit."); } else if (outputFileStore.Contains(outputFile)) { info.Trace($"{outputFile} already exists. Skipping call to the API."); } else { info.Trace($"Fetching changes for commit {mergeCommitId.ToString()} ..."); var changes = await gitClient.GetChangesAsync( project, commitId : mergeCommitId, repositoryId : repositoryId); info.Trace($"Writing output to {outputFile} ..."); await outputFileStore.WriteFileAsync( filename : outputFile, content : JsonConvert.SerializeObject(changes, Formatting.Indented)); } }
static void Main(string[] args) { var credentials = new VssAadCredential(); var messageHandler = new VssHttpMessageHandler(credentials, new VssHttpRequestSettings()); Uri uri = new Uri(@"https://microsoft.visualstudio.com/"); GitHttpClient gitHttpClient = new GitHttpClient(uri, messageHandler.Credentials); var Repositories = gitHttpClient.GetRepositoriesAsync().Result; GitRepository repository = Repositories.FirstOrDefault(r => r.Name.ToLowerInvariant() == "Localization".ToLowerInvariant()); var gitBranchStatuss = gitHttpClient.GetBranchesAsync(repository.Id).Result; GitBranchStats gitBranchStatus = gitBranchStatuss.FirstOrDefault(branch => branch.Name.ToLowerInvariant() == "master"); var descriptor = new GitVersionDescriptor() { Version = gitBranchStatus.Name, VersionOptions = GitVersionOptions.None, VersionType = GitVersionType.Branch }; //GitItem item = gitHttpClient.GetItemAsync(repositoryId: repository.Id, path: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", scopePath: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", recursionLevel: VersionControlRecursionType.OneLevel, includeContentMetadata: true, latestProcessedChange: true, download: true, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; VersionControlProjectInfo vvvvvv = new VersionControlProjectInfo(); List <GitItem> items = gitHttpClient.GetItemsAsync(repositoryId: repository.Id, scopePath: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", recursionLevel: VersionControlRecursionType.OneLevel, includeContentMetadata: true, latestProcessedChange: true, download: true, includeLinks: false, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; List <GitCommitRef> aaaa = gitHttpClient.GetCommitsAsync(repositoryId: repository.Id, searchCriteria: new GitQueryCommitsCriteria(), skip: null, top: null, userState: null, cancellationToken: new CancellationToken()).Result; GitCommitChanges gitCommitChanges = gitHttpClient.GetChangesAsync(items[0].CommitId, repositoryId: repository.Id, top: null, skip: null, userState: null, cancellationToken: new CancellationToken()).Result; Stream ssss = gitHttpClient.GetItemContentAsync(repositoryId: repository.Id, path: items[0].Path, recursionLevel: VersionControlRecursionType.None, includeContentMetadata: true, latestProcessedChange: true, download: true, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; using (MemoryStream memoryStream = new MemoryStream()) { ssss.CopyTo(memoryStream); // Use StreamReader to read MemoryStream created from byte array using (StreamReader streamReader = new StreamReader(new MemoryStream(memoryStream.ToArray()))) { string fileString = streamReader.ReadToEnd(); } } }
static void Main(string[] args) { IServiceProvider services = ServiceProviderBuilder.GetServiceProvider(args); IOptions <APIKeys> options = services.GetRequiredService <IOptions <APIKeys> >(); asciiArtClass asciiArt = new asciiArtClass(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("\n\n"); foreach (string line in asciiArt.azureArtArr) { Console.WriteLine(line); } //use the httpclient VssCredentials creds = new VssBasicCredential(string.Empty, options.Value.PAT); // Connect to Azure DevOps Services Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nConnecting..."); VssConnection connection = new VssConnection(new Uri(c_collectionUri + options.Value.OrgName), creds); ProjectHttpClient projClient = connection.GetClientAsync <ProjectHttpClient>().Result; IPagedList <TeamProjectReference> projects = projClient.GetProjects().Result; // Get a GitHttpClient to talk to the Git endpoints using (GitHttpClient gitClient = connection.GetClient <GitHttpClient>()) { foreach (TeamProjectReference p in projects) { Console.WriteLine("\n\nProject --- " + p.Name); List <GitRepository> repoList = gitClient.GetRepositoriesAsync(p.Name).Result; GitRepository masterRepo = repoList.Where(x => x.Name == "master" || x.Name == p.Name).FirstOrDefault(); Console.WriteLine("Repo Name --- " + masterRepo.Name); //set a filter to only return commits within the last 7 days GitQueryCommitsCriteria searches = new GitQueryCommitsCriteria(); searches.FromDate = DateTime.Now.AddDays(-7).ToShortDateString(); List <GitCommitRef> commits = gitClient.GetCommitsBatchAsync(searches, masterRepo.Id).Result; foreach (GitCommitRef cmt in commits) { Console.WriteLine("\n\nProject --- " + p.Name); Console.WriteLine("Repo Name --- " + masterRepo.Name); Console.WriteLine("\nCommit ID - #{0}\nBy - {1}\nEmail - {2}\nOn - {3}", cmt.CommitId, cmt.Author.Name, cmt.Author.Email, cmt.Author.Date.ToLongDateString(), cmt.Comment); GitCommitChanges changes = gitClient.GetChangesAsync(p.Name, cmt.CommitId, p.Name).Result; Console.WriteLine("Files:"); foreach (GitChange change in changes.Changes) { Console.WriteLine("{0}: {1}", change.ChangeType, change.Item.Path); } } } } Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("\n\n"); foreach (string line in asciiArt.tieFArtArr) { Console.WriteLine(line); } }
public TFSWork(string url, string pat) { // Initialize connection to azure devops personalaccesstoken = pat; var networkCredential = new VssBasicCredential(string.Empty, pat); VssConnection connection = new VssConnection(new Uri(url), networkCredential); // Initialize ProjectHttpClient and GitHttpClient var projclient = connection.GetClient <ProjectHttpClient>(); GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); // Get list of projects credentials have access to var projcollection = projclient.GetProjects().Result; foreach (var proj in projcollection) { // Get list of repos for a project List <GitRepository> repos = gitClient.GetRepositoriesAsync(proj.Id.ToString()).Result; // Set commits query criteria GitQueryCommitsCriteria criteria = new GitQueryCommitsCriteria() { // Add criterias in here, some examples: ToDate, FromDate, Top, FromCommitId }; foreach (GitRepository repo in repos) { // Get list of commits for a repo List <GitCommitRef> commits = gitClient.GetCommitsAsync(repo.Id, criteria).Result.OrderBy(x => x.Committer.Date).ToList(); for (int i = 0; i < commits.Count; i++) { // ASSUMPTION: i=0 is first commit and no code/files in this commit // TODO: update to handle all cases if (i != 0) { // Collect commit count var objc = userStats.FirstOrDefault(x => x.email == commits[i].Committer.Email && x.projectName == proj.Name && x.repoName == repo.Name); if (objc != null) { objc.commitCount = objc.commitCount + 1; objc.lastCommitDate = objc.lastCommitDate > commits[i].Committer.Date ? objc.lastCommitDate : commits[i].Committer.Date; } else { UserStat user = new UserStat(); user.projectName = proj.Name; user.repoName = repo.Name; user.email = commits[i].Committer.Email; user.name = commits[i].Committer.Name; user.commitCount = user.commitCount + 1; user.lastCommitDate = user.lastCommitDate > commits[i].Committer.Date ? user.lastCommitDate : commits[i].Committer.Date; userStats.Add(user); } // Get list of changes for a commit GitCommitChanges changes = gitClient.GetChangesAsync(commits[i].CommitId, repo.Id).Result; foreach (var change in changes.Changes) { // Only will collect stats pertaining to *.cs files if (change.Item.Path.EndsWith(".cs")) { // Collect file stats var obj = userStats.FirstOrDefault(x => x.email == commits[i].Committer.Email && x.projectName == proj.Name && x.repoName == repo.Name); if (obj != null) { if (change.ChangeType == VersionControlChangeType.Add) { obj.filesAdded = obj.filesAdded + 1; } else if (change.ChangeType == VersionControlChangeType.Delete) { obj.filesDeleted = obj.filesDeleted + 1; } else if (change.ChangeType == VersionControlChangeType.Edit) { obj.filesModified = obj.filesModified + 1; } } else { UserStat user = new UserStat(); user.projectName = proj.Name; user.repoName = repo.Name; user.email = commits[i].Committer.Email; user.name = commits[i].Committer.Name; if (change.ChangeType == VersionControlChangeType.Add) { user.filesAdded = user.filesAdded + 1; } else if (change.ChangeType == VersionControlChangeType.Delete) { user.filesDeleted = user.filesDeleted + 1; } else if (change.ChangeType == VersionControlChangeType.Edit) { user.filesModified = user.filesModified + 1; } userStats.Add(user); } // Collect code stats ChurnFileStats(url, proj.Name, repo.Id.ToString(), repo.Name, change, pat, commits[i].CommitId, commits[i - 1].CommitId, commits[i].Committer.Email, commits[i].Committer.Name); } } } } } } }
/// <summary> /// View detiled information of active pull requests /// </summary> /// <param name="TeamProjectName"></param> /// <param name="GitRepo"></param> private static void ViewPullRequests(string TeamProjectName, string GitRepo, bool CompletedPRs = false, string TargetRef = "") { if (CompletedPRs && TargetRef == "") { Console.WriteLine("Define a target branch reference"); return; } var pullRequests = (CompletedPRs)? GitClient.GetPullRequestsAsync(TeamProjectName, GitRepo, new GitPullRequestSearchCriteria { Status = PullRequestStatus.Completed, TargetRefName = TargetRef }, top: 10).Result : GitClient.GetPullRequestsAsync(TeamProjectName, GitRepo, null).Result; foreach (var pullRequest in pullRequests) { Console.WriteLine("+================PULL REQUEST======================================================="); Console.WriteLine("ID: {0} | TITLE: {1}", pullRequest.PullRequestId, pullRequest.Title); Console.WriteLine("AUTHOR: {0} | STATUS: {1}", pullRequest.CreatedBy.DisplayName, pullRequest.Status.ToString()); Console.WriteLine("SOURCEREF: {0} | TARGETREF: {1}", pullRequest.SourceRefName, pullRequest.TargetRefName); Console.WriteLine("Description:\n{0}", pullRequest.Description); var pullTheads = GitClient.GetThreadsAsync(TeamProjectName, GitRepo, pullRequest.PullRequestId).Result; if (pullTheads.Count > 0) { Console.WriteLine("+------------------COMMENTS---------------------------------------------------------"); } for (int i = 0; i < pullTheads.Count; i++) { if (i == 0) { Console.WriteLine("\n{0}", pullTheads[i].Comments[0].Content); Console.WriteLine("STATUS: {0} | AUTHOR: {1}", pullTheads[i].Status.ToString(), pullTheads[i].Comments[0].Author.DisplayName); } for (int c = 1; c < pullTheads[i].Comments.Count; c++) { Console.WriteLine("\t\t{0}", pullTheads[i].Comments[c].Content); Console.WriteLine("\t\tAUTHOR: {0}", pullTheads[i].Comments[c].Author.DisplayName); } } var workItemRefs = GitClient.GetPullRequestWorkItemRefsAsync(TeamProjectName, GitRepo, pullRequest.PullRequestId).Result; if (workItemRefs.Count > 0) { Console.WriteLine("+------------------WORK ITEMS-------------------------------------------------------"); foreach (var workItemRef in workItemRefs) { int wiId = 0; if (!int.TryParse(workItemRef.Id, out wiId)) { continue; } var workItem = WitClient.GetWorkItemAsync(wiId).Result; Console.WriteLine("{0,10} {1}", workItem.Id, workItem.Fields["System.Title"]); } } var commits = GitClient.GetPullRequestCommitsAsync(TeamProjectName, GitRepo, pullRequest.PullRequestId).Result; Console.WriteLine("+------------------COMMITS----------------------------------------------------------"); foreach (var commit in commits) { Console.WriteLine("{0} {1}", commit.CommitId.Substring(0, 8), commit.Comment); GitCommitChanges changes = GitClient.GetChangesAsync(TeamProjectName, commit.CommitId, GitRepo).Result; foreach (var change in changes.Changes) { Console.WriteLine("{0}: {1}", change.ChangeType, change.Item.Path); } } } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); const String c_collectionUri = "https://dev.azure.com/ankhokha"; // Interactively ask the user for credentials, caching them so the user isn't constantly prompted VssCredentials creds = new VssBasicCredential(String.Empty, ""); // Connect to Azure DevOps Services VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds); // Get a GitHttpClient to talk to the Git endpoints GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); int pullRequestId = 1; IList <string> fileList = new List <string>(); IList <File> fileDetailsList = new List <File>(); List <FileInput> fileMutationDetailsList = new List <FileInput>(); var repository = gitClient.GetRepositoryAsync("8ff8a410-814b-463b-8ecc-949c96fe2007").SyncResult(); var repoLink = (repository.Links.Links["web"] as ReferenceLink).Href; var uriBuilder = new UriBuilder(repoLink); var query = HttpUtility.ParseQueryString(uriBuilder.Query); while (true) { fileMutationDetailsList.Clear(); Console.WriteLine(pullRequestId); // Get data about a specific repository IList <GitCommitRef> commitsList; try { commitsList = gitClient.GetPullRequestCommitsAsync("8ff8a410-814b-463b-8ecc-949c96fe2007", pullRequestId).SyncResult(); } catch (VssServiceException ex) { Console.WriteLine(String.Format("Pull request with id {0} not found. Exiting...", pullRequestId)); break; } string email = ""; string authorName = ""; foreach (var commit in commitsList) { var commitId = commit.CommitId; var result = gitClient.GetChangesAsync(commitId, new Guid("8ff8a410-814b-463b-8ecc-949c96fe2007")).SyncResult <GitCommitChanges>(); var changes = result.Changes.ToList(); foreach (var change in changes) { fileList.Add(change.Item.Path); query["path"] = change.Item.Path; email = commit.Author.Email; authorName = commit.Author.Name; uriBuilder.Query = query.ToString(); var include = true; foreach (var file in fileMutationDetailsList) { if (file.Path == change.Item.Path) { include = false; } } if (include) { fileMutationDetailsList.Add(new FileInput(change.Item.Path, uriBuilder.ToString())); } } } string graphqlServer = "https://ganes-server.azurewebsites.net/graphql"; var graphQlCLient = new GraphQL.Client.GraphQLClient(graphqlServer); var q = new GraphQL.Common.Request.GraphQLRequest(); List <FileInput> a = new List <FileInput> (); q.Query = @"mutation Mutation1($files: [FileInput]!, $email: String!, $name: String!, $pullRequestId: String!) { IngestPullRequest( pullRequest: { Files: $files, ModifiedBy: { email: $email, name: $name }, Properties: { Key: ""pullRequestId"", Value: $pullRequestId } } ) { name } }"; q.Variables = new { files = fileMutationDetailsList, email = email, name = authorName, pullRequestId = pullRequestId.ToString() }; var response = graphQlCLient.PostAsync(q).SyncResult(); Thread.Sleep(2000); pullRequestId++; } }