/// <summary> /// Push the specified branches to their tracked branches on the remote. /// </summary> /// <param name="network">The <see cref="Network"/> being worked with.</param> /// <param name="branches">The branches to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <exception cref="LibGit2SharpException">Throws if either the Remote or the UpstreamBranchCanonicalName is not set.</exception> public static void Push( this Network network, IEnumerable<Branch> branches, PushOptions pushOptions = null) { var enumeratedBranches = branches as IList<Branch> ?? branches.ToList(); foreach (var branch in enumeratedBranches) { if (string.IsNullOrEmpty(branch.UpstreamBranchCanonicalName)) { throw new LibGit2SharpException( string.Format( CultureInfo.InvariantCulture, "The branch '{0}' (\"{1}\") that you are trying to push does not track an upstream branch.", branch.Name, branch.CanonicalName)); } } foreach (var branch in enumeratedBranches) { network.Push(branch.Remote, string.Format( CultureInfo.InvariantCulture, "{0}:{1}", branch.CanonicalName, branch.UpstreamBranchCanonicalName), pushOptions); } }
public void CloneRepo() { var scd = BuildSelfCleaningDirectory(); CloneOptions options = new CloneOptions(); var credentials = new UsernamePasswordCredentials(); credentials.Username = Constants.Identity.Name; credentials.Password = "******"; options.CredentialsProvider += (url, fromUrl, types) => credentials; string clonedRepoPath = Repository.Clone(testUrl, scd.DirectoryPath, options); string file = Path.Combine(scd.DirectoryPath, "testpush.txt"); var rbg = new RandomBufferGenerator(30000); using (var repo = new Repository(clonedRepoPath)) { for (int i = 0; i < 1; i++) { var network = repo.Network.Remotes.First(); FetchOptions fetchOptions = new FetchOptions(); fetchOptions.CredentialsProvider += (url, fromUrl, types) => credentials; repo.Fetch(network.Name, fetchOptions); File.WriteAllBytes(file, rbg.GenerateBufferFromSeed(30000)); repo.Stage(file); Signature author = Constants.Signature; Commit commit = repo.Commit($"Here's a commit {i + 1} i made!", author, author); PushOptions pushOptions = new PushOptions(); pushOptions.CredentialsProvider += (url, fromUrl, types) => credentials; repo.Network.Push(repo.Branches["master"], pushOptions); } } }
/// <summary> /// Push the specified branch to its tracked branch on the remote. /// </summary> /// <param name="network">The <see cref="Network"/> being worked with.</param> /// <param name="branch">The branch to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <exception cref="LibGit2SharpException">Throws if either the Remote or the UpstreamBranchCanonicalName is not set.</exception> public static void Push( this Network network, Branch branch, PushOptions pushOptions = null) { network.Push(new[] { branch }, pushOptions); }
/// <summary> /// Push specified reference to the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="pushRefSpec">The pushRefSpec to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> public virtual void Push( Remote remote, string pushRefSpec, PushOptions pushOptions) { Ensure.ArgumentNotNullOrEmptyString(pushRefSpec, "pushRefSpec"); Push(remote, new[] { pushRefSpec }, pushOptions); }
internal RemoteCallbacks(PushOptions pushOptions) { if (pushOptions == null) { return; } PushTransferProgress = pushOptions.OnPushTransferProgress; PackBuilderProgress = pushOptions.OnPackBuilderProgress; CredentialsProvider = pushOptions.CredentialsProvider; }
/// <summary> /// Push specified reference to the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="pushRefSpec">The pushRefSpec to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <param name="signature">Identity for use when updating the reflog.</param> /// <param name="logMessage">Message to use when updating the reflog.</param> public virtual void Push( Remote remote, string pushRefSpec, PushOptions pushOptions = null, Signature signature = null, string logMessage = null) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNullOrEmptyString(pushRefSpec, "pushRefSpec"); Push(remote, new string[] { pushRefSpec }, pushOptions, signature, logMessage); }
public Boolean CommitAndPush(String gitPath, String branch, String message) { int tries = 0; while (true) { try { using (Repository repo = new Repository(gitPath)) { // git commit // Create the committer's signature and commit //_log.Info("git commit"); Signature author = new Signature("blimp", "*****@*****.**", DateTime.Now); Signature committer = author; // Commit to the repository try { Commit commit = repo.Commit(message, author, committer); } catch (Exception e) { //_log.info("Empty commit"); } // git push //_log.Info("git push"); LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = _gitToken, Password = String.Empty }); repo.Network.Push(repo.Branches[branch], options); return(true); } } catch (Exception ex) { tries = tries + 1; System.Threading.Thread.Sleep(1 * 60 * 1000); // sleep 1 min if (tries > 3) { //_log.Info("delete repo" + githubURL); throw ex; } } } }
public void Push() { var pushOptions = new PushOptions(); pushOptions.CredentialsProvider = new LibGit2Sharp.Handlers.CredentialsHandler( (_url, _user, _cred) => new UsernamePasswordCredentials() { Username = this.username, Password = this.password }); repo.Network.Push(repo.Branches["master"], pushOptions); }
/// <summary> /// Push the objectish to the destination reference on the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="objectish">The source objectish to push.</param> /// <param name="destinationSpec">The reference to update on the remote.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> public virtual void Push( Remote remote, string objectish, string destinationSpec, PushOptions pushOptions = null) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNull(objectish, "objectish"); Ensure.ArgumentNotNullOrEmptyString(destinationSpec, destinationSpec); Push(remote, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", objectish, destinationSpec), pushOptions); }
internal RemoteCallbacks(PushOptions pushOptions) { if (pushOptions == null) { return; } PushTransferProgress = pushOptions.OnPushTransferProgress; PackBuilderProgress = pushOptions.OnPackBuilderProgress; CredentialsProvider = pushOptions.CredentialsProvider; CertificateCheck = pushOptions.CertificateCheck; PushStatusError = pushOptions.OnPushStatusError; PrePushCallback = pushOptions.OnNegotiationCompletedBeforePush; }
public static void PushChanges(Repository repository, CredentialsHandler credentialsHandler, string remote, string branch, string tagName) { try { var remotes = repository.Network.Remotes[remote]; var options = new PushOptions {CredentialsProvider = credentialsHandler}; string pushRefSpec = string.Format("refs/heads/{0}:refs/tags/{1}", branch, tagName); repository.Network.Push(remotes, pushRefSpec, options); } catch (Exception e) { Console.WriteLine("Exception:RepoActions:PushChanges " + e.Message); } }
private void Push() { using (var repo = new Repository(repoPath)) { LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = username, Password = password }); repo.Network.Push(repo.Branches["master"], options); } }
public IActionResult export_ToGitHub(string username, string password, string gurl) { string folder = Repository.Init(currentProject_Path); try { using (var repo = new Repository(folder)) { /* origin remote does not exists */ if (repo.Network.Remotes["origin"] != null) { repo.Network.Remotes.Remove("origin"); } repo.Network.Remotes.Add("origin", gurl); Remote remote = repo.Network.Remotes["origin"]; repo.Network.Remotes.Update(remote, r => { r.Url = gurl; }); repo.Branches.Update(repo.Head, b => b.Remote = remote.Name, b => b.UpstreamBranch = repo.Head.CanonicalName); Commands.Stage(repo, "*"); Signature author = new Signature(username, "@mail", DateTime.Now); Signature committer = author; Commit commit = repo.Commit("Automated commit from OIDEA.", author, committer); LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = username, Password = password }); repo.Network.Push(repo.Branches["master"], options); } }catch (Exception e) { return(Json(e.Message)); } return(Json("Success")); }
public void Run() { var repoName = "NeverSink-EconomyUpdated-Filter"; var filterOutFolder = Path.GetTempPath() + "filterGenerationResult"; var repoFolder = filterOutFolder + "\\" + repoName; if (!Directory.Exists(filterOutFolder)) { Directory.CreateDirectory(filterOutFolder); } if (Directory.Exists(repoFolder)) { DeleteDirectory(repoFolder); } Repository.Clone("https://github.com/NeverSinkDev/" + repoName + ".git", repoFolder); // create filter FilterWriter.WriteFilter(this.Filter, false, repoFolder, null); var author = Environment.GetEnvironmentVariable("author", EnvironmentVariableTarget.Process) ?? "FilterPolishZ"; var email = Environment.GetEnvironmentVariable("email", EnvironmentVariableTarget.Process) ?? "FilterPolishZ"; var gitToken = Environment.GetEnvironmentVariable("githubPAT", EnvironmentVariableTarget.Process); Signature sig = new Signature(author, email, DateTime.Now); Signature committer = sig; using (var repo = new Repository(repoFolder)) { Commands.Stage(repo, "*"); Commit commit = repo.Commit("automated economy update " + DateTime.Today.ToString(), sig, committer); LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = author, Password = gitToken }); repo.Network.Push(repo.Branches["master"], options); } // cleanUp DeleteDirectory(repoFolder); }
/// <summary> /// Push specified references to the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="pushRefSpecs">The pushRefSpecs to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <param name="signature">Identity for use when updating the reflog.</param> /// <param name="logMessage">Message to use when updating the reflog.</param> public virtual void Push( Remote remote, IEnumerable <string> pushRefSpecs, PushOptions pushOptions = null, Signature signature = null, string logMessage = null) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNull(pushRefSpecs, "pushRefSpecs"); // Return early if there is nothing to push. if (!pushRefSpecs.Any()) { return; } if (pushOptions == null) { pushOptions = new PushOptions(); } // Load the remote. using (RemoteSafeHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, remote.Name, true)) { var callbacks = new RemoteCallbacks(pushOptions); GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks(); Proxy.git_remote_set_callbacks(remoteHandle, ref gitCallbacks); try { Proxy.git_remote_connect(remoteHandle, GitDirection.Push); Proxy.git_remote_push(remoteHandle, pushRefSpecs, new GitPushOptions() { PackbuilderDegreeOfParallelism = pushOptions.PackbuilderDegreeOfParallelism }, signature.OrDefault(repository.Config), logMessage); } finally { Proxy.git_remote_disconnect(remoteHandle); } } }
bool PushCore(CommonRepository repository) { using (var repo = new Repository(repository.Path)) { LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = "******", Password = "******" }); var branch = repo.Branches.FirstOrDefault(b => b.FriendlyName == $"20{repository.Version}"); if (branch == null) { return(false); } repo.Network.Push(branch, options); return(true); } }
private bool push() { LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = credential; syncStatus.Text = "数据上传中。。。"; try { Console.WriteLine("Pushing to remote"); repo.Network.Push(repo.Head, options); } catch (Exception e) { syncStatus.Text = "数据上传失败,请点击手动同步重试"; Console.WriteLine("Push failed: " + e.ToString()); return(false); } syncStatus.Text = "数据上传完成"; Console.WriteLine("Push success"); return(true); }
public void CommitAndPush(String gitPath, String branch, String message) { try { using (Repository repo = new Repository(gitPath)) { // git commit // Create the committer's signature and commit //_log.Info("git commit"); Signature author = new Signature("appsvcbuild", "*****@*****.**", DateTime.Now); Signature committer = author; // Commit to the repository try { Commit commit = repo.Commit(message, author, committer); } catch (Exception e) { //_log.info("Empty commit"); } // git push //_log.Info("git push"); LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = _gitToken, Password = String.Empty }); repo.Network.Push(repo.Branches[branch], options); } } catch (Exception e) { //TODO better retry logic _log.LogInformation(e.ToString()); } }
/// <inheritdoc /> public IObservable<Unit> Push(IObserver<Tuple<string, int>> observer) { var branch = _repository.Head; var isCancelled = false; var options = new PushOptions { CredentialsProvider = _credentialsHandler, OnPushTransferProgress = (current, total, bytes) => { var progress = 0; if (total != 0) { progress = 50 + (50 * current) / total; } observer.OnNext(Tuple.Create("", progress)); return !isCancelled; } }; return Observable.Create<Unit>(subj => { var sub = Observable.Start(() => { _repository.Network.Push(branch, options); observer.OnNext(Tuple.Create("push completed", 100)); observer.OnCompleted(); }, Scheduler.Default).Subscribe(subj); return new CompositeDisposable( sub, Disposable.Create(() => { isCancelled = true; observer.OnCompleted(); })); }); }
/// <summary> /// Push the specified branches to their tracked branches on the remote. /// </summary> /// <param name="network">The <see cref="Network"/> being worked with.</param> /// <param name="branches">The branches to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <exception cref="LibGit2SharpException">Throws if either the Remote or the UpstreamBranchCanonicalName is not set.</exception> public static void Push( this Network network, IEnumerable <Branch> branches, PushOptions pushOptions = null) { var enumeratedBranches = branches as IList <Branch> ?? branches.ToList(); foreach (var branch in enumeratedBranches) { if (string.IsNullOrEmpty(branch.UpstreamBranchCanonicalName)) { throw new LibGit2SharpException(string.Format("The branch '{0}' (\"{1}\") that you are trying to push does not track an upstream branch.", branch.Name, branch.CanonicalName)); } } foreach (var branch in enumeratedBranches) { network.Push(branch.Remote, string.Format("{0}:{1}", branch.CanonicalName, branch.UpstreamBranchCanonicalName), pushOptions); } }
/// <summary> /// Push the specified branches to their tracked branches on the remote. /// </summary> /// <param name="branches">The branches to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <exception cref="LibGit2SharpException">Throws if either the Remote or the UpstreamBranchCanonicalName is not set.</exception> public virtual void Push( IEnumerable <Branch> branches, PushOptions pushOptions) { var enumeratedBranches = branches as IList <Branch> ?? branches.ToList(); foreach (var branch in enumeratedBranches) { if (string.IsNullOrEmpty(branch.UpstreamBranchCanonicalName)) { throw new LibGit2SharpException("The branch '{0}' (\"{1}\") that you are trying to push does not track an upstream branch.", branch.FriendlyName, branch.CanonicalName); } } foreach (var branch in enumeratedBranches) { Push(branch.Remote, string.Format( CultureInfo.InvariantCulture, "{0}:{1}", branch.CanonicalName, branch.UpstreamBranchCanonicalName), pushOptions); } }
public override void Unpublish(string branch) { try { var remote = _repo.Branches[branch].Remote; _repo.Branches.Update(_repo.Branches[branch], b => b.Remote = remote.Name, b => b.TrackedBranch = null, b => b.UpstreamBranch = null); PushOptions options = null; if (_credentials != null) { options = new PushOptions { CredentialsProvider = _credentialsHandler }; } _repo.Network.Push(remote, ":" + _repo.Branches[branch].UpstreamBranchCanonicalName, options); } catch (LibGit2SharpException ex) { throw new SourceControlException(SourceControlText.GitUnpublishFailed, ex); } }
static async Task Main(string[] args) { Uri org1Url = new Uri("https://dev.azure.com/" + Environment.GetEnvironmentVariable("ORG1")); String project1 = Environment.GetEnvironmentVariable("PROJ1"); String pat1 = Environment.GetEnvironmentVariable("PAT1"); // See https://docs.microsoft.com/azure/devops/integrate/get-started/authentication/pats Uri org2Url = new Uri("https://dev.azure.com/" + Environment.GetEnvironmentVariable("ORG2")); String project2 = Environment.GetEnvironmentVariable("PROJ2"); String pat2 = Environment.GetEnvironmentVariable("PAT2"); // Project name which this should look at Boolean dryRun = !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("DRYRUN")); // Create a connection var sourceConnection = new VssConnection(org1Url, new VssBasicCredential(string.Empty, pat1)); var destinationConnection = new VssConnection(org2Url, new VssBasicCredential(string.Empty, pat2)); var destProject = await destinationConnection.GetClient <ProjectHttpClient>().GetProject(project2); var sourceRepos = await GetAllRepos(sourceConnection, project1); var destReposDict = (await GetAllRepos(destinationConnection, project2)).ToDictionary(x => x.Name); var missingReposInDest = sourceRepos.Where(x => !destReposDict.ContainsKey(getDestNameFromSourceName(x.Name))); var tempPath = Path.GetTempPath(); var tempDir = Directory.CreateDirectory(Path.Join(tempPath, "repocloner", RandomString(5).ToLower())); Console.WriteLine($"Using path {tempDir.FullName}"); // Create any repos missing in proj2 var destSourceClient = destinationConnection.GetClient <GitHttpClient>(); foreach (var sourceRepo in missingReposInDest) { if (dryRun) { Console.WriteLine($"Would create repo {sourceRepo.Name} in {destSourceClient.BaseAddress}"); } else { var gitToCreate = new GitRepositoryCreateOptions() { Name = getDestNameFromSourceName(sourceRepo.Name), ProjectReference = destProject, }; var destRepo = await destSourceClient.CreateRepositoryAsync(gitToCreate); destReposDict[destRepo.Name] = destRepo; } } // Sync source from proj1 to proj2 for all branchs foreach (var sourceRepo in sourceRepos) { var destRepo = destReposDict[getDestNameFromSourceName(sourceRepo.Name)]; if (dryRun) { Console.WriteLine($"Would clone {sourceRepo.Name} @ {sourceRepo.WebUrl} and sync to {destRepo.Name} @ {destRepo.WebUrl}"); } else { // Create a temp dir to store the cloned repo var gitDir = Directory.CreateDirectory(Path.Join(tempDir.FullName, sourceRepo.Name)); var co = new CloneOptions(); CredentialsHandler sourceCredProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = pat1, Password = pat1 }; co.CredentialsProvider = sourceCredProvider; Console.WriteLine($"Cloning source {sourceRepo.Name}"); Repository.Clone(sourceRepo.RemoteUrl, gitDir.FullName, co); using (var repo = new Repository(gitDir.FullName)) { CredentialsHandler destCredProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = pat2, Password = pat2 }; LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = destCredProvider; if (!repo.Network.Remotes.Where(x => x.Name == "dest").Any()) { repo.Network.Remotes.Add("dest", destRepo.RemoteUrl); } else { repo.Network.Remotes.Remove("dest"); repo.Network.Remotes.Add("dest", destRepo.RemoteUrl); } var destRemote = repo.Network.Remotes["dest"]; foreach (var branch in repo.Branches) { Console.WriteLine($"Pusing source {sourceRepo.Name}:{branch} to {destRepo.Name}:{branch} @ {destRepo.Url}"); repo.Network.Push(destRemote, branch.CanonicalName, new PushOptions() { CredentialsProvider = destCredProvider }); } } } } }
private static async Task WriteContributorsToRepo(string username, string password) { var nameOfThankyouBranch = "thankyou"; var repoUrl = _parsedOptions.gitRepositoryUrl; var contributorsHeader = _parsedOptions.acknowledgementSection; var fileHoldingContributorsInfo = _parsedOptions.fileInRepoForAcknowledgement; string tempPathGitFolder = CreateTempFolderForTheRepo(); var gitCredentialsHandler = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = username, Password = password }); var cloneOptions = new CloneOptions(); cloneOptions.CredentialsProvider = gitCredentialsHandler; LibGit2Sharp.Repository.Clone(repoUrl, tempPathGitFolder, cloneOptions); using (var repo = new LibGit2Sharp.Repository(tempPathGitFolder)) { var remote = repo.Network.Remotes["origin"]; var defaultBranch = repo.Branches.FirstOrDefault(b => b.IsCurrentRepositoryHead == true); var refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); var remoteThankYouBranch = repo.Branches.FirstOrDefault(b => b.FriendlyName == repo.Network.Remotes.FirstOrDefault()?.Name + "/" + nameOfThankyouBranch); if (remoteThankYouBranch != null) { Commands.Checkout(repo, remoteThankYouBranch); } if (repo.Head.FriendlyName != nameOfThankyouBranch) { var newThankyouBranch = repo.CreateBranch(nameOfThankyouBranch); repo.Branches.Update(newThankyouBranch, b => b.UpstreamBranch = newThankyouBranch.CanonicalName, b => b.Remote = repo.Network.Remotes.First().Name); Commands.Checkout(repo, newThankyouBranch); } var pathToReadme = Path.Combine(tempPathGitFolder, fileHoldingContributorsInfo); // Change the file and save it var inputLines = await File.ReadAllLinesAsync(pathToReadme); var outputLines = MarkdownProcessor.AddContributorsToMarkdownFile(inputLines, _contributorsToday); await File.WriteAllLinesAsync(pathToReadme, outputLines); var status = repo.RetrieveStatus(fileHoldingContributorsInfo); if (status == FileStatus.ModifiedInWorkdir) { // Commit the file to the repo, on a non-master branch repo.Index.Add(fileHoldingContributorsInfo); repo.Index.Write(); var gitAuthorName = _parsedOptions.gitAuthorName; var gitAuthorEmail = _parsedOptions.gitAuthorEmail; // Create the committer's signature and commit var author = new LibGit2Sharp.Signature(gitAuthorName, gitAuthorEmail, DateTime.Now); var committer = author; // Commit to the repository var commit = repo.Commit("A new list of awesome contributors", author, committer); //Push the commit to origin LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = gitCredentialsHandler; repo.Network.Push(repo.Head, options); // Login to GitHub with Octokit var githubClient = new GitHubClient(new ProductHeaderValue(username)); githubClient.Credentials = new Octokit.Credentials(password); try { // Create a PR on the repo for the branch "thank you" await githubClient.PullRequest.Create(username, "thankyou", new NewPullRequest("Give credit for people on Twitch chat", nameOfThankyouBranch, defaultBranch.FriendlyName)); } catch (Exception ex) { // It's alright, the PR is already there. No harm is done. } } } }
public override void Push() { try { //Only use credentials if we've been given credentials to use in the constructor. PushOptions options = null; if (_credentials != null) { options = new PushOptions() { CredentialsProvider = _credentialsHandler }; } var branch = _repo.Branches[CurrentBranch.Name]; _repo.Network.Push(branch, options); RequeryUnsyncedCommits(); } catch (LibGit2SharpException ex) { throw new SourceControlException(SourceControlText.GitPushFailed, ex); } }
// full: delete diff post for api remote public async Task Push(string name = "", bool full = false) { if (string.IsNullOrEmpty(name)) { name = Option.CurrentRemote; } Logger.LogInformation($"Push to remote {name}."); if (Option.Remotes.TryGetValue(name, out var remote)) { Logger.LogInformation($"Detect remote {remote.Name} ({Enum.GetName(typeof(RemoteType), remote.Type)})."); switch (remote.Type) { case RemoteType.LocalFS: { await toLocalFS(remote); } break; case RemoteType.RemoteFS: { throw new NotSupportedException("Not support pushing to remote file system, please push to local file system and sync to remote."); } case RemoteType.Api: { await Connect(name); Logger.LogInformation($"Fetch remote posts."); HashSet <string> remoteIds = (await Remote.PostService.All()).ToHashSet(); foreach (var item in await Local.PostService.GetAllPosts()) { if (item is null) { continue; } Logger.LogInformation($"Loaded {item.Id}: {item.Title}"); if (remoteIds.Contains(item.Id)) { var result = await Remote.PostService.Update(item); if (result) { Logger.LogInformation($"Updated {item.Id}"); } else { Logger.LogError($"Failed to update {item.Id}"); } } else { var result = await Remote.PostService.Create(item); if (result is null) { Logger.LogError($"Failed to create {item.Id}"); } else { Logger.LogInformation($"Created {item.Id}"); } } remoteIds.Remove(item.Id); } if (full) { foreach (var v in remoteIds) { var result = await Remote.PostService.Delete(v); if (result) { Logger.LogInformation($"Deleted {v}."); } else { Logger.LogError($"Failed to deleted {v}."); } } } } break; case RemoteType.Git: { await Connect(name); string tempDist = Path.Join(Environment.CurrentDirectory, "temp/dist"); Logger.LogInformation("Generate data."); await toLocalFS(new RemoteOption { Uri = tempDist, Type = RemoteType.LocalFS, Name = remote.Name }); FSExtensions.CopyDirectory(tempDist, GitTempFolder); Logger.LogInformation("Load git config."); string userName = Option.Properties[$"remote.{remote.Name}.git.username"], password = Option.Properties[$"remote.{remote.Name}.git.password"]; { if (string.IsNullOrEmpty(userName)) { userName = ConsoleExtensions.Input("Input username: "******"Input password: "******"Commit to git."); LibGit2Sharp.Commands.Stage(repo, "*"); var signature = new LibGit2Sharp.Signature( new Identity("AcBlog.Tools.Sdk", "tools.sdk@acblog"), DateTimeOffset.Now); repo.Commit(DateTimeOffset.Now.ToString(), signature, signature, new CommitOptions { AllowEmptyCommit = true }); Logger.LogInformation($"Push to {repo.Head.RemoteName}."); PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = string.IsNullOrEmpty(userName) ? usernameFromUrl : userName, Password = password }); repo.Network.Push(repo.Head, options); } } break; } } else { throw new Exception("No remote"); } async Task toLocalFS(RemoteOption remote) { FSBuilder fsBuilder = new FSBuilder(remote.Uri); fsBuilder.EnsureDirectoryEmpty(); List <Post> posts = new List <Post>(); foreach (var item in await Local.PostService.GetAllPosts()) { if (item is null) { continue; } Logger.LogInformation($"Loaded {item.Id}: {item.Title}"); posts.Add(item); } Logger.LogInformation("Build data."); { BlogOptions options = await Local.GetOptions(); BlogBuilder builder = new BlogBuilder(options, Path.Join(remote.Uri)); await builder.Build(); } { PostRepositoryBuilder builder = new PostRepositoryBuilder(posts, Path.Join(remote.Uri, "posts")); await builder.Build(); } { var baseAddress = Option.Properties[$"remote.{remote.Name}.generator.baseAddress"]; if (!string.IsNullOrEmpty(baseAddress)) { Logger.LogInformation("Build sitemap."); var sub = fsBuilder.CreateSubDirectoryBuilder("Site"); { var siteMapBuilder = await Local.BuildSitemap(baseAddress); using var st = sub.GetFileRewriteStream("sitemap.xml"); using var writer = XmlWriter.Create(st); siteMapBuilder.Build().WriteTo(writer); } Logger.LogInformation("Build feed."); { var feed = await Local.BuildSyndication(baseAddress); using var st = sub.GetFileRewriteStream("atom.xml"); using var writer = XmlWriter.Create(st); feed.GetAtom10Formatter().WriteTo(writer); } } } } }
/// <summary> /// Push the specified branches to their tracked branches on the remote. /// </summary> /// <param name="branches">The branches to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <exception cref="LibGit2SharpException">Throws if either the Remote or the UpstreamBranchCanonicalName is not set.</exception> public virtual void Push( IEnumerable<Branch> branches, PushOptions pushOptions) { var enumeratedBranches = branches as IList<Branch> ?? branches.ToList(); foreach (var branch in enumeratedBranches) { if (string.IsNullOrEmpty(branch.UpstreamBranchCanonicalName)) { throw new LibGit2SharpException("The branch '{0}' (\"{1}\") that you are trying to push does not track an upstream branch.", branch.FriendlyName, branch.CanonicalName); } } foreach (var branch in enumeratedBranches) { using (var remote = repository.Network.Remotes.RemoteForName(branch.RemoteName)) { Push(remote, string.Format( CultureInfo.InvariantCulture, "{0}:{1}", branch.CanonicalName, branch.UpstreamBranchCanonicalName), pushOptions); } } }
private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { // remove from git using (var repo = new Repository(Properties.Settings.Default.PassDirectory)) { // remove the file repo.Remove(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString()); // Commit repo.Commit("password removed", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); // push var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GitUsername, Password = GitPassword }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options, new Signature("pass4win", "*****@*****.**", DateTimeOffset.Now), "pushed changes"); } ResetDatagrid(); }
/// <summary> /// Callback for the encrypt thread /// </summary> /// <param name="result"></param> /// <param name="tmpFile"></param> /// <param name="tmpFile2"></param> /// <param name="path"></param> public void EncryptCallback(GpgInterfaceResult result, string tmpFile, string tmpFile2, string path) { if (result.Status == GpgInterfaceStatus.Success) { File.Delete(tmpFile); File.Delete(path); File.Move(tmpFile2, path); // add to git using (var repo = new Repository(Cfg["PassDirectory"])) { // Stage the file repo.Stage(path); // Commit repo.Commit("password changes", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false) { toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } } else { MessageBox.Show(Strings.Error_weird_shit_happened_encryption, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Push specified references to the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="pushRefSpecs">The pushRefSpecs to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <param name="signature">Identity for use when updating the reflog.</param> /// <param name="logMessage">Message to use when updating the reflog.</param> public virtual void Push( Remote remote, IEnumerable<string> pushRefSpecs, PushOptions pushOptions = null, Signature signature = null, string logMessage = null) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNull(pushRefSpecs, "pushRefSpecs"); // The following local variables are protected from garbage collection // by a GC.KeepAlive call at the end of the method. Otherwise, // random crashes during push progress reporting could occur. PushTransferCallbacks pushTransferCallbacks; PackbuilderCallbacks packBuilderCallbacks; NativeMethods.git_push_transfer_progress pushProgress; NativeMethods.git_packbuilder_progress packBuilderProgress; // Return early if there is nothing to push. if (!pushRefSpecs.Any()) { return; } if (pushOptions == null) { pushOptions = new PushOptions(); } PushCallbacks pushStatusUpdates = new PushCallbacks(pushOptions.OnPushStatusError); // Load the remote. using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true)) { var callbacks = new RemoteCallbacks(null, null, null, pushOptions.Credentials); GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks(); Proxy.git_remote_set_callbacks(remoteHandle, ref gitCallbacks); try { Proxy.git_remote_connect(remoteHandle, GitDirection.Push); // Perform the actual push. using (PushSafeHandle pushHandle = Proxy.git_push_new(remoteHandle)) { pushTransferCallbacks = new PushTransferCallbacks(pushOptions.OnPushTransferProgress); packBuilderCallbacks = new PackbuilderCallbacks(pushOptions.OnPackBuilderProgress); pushProgress = pushTransferCallbacks.GenerateCallback(); packBuilderProgress = packBuilderCallbacks.GenerateCallback(); Proxy.git_push_set_callbacks(pushHandle, pushProgress, packBuilderProgress); // Set push options. Proxy.git_push_set_options(pushHandle, new GitPushOptions() { PackbuilderDegreeOfParallelism = pushOptions.PackbuilderDegreeOfParallelism }); // Add refspecs. foreach (string pushRefSpec in pushRefSpecs) { Proxy.git_push_add_refspec(pushHandle, pushRefSpec); } Proxy.git_push_finish(pushHandle); if (!Proxy.git_push_unpack_ok(pushHandle)) { throw new LibGit2SharpException("Push failed - remote did not successfully unpack."); } Proxy.git_push_status_foreach(pushHandle, pushStatusUpdates.Callback); Proxy.git_push_update_tips(pushHandle, signature.OrDefault(repository.Config), logMessage); } } finally { Proxy.git_remote_disconnect(remoteHandle); } } GC.KeepAlive(pushProgress); GC.KeepAlive(packBuilderProgress); GC.KeepAlive(pushTransferCallbacks); GC.KeepAlive(packBuilderCallbacks); }
public GitClient(IGitHubCredentialProvider credentialProvider) { pushOptions = new PushOptions { CredentialsProvider = credentialProvider.HandleCredentials }; fetchOptions = new FetchOptions { CredentialsProvider = credentialProvider.HandleCredentials }; }
/// <summary> /// Push specified reference to the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="pushRefSpec">The pushRefSpec to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <param name="signature">Identity for use when updating the reflog.</param> /// <param name="logMessage">Message to use when updating the reflog.</param> public virtual void Push( Remote remote, string pushRefSpec, PushOptions pushOptions = null, Signature signature = null, string logMessage = null) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNullOrEmptyString(pushRefSpec, "pushRefSpec"); Push(remote, new[] { pushRefSpec }, pushOptions, signature, logMessage); }
private void renameToolStripMenuItem_Click(object sender, EventArgs e) { // rename the entry InputBoxValidation validation = delegate(string val) { if (val == "") return "Value cannot be empty."; if (new Regex(@"[a-zA-Z0-9-\\_]+/g").IsMatch(val)) return "Not a valid name, can only use characters or numbers and - \\."; if (File.Exists(Properties.Settings.Default.PassDirectory + "\\" + @val + ".gpg")) return "Entry already exists."; return ""; }; string value = dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[1].Value.ToString(); if (InputBox.Show("Enter a new name", "Name:", ref value, validation) == DialogResult.OK) { // parse path string tmpPath = Properties.Settings.Default.PassDirectory + "\\" + @value + ".gpg"; Directory.CreateDirectory(Path.GetDirectoryName(tmpPath)); File.Copy(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString(), tmpPath); using (var repo = new Repository(Properties.Settings.Default.PassDirectory)) { // add the file repo.Remove(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString()); repo.Stage(tmpPath); // Commit repo.Commit("password moved", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); //push var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GitUsername, Password = GitPassword }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options, new Signature("pass4win", "*****@*****.**", DateTimeOffset.Now), "pushed changes"); } ResetDatagrid(); } }
/// <summary> /// Push specified references to the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="pushRefSpecs">The pushRefSpecs to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> public virtual void Push(Remote remote, IEnumerable<string> pushRefSpecs, PushOptions pushOptions) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNull(pushRefSpecs, "pushRefSpecs"); // Return early if there is nothing to push. if (!pushRefSpecs.Any()) { return; } if (pushOptions == null) { pushOptions = new PushOptions(); } // Load the remote. using (RemoteHandle remoteHandle = Proxy.git_remote_lookup(repository.Handle, remote.Name, true)) { var callbacks = new RemoteCallbacks(pushOptions); GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks(); Proxy.git_remote_push(remoteHandle, pushRefSpecs, new GitPushOptions() { PackbuilderDegreeOfParallelism = pushOptions.PackbuilderDegreeOfParallelism, RemoteCallbacks = gitCallbacks, ProxyOptions = new GitProxyOptions { Version = 1 }, }); } }
private void setupOptions(string Username, SecureString SecurePassword, string RepoPath, string RepoUrl) { credentials = new SecureUsernamePasswordCredentials() { Username = Username, Password = SecurePassword }; var credentialsProvider = new CredentialsHandler((_url, _user, _cred) => new SecureUsernamePasswordCredentials { Username = Username, Password = SecurePassword }); fetchOptions = new FetchOptions() { CredentialsProvider = credentialsProvider }; pullOptions = new PullOptions() { FetchOptions = fetchOptions }; pushOptions = new PushOptions() { CredentialsProvider = credentialsProvider }; cloneOptions = new CloneOptions() { CredentialsProvider = credentialsProvider }; statusOptions = new StatusOptions() { ExcludeSubmodules = true, IncludeUnaltered = false }; }
/// <summary> /// rename the entry with all the hassle that accompanies it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RenameToolStripMenuItemClick(object sender, EventArgs e) { SaveFileDialog newFileDialog = new SaveFileDialog { AddExtension = true, AutoUpgradeEnabled = true, CreatePrompt = false, DefaultExt = "gpg", InitialDirectory = Cfg["PassDirectory"], Title = Strings.FrmMain_RenameToolStripMenuItemClick_Rename }; if (newFileDialog.ShowDialog() == DialogResult.Cancel) { return; } string tmpFileName = newFileDialog.FileName; newFileDialog.Dispose(); // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(path: Path.GetDirectoryName(tmpFileName)); File.Copy(dirTreeView.SelectedNode.Tag + "\\" + listFileView.SelectedItem + ".gpg", tmpFileName); using (var repo = new Repository(Cfg["PassDirectory"])) { // add the file repo.Remove(listFileView.SelectedItem.ToString()); repo.Stage(tmpFileName); // Commit repo.Commit("password moved", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false) { //push toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } this.CreateNodes(); }
private static async Task WriteContributorsToRepo(string username, string password) { var nameOfThankyouBranch = "thankyou"; var repoUrl = _parsedOptions.repositoryUrl; var contributorsHeader = _parsedOptions.acknowledgementSection; var fileHoldingContributorsInfo = _parsedOptions.fileInRepoForAcknowledgement; var cloneOptions = new CloneOptions(); var gitCredentialsHandler = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = username, Password = password }); cloneOptions.CredentialsProvider = gitCredentialsHandler; var tempPath = Path.GetTempPath(); var tempPathForRepo = Path.Combine(tempPath, "Jaan"); if (Directory.Exists(tempPathForRepo)) { Directory.Delete(tempPathForRepo, true); //TODO: Don't remove and re-clone, clone only if doesn't exist } var tempPathGitFolder = Path.Combine(tempPath, "Jaan"); if (!Directory.Exists(tempPathGitFolder)) { var directoryInfo = Directory.CreateDirectory(tempPathGitFolder); } LibGit2Sharp.Repository.Clone(repoUrl, tempPathGitFolder, cloneOptions); //TODO: if the repo clone is already here, should we delete and reclone? or should we assume correct repo here. using (var repo = new LibGit2Sharp.Repository(tempPathGitFolder)) { var remote = repo.Network.Remotes["origin"]; var defaultBranch = repo.Branches.FirstOrDefault(b => b.IsCurrentRepositoryHead == true); var refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); var remoteThankYouBranch = repo.Branches.FirstOrDefault(b => b.FriendlyName == repo.Network.Remotes.FirstOrDefault()?.Name + "/" + nameOfThankyouBranch); if (remoteThankYouBranch != null) { Commands.Checkout(repo, remoteThankYouBranch); } if (repo.Head.FriendlyName != nameOfThankyouBranch) { var newThankyouBranch = repo.CreateBranch(nameOfThankyouBranch); repo.Branches.Update(newThankyouBranch, b => b.UpstreamBranch = newThankyouBranch.CanonicalName, b => b.Remote = repo.Network.Remotes.First().Name); Commands.Checkout(repo, newThankyouBranch); } var pathToReadme = Path.Combine(tempPathGitFolder, fileHoldingContributorsInfo); // Change the file and save it using (StreamWriter sw = File.AppendText(pathToReadme)) { foreach (var contributor in _contributorsToday) { sw.WriteLine(contributor); } } // Commit the file to the repo, on a non-master branch repo.Index.Add(fileHoldingContributorsInfo); repo.Index.Write(); // Create the committer's signature and commit var author = new LibGit2Sharp.Signature(_parsedOptions.gitAuthorName, _parsedOptions.gitAuthorEmail, DateTime.Now); var committer = author; // Commit to the repository var commit = repo.Commit("A new list of awesome contributors", author, committer); //Push the commit to origin LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = gitCredentialsHandler; repo.Network.Push(repo.Head, options); // Login to GitHub with Octokit var githubClient = new GitHubClient(new ProductHeaderValue(username)); githubClient.Credentials = new Octokit.Credentials(password); try { // Create a PR on the repo for the branch "thank you" await githubClient.PullRequest.Create(username, "thankyou", new NewPullRequest("Give credit for people on Twitch chat", nameOfThankyouBranch, defaultBranch.FriendlyName)); } catch (Exception ex) { Console.WriteLine(ex); } } }
/// <summary> /// Delete an entry /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeleteToolStripMenuItemClick(object sender, EventArgs e) { // remove from git using (var repo = new Repository(Cfg["PassDirectory"])) { // remove the file repo.Remove(dirTreeView.SelectedNode.Tag + "\\" + listFileView.SelectedItem + ".gpg"); // Commit repo.Commit("password removed", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false) { // push toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } this.CreateNodes(); }
/// <summary> /// Push the specified branch to its tracked branch on the remote. /// </summary> /// <param name="branch">The branch to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <exception cref="LibGit2SharpException">Throws if either the Remote or the UpstreamBranchCanonicalName is not set.</exception> public virtual void Push( Branch branch, PushOptions pushOptions) { Push(new[] { branch }, pushOptions); }
private void CheckOnline(bool silent = false) { // Is remote on in the config if (Cfg["UseGitRemote"]) { // Check if the remote is there if (IsGitAlive(Cfg["GitRemote"]) || IsHttpsAlive(Cfg["GitRemote"])) { // looks good, let's try this.gitRepoOffline = false; } // Do a fetch to get the latest repo. if (!GitFetch()) { // nope not online this.gitRepoOffline = true; MessageBox.Show(Strings.Error_connection, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { // We're online toolStripOffline.Visible = false; // look if we have changes we should sync using (var repo = new Repository(Cfg["PassDirectory"])) { var tc = repo.Diff.Compare<TreeChanges>(repo.Branches["origin/master"].Tip.Tree, repo.Head.Tip.Tree); if (tc.Any()) { var remote = repo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } } } else { // no remote checkbox so we're staying offline if (!silent) MessageBox.Show(Strings.Error_remote_disabled, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static async Task WriteContributorsToRepo(string username, string password) { var nameOfThankyouBranch = "thankyou"; var contributorsHeader = _parsedOptions.acknowledgementSection; var fileHoldingContributorsInfo = _parsedOptions.fileInRepoForAcknowledgement; var githubRepoOwner = _parsedOptions.githubRepoOwner; var githubRepoName = _parsedOptions.githubRepoName; string tempPathGitFolder = CreateTempFolderForTheRepo(); // Login to GitHub with Octokit var githubClient = new GitHubClient(new ProductHeaderValue(username)); githubClient.Credentials = new Octokit.Credentials(password); var githubRepo = await githubClient.Repository.Get(githubRepoOwner, githubRepoName); var gitCredentialsHandler = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = username, Password = password }); var cloneOptions = new CloneOptions(); cloneOptions.CredentialsProvider = gitCredentialsHandler; LibGit2Sharp.Repository.Clone(githubRepo.CloneUrl, tempPathGitFolder, cloneOptions); using (var repo = new LibGit2Sharp.Repository(tempPathGitFolder)) { var remote = repo.Network.Remotes["origin"]; var defaultBranch = repo.Branches.FirstOrDefault(b => b.IsCurrentRepositoryHead == true); var refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); var remoteThankYouBranch = repo.Branches.FirstOrDefault(b => b.FriendlyName == repo.Network.Remotes.FirstOrDefault()?.Name + "/" + nameOfThankyouBranch); if (remoteThankYouBranch != null) { Commands.Checkout(repo, remoteThankYouBranch); } if (repo.Head.FriendlyName != nameOfThankyouBranch) { var newThankyouBranch = repo.CreateBranch(nameOfThankyouBranch); repo.Branches.Update(newThankyouBranch, b => b.UpstreamBranch = newThankyouBranch.CanonicalName, b => b.Remote = repo.Network.Remotes.First().Name); Commands.Checkout(repo, newThankyouBranch); } var pathToReadme = Path.Combine(tempPathGitFolder, fileHoldingContributorsInfo); // Change the file and save it var inputLines = await File.ReadAllLinesAsync(pathToReadme); var outputLines = MarkdownProcessor.AddContributorsToMarkdownFile(inputLines, _contributorsToday); await File.WriteAllLinesAsync(pathToReadme, outputLines); var status = repo.RetrieveStatus(fileHoldingContributorsInfo); if (status == FileStatus.ModifiedInWorkdir) { try { // Commit the file to the repo, on a non-master branch repo.Index.Add(fileHoldingContributorsInfo); repo.Index.Write(); var gitAuthorName = _parsedOptions.gitAuthorName; var gitAuthorEmail = _parsedOptions.gitAuthorEmail; // Create the committer's signature and commit var author = new LibGit2Sharp.Signature(gitAuthorName, gitAuthorEmail, DateTime.Now); var committer = author; // Commit to the repository var commit = repo.Commit("A new list of awesome contributors", author, committer); //Push the commit to origin LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = gitCredentialsHandler; repo.Network.Push(repo.Head, options); // Check if there is already a PR exist for the same branch var prsOfRepo = await githubClient.PullRequest.GetAllForRepository(githubRepoOwner, githubRepoName, new PullRequestRequest { State = ItemStateFilter.Open }); var currentPR = prsOfRepo.FirstOrDefault(x => x.Head.Label == $"{githubRepoOwner}:{nameOfThankyouBranch}"); if (currentPR == null) { // Create a PR on the repo for the branch "thank you" await githubClient.PullRequest.Create(username, githubRepoName, new NewPullRequest("Give credit for people on Twitch chat", nameOfThankyouBranch, defaultBranch.FriendlyName)); } else { _logger.LogWarning($"Pull Rrequest is already created. Check PR {currentPR.Id}"); } } catch (Exception ex) { // This exception might be caused by an already existing PR for this branch. In this case it's ok, otherwise we will just log it. _logger.LogError(ex, $"Ops, We couldn't create the PR. But here is the list of contributors you were trying to add {string.Join(", ", _contributorsToday.Select(c => c.Name))}"); } } else { _logger.LogInformation("There was no changes on the README file, this means that either there was no contributors, or all today's contributors are duplicates."); } } }
public async Task RunAsync() { await _sourceRepo.Initialize(); await _destRepo.Initialize(); // fetch latest sources WriteLine("Fetching."); _sourceRepo.Fetch(_options.PullRequestBranchSourceRemote); var (prRepo, prRemoteName, prUserName, prPassword) = _options.PushBranchToDestination ? (_destRepo, _options.DestinationRemoteName, _options.DestinationUserName, _options.DestinationPassword) : (_sourceRepo, _options.SourceRemoteName, _options.SourceUserName, _options.SourcePassword); // branch from the source var title = $"Merge {_options.SourceBranchName} into {_options.DestinationBranchName}"; if (_options.Force || await prRepo.ShouldMakePullRequestAsync(title)) { } else { WriteLine("Existing merge PRs exist; aboring creation."); return; } var prBranchName = $"merge-{_options.SourceBranchName}-into-{_options.DestinationBranchName}-{DateTime.UtcNow.ToString("yyyyMMdd-HHmmss")}"; var prSourceBranch = $"{_options.PullRequestBranchSourceRemote}/{_options.SourceBranchName}"; WriteLine($"Creating branch '{prBranchName}' from '{prSourceBranch}'."); if (_options.Debug) { WriteLine("Debug: Skiping branch creation."); } else { var prBranch = prRepo.Repository.CreateBranch(prBranchName, prSourceBranch); } // push the branch var remote = prRepo.Repository.Network.Remotes[prRemoteName]; WriteLine($"Pushing branch '{prBranchName}'."); if (_options.Debug) { WriteLine("Debug: Skipping branch push."); } else { var pushOptions = new PushOptions() { CredentialsProvider = (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = prUserName, Password = prPassword } }; prRepo.Repository.Network.Push(remote, $"+refs/heads/{prBranchName}:refs/heads/{prBranchName}", pushOptions); } // create PR WriteLine("Creating PR."); if (_options.Debug) { WriteLine("Debug: Skipping PR creation."); } else { await _destRepo.CreatePullRequestAsync(title, _options.DestinationRepoOwner, prBranchName, _options.PullRequestBranchSourceRemote, _options.SourceBranchName, _options.DestinationBranchName); } }
/// <summary> /// Push function. /// </summary> /// <param name="gitUser"> /// The git user. /// </param> /// <param name="gitPass"> /// The git pass. /// </param> /// <returns> /// Result in boolean <see cref="bool"/>. /// </returns> public bool Push(string gitUser, string gitPass) { log.Debug("Push commits"); if (File.Exists(ExternalGitPath)) { string GitOutput = ExecuteGitCommand("push"); bool result = Regex.IsMatch(GitOutput, "\\bfatal\\b", RegexOptions.IgnoreCase); if (result == true) { return false; } } else { var tc = this.gitRepo.Diff.Compare<TreeChanges>(this.gitRepo.Branches["origin/master"].Tip.Tree, this.gitRepo.Head.Tip.Tree); if (!tc.Any()) { return true; } var remote = this.gitRepo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = gitUser, Password = gitPass } }; var pushRefSpec = @"refs/heads/master"; try { this.gitRepo.Network.Push(remote, pushRefSpec, options); } catch (Exception message) { log.Debug(message); return false; } } return true; }
public override void Publish(string branch) { try { _repo.Branches.Update(_repo.Branches[branch], b => b.Remote = _repo.Network.Remotes["origin"].Name, b => b.UpstreamBranch = _repo.Branches[branch].CanonicalName); PushOptions options = null; if (_credentials != null) { options = new PushOptions { CredentialsProvider = _credentialsHandler }; } _repo.Network.Push(_repo.Branches[branch], options); } catch (LibGit2SharpException ex) { throw new SourceControlException(SourceControlText.GitPublishFailed, ex); } }
public static async void createPR(String stack) { String _gitToken = File.ReadAllText("../../../gitToken.txt"); // clone master String timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss"); String root = String.Format("D:\\local\\temp\\blimpPR{0}", timeStamp); String upstream = root + "\\" + stack; String upstreamURL = String.Format("https://github.com/Azure-App-Service/{0}.git", stack); String branch = String.Format("blimp{0}", timeStamp); Repository.Clone(upstreamURL, upstream, new CloneOptions { BranchName = "dev" }); // branch Repository repo = new Repository(upstream); repo.CreateBranch(branch); Commands.Checkout(repo, branch); // list temp repos HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("patricklee2"); HttpResponseMessage response = null; List <Repo> resultList = new List <Repo>(); List <Repo> stackRepos = null; int run = 0; while (true) { String generatedReposURL = String.Format("https://api.github.com/orgs/{0}/repos?page={1}&per_page=30&sort=full_name&direction=asc", "blessedimagepipeline", run); response = await httpClient.GetAsync(generatedReposURL); response.EnsureSuccessStatusCode(); string contentString = await response.Content.ReadAsStringAsync(); List <Repo> l = JsonConvert.DeserializeObject <List <Repo> >(contentString); resultList.AddRange(l); run++; if (l.Count < 30) { break; } } switch (stack) { case "dotnetcore": stackRepos = resultList.FindAll(isDotnetcoreRepo); break; case "node": stackRepos = resultList.FindAll(isNodeRepo); break; case "php": stackRepos = resultList.FindAll(isPhpRepo); break; case "python": stackRepos = resultList.FindAll(isPythonRepo); break; case "ruby": stackRepos = resultList.FindAll(isRubyRepo); rubyBase(resultList.FindAll(isRubyBaseRepo), root, upstream); break; } // List<Repo> stackRepos = resultList.FindAll(isStackRepo(stack)); foreach (Repo r in stackRepos) { try { Console.WriteLine("copying " + r.full_name); // pull temps String dest = root + "\\" + r.name; Repository.Clone(r.clone_url, dest, new CloneOptions { BranchName = "dev" }); // move String version = r.name.ToLower().Replace(stack + "-", ""); String suffix = ""; if (stack.Equals("php")) { suffix = "-apache"; } GitHubUtils githubUtils = new GitHubUtils("fake"); githubUtils.Delete(upstream + "\\" + version + suffix, skipGit: true); githubUtils.DeepCopy(dest, upstream + "\\" + version + suffix); // stage Commands.Stage(repo, upstream + "\\" + version + suffix); } catch (LibGit2Sharp.NameConflictException e) { } catch (Exception e) { Console.WriteLine(e.ToString()); } } // git commit // Create the committer's signature and commit //_log.Info("git commit"); Signature author = new Signature("blimp", "*****@*****.**", DateTime.Now); Signature committer = author; // Commit to the repository try { Commit commit = repo.Commit("blimp", author, committer); } catch (Exception e) { //_log.info("Empty commit"); } Remote remote = repo.Network.Remotes.Add("upstream", upstreamURL); repo.Branches.Update(repo.Head, b => b.Remote = remote.Name, b => b.UpstreamBranch = repo.Head.CanonicalName); // git push //_log.Info("git push"); LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = _gitToken.Trim(), Password = String.Empty }); repo.Network.Push(repo.Branches[branch], options); // fails if branch already exists //create PR String pullRequestURL = String.Format("https://api.github.com/repos/{0}/{1}/pulls?access_token={2}", "azure-app-service", stack, _gitToken); String body = "{ " + "\"title\": " + JsonConvert.SerializeObject("sync from templates") + ", " + "\"body\": " + JsonConvert.SerializeObject("sync from templates") + ", " + "\"head\": " + JsonConvert.SerializeObject("azure-app-service:" + branch) + ", " + "\"base\": " + JsonConvert.SerializeObject("dev") + "}"; response = await httpClient.PostAsync(pullRequestURL, new StringContent(body)); // fails on empty commits String result = await response.Content.ReadAsStringAsync(); System.Console.WriteLine(response.ToString()); System.Console.WriteLine(result); if (response.StatusCode == HttpStatusCode.UnprocessableEntity) { System.Console.WriteLine("Unable to make PR due to no differnce"); } //cleanup //new DirectoryInfo(root).Delete(true); }
public override void DeleteBranch(string branchName) { try { var branch = _repo.Branches.FirstOrDefault(b => b.FriendlyName == branchName); if (branch != null) { if (branch.TrackedBranch != null && branch.TrackedBranch.Tip != null) // check if the branch exists on the remote repo { PushOptions options = null; if (_credentials != null) { options = new PushOptions { CredentialsProvider = _credentialsHandler }; } _repo.Network.Push(branch.Remote, ":" + _repo.Branches[branchName].UpstreamBranchCanonicalName, options); } // remote local repo _repo.Branches.Remove(branch); } } catch(LibGit2SharpException ex) { throw new SourceControlException(SourceControlText.GitBranchDeleteFailed, ex); } }
/// <summary> /// Push specified references to the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="pushRefSpecs">The pushRefSpecs to push.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <param name="signature">Identity for use when updating the reflog.</param> /// <param name="logMessage">Message to use when updating the reflog.</param> public virtual void Push( Remote remote, IEnumerable <string> pushRefSpecs, PushOptions pushOptions = null, Signature signature = null, string logMessage = null) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNull(pushRefSpecs, "pushRefSpecs"); // The following local variables are protected from garbage collection // by a GC.KeepAlive call at the end of the method. Otherwise, // random crashes during push progress reporting could occur. PushTransferCallbacks pushTransferCallbacks; PackbuilderCallbacks packBuilderCallbacks; NativeMethods.git_push_transfer_progress pushProgress; NativeMethods.git_packbuilder_progress packBuilderProgress; // Return early if there is nothing to push. if (!pushRefSpecs.Any()) { return; } if (pushOptions == null) { pushOptions = new PushOptions(); } PushCallbacks pushStatusUpdates = new PushCallbacks(pushOptions.OnPushStatusError); // Load the remote. using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true)) { var callbacks = new RemoteCallbacks(null, null, null, pushOptions.Credentials); GitRemoteCallbacks gitCallbacks = callbacks.GenerateCallbacks(); Proxy.git_remote_set_callbacks(remoteHandle, ref gitCallbacks); try { Proxy.git_remote_connect(remoteHandle, GitDirection.Push); // Perform the actual push. using (PushSafeHandle pushHandle = Proxy.git_push_new(remoteHandle)) { pushTransferCallbacks = new PushTransferCallbacks(pushOptions.OnPushTransferProgress); packBuilderCallbacks = new PackbuilderCallbacks(pushOptions.OnPackBuilderProgress); pushProgress = pushTransferCallbacks.GenerateCallback(); packBuilderProgress = packBuilderCallbacks.GenerateCallback(); Proxy.git_push_set_callbacks(pushHandle, pushProgress, packBuilderProgress); // Set push options. Proxy.git_push_set_options(pushHandle, new GitPushOptions() { PackbuilderDegreeOfParallelism = pushOptions.PackbuilderDegreeOfParallelism }); // Add refspecs. foreach (string pushRefSpec in pushRefSpecs) { Proxy.git_push_add_refspec(pushHandle, pushRefSpec); } Proxy.git_push_finish(pushHandle); if (!Proxy.git_push_unpack_ok(pushHandle)) { throw new LibGit2SharpException("Push failed - remote did not successfully unpack."); } Proxy.git_push_status_foreach(pushHandle, pushStatusUpdates.Callback); Proxy.git_push_update_tips(pushHandle, signature.OrDefault(repository.Config), logMessage); } } finally { Proxy.git_remote_disconnect(remoteHandle); } } GC.KeepAlive(pushProgress); GC.KeepAlive(packBuilderProgress); GC.KeepAlive(pushTransferCallbacks); GC.KeepAlive(packBuilderCallbacks); }
/// <summary> /// Push the objectish to the destination reference on the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="objectish">The source objectish to push.</param> /// <param name="destinationSpec">The reference to update on the remote.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> /// <param name="signature">Identity for use when updating the reflog.</param> /// <param name="logMessage">Message to use when updating the reflog.</param> public virtual void Push( Remote remote, string objectish, string destinationSpec, PushOptions pushOptions = null, Signature signature = null, string logMessage = null) { Ensure.ArgumentNotNull(remote, "remote"); Ensure.ArgumentNotNull(objectish, "objectish"); Ensure.ArgumentNotNullOrEmptyString(destinationSpec, destinationSpec); Push(remote, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", objectish, destinationSpec), pushOptions, signature, logMessage); }
/// <summary> /// Push the objectish to the destination reference on the <see cref="Remote"/>. /// </summary> /// <param name="remote">The <see cref="Remote"/> to push to.</param> /// <param name="objectish">The source objectish to push.</param> /// <param name="destinationSpec">The reference to update on the remote.</param> /// <param name="pushOptions"><see cref="PushOptions"/> controlling push behavior</param> public virtual void Push( Remote remote, string objectish, string destinationSpec, PushOptions pushOptions) { Ensure.ArgumentNotNull(objectish, "objectish"); Ensure.ArgumentNotNullOrEmptyString(destinationSpec, "destinationSpec"); Push(remote, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", objectish, destinationSpec), pushOptions); }