public void After_A_Merge_Between_Main_Branch_And_Ref_Branch_Then_The_Main_Branch_Should_Be_Deletable() { /* Setup */ // First commit File.WriteAllText(Path.Combine(_repoPath, "file1.txt"), "File1's content..."); _repo.Stage("file1.txt"); _repo.Commit("First commit..."); // Checkout new branch _repo.CreateBranch("newBranch"); _repo.Checkout("newBranch"); // Second commit File.WriteAllText(Path.Combine(_repoPath, "file2.txt"), "File2's content..."); _repo.Stage("file2.txt"); _repo.Commit("Second commit..."); // Merge branches var merger = new LibGit2Sharp.Signature("Name", "@email", DateTime.Now); _repo.Checkout("master"); _repo.Merge("newBranch", merger); // Prepare for comparison var mainBranch = _repo.Branches["newBranch"]; var refBranch = _repo.Branches["master"]; /* Test */ var result = _selector.CompareBranches(new Gitcomparer.Core.Model.Branch(mainBranch), new Gitcomparer.Core.Model.Branch(refBranch)); /* Assert */ Assert.That(result.Status, Is.EqualTo(ResultStatus.Yes)); }
public override async Task <Message> HandleMessage(Message msg) { MessageContext context = new MessageContext(msg, this); return(await Task.Run <Message>(() => { string sfWorkDir = Smart.Format(WorkingDir, context); string sfUser = Smart.Format(User, context); string sfPass = Smart.Format(Pass, context); string sfMergeUser = Smart.Format(MergeUser, context); string sfMergeEmail = Smart.Format(MergeEmail, context); Repository repo = new Repository(sfWorkDir); PullOptions options = new LibGit2Sharp.PullOptions(); if (!String.IsNullOrWhiteSpace(sfUser)) { options.FetchOptions = new FetchOptions(); options.FetchOptions.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = sfUser, Password = sfPass }); } var signature = new LibGit2Sharp.Signature(new Identity(sfMergeUser, sfMergeEmail), DateTimeOffset.Now); Commands.Pull(repo, signature, options); return msg; })); }
/// <summary> /// Initializes a new instance of the <see cref="ReflogEntry"/> class. /// </summary> /// <param name="entryHandle">a <see cref="SafeHandle"/> to the reflog entry</param> public ReflogEntry(SafeHandle entryHandle) { _from = Proxy.git_reflog_entry_id_old(entryHandle); _to = Proxy.git_reflog_entry_id_new(entryHandle); _commiter = Proxy.git_reflog_entry_committer(entryHandle); message = Proxy.git_reflog_entry_message(entryHandle); }
static void Pull() { var repo = new Repository("Pad"); // Credential information to fetch PullOptions options = new PullOptions(); options.FetchOptions = new FetchOptions(); options.FetchOptions.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = "******", Password = "" }); // User information to create a merge commit var signature = new LibGit2Sharp.Signature( new Identity("npangunion", "*****@*****.**"), DateTimeOffset.Now); // Pull var mergeResult = Commands.Pull(repo, signature, options); Console.WriteLine(mergeResult.Status); if (mergeResult.Commit != null) { Console.WriteLine(mergeResult.Commit.Message); } }
/// <summary> /// Commit changes for repository /// </summary> /// <param name="commitInfo">Information about the commit</param> public void Commit(CommitInfo commitInfo) { string localServiceRepoFolder = _settings.GetServicePath(commitInfo.Org, commitInfo.Repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); using (LibGit2Sharp.Repository repo = new LibGit2Sharp.Repository(localServiceRepoFolder)) { string remoteUrl = FindRemoteRepoLocation(commitInfo.Org, commitInfo.Repository); Remote remote = repo.Network.Remotes["origin"]; if (!remote.PushUrl.Equals(remoteUrl)) { // This is relevant when we switch beteen running designer in local or in docker. The remote URL changes. // Requires adminstrator access to update files. repo.Network.Remotes.Update("origin", r => r.Url = remoteUrl); } Commands.Stage(repo, "*"); // Create the committer's signature and commit LibGit2Sharp.Signature author = new LibGit2Sharp.Signature(AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext), "@jugglingnutcase", DateTime.Now); LibGit2Sharp.Signature committer = author; // Commit to the repository LibGit2Sharp.Commit commit = repo.Commit(commitInfo.Message, author, committer); } }
public void Pull(Octokit.Repository rep) { string reppath = Path.Combine(_account.TempRepPath, rep.Name); if (!Repository.IsValid(reppath)) { Repository.Clone(rep.CloneUrl, reppath); using (var repo = new Repository(reppath)) { var upstream = repo.Network.Remotes.Add("upstream", rep.Parent.CloneUrl); Commands.Fetch(repo, "upstream", new List <string>() { }, new FetchOptions(), null); Branch upstreamMaster = repo.Branches["upstream/master"]; Branch localMaster = repo.Branches["master"]; repo.Branches.Update(localMaster, b => b.TrackedBranch = upstreamMaster.CanonicalName); var sign = new LibGit2Sharp.Signature(_account.UserName, _account.Email, new DateTimeOffset(DateTime.Now)); Commands.Pull(repo, sign, new PullOptions()); } } else { using (var repo = new Repository(reppath)) { var branchMaster = repo.Branches["master"]; Commands.Checkout(repo, branchMaster); var sign = new LibGit2Sharp.Signature(_account.UserName, _account.Email, new DateTimeOffset(DateTime.Now)); Commands.Pull(repo, sign, new PullOptions()); } } }
internal static void DescargarVistas(string proyecto) { string rutaDirectorio = $"{AppContext.BaseDirectory}Views/{proyecto}"; using (var repo = new Repository(rutaDirectorio)) { try { // Comprobar que la rama actual es la última string ramaActual = GetActualBranchRepository(proyecto); Branch rama = FindBranch(ramaActual, repo); var fetchOptions = new FetchOptions() { CredentialsProvider = Credential }; PullOptions options = new PullOptions(); options.FetchOptions = fetchOptions; var signature = new LibGit2Sharp.Signature( new Identity("MERGE_USER_NAME", "MERGE_USER_EMAIL"), DateTimeOffset.Now); MergeResult merge = Commands.Pull(repo, signature, options); } catch (Exception ex) { //repo.Info.WorkingDirectory } } }
private void CommitCore(string message) { using var repo = new Git.Repository(Location); var statusOptions = new Git.StatusOptions { DetectRenamesInIndex = true, DetectRenamesInWorkDir = true, IncludeIgnored = false, IncludeUntracked = true, RecurseUntrackedDirs = true, RecurseIgnoredDirs = false }; if (!repo.RetrieveStatus(statusOptions).IsDirty) { return; } Git.Commands.Stage(repo, "*"); var author = new Git.Signature("JournalCli", "@journalCli", DateTime.Now); var committer = author; var options = new Git.CommitOptions { PrettifyMessage = true }; var commit = repo.Commit(message, author, committer, options); }
//[Conditional("RELEASE")] public static void PullChanges() { var targetDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts"); if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } if (!Directory.Exists(Path.Combine(targetDirectory, ".git"))) { Repository.Clone("https://github.com/PMDShift/Scripts.git", targetDirectory); } else { using (var repo = new Repository(targetDirectory)) { // Credential information to fetch var options = new LibGit2Sharp.PullOptions(); var signature = new LibGit2Sharp.Signature(new Identity("Server", "*****@*****.**"), DateTimeOffset.Now); // Pull Commands.Pull(repo, signature, options); } } }
/** * Download the latest repo from GitHub.com */ public static void GitPull(LibGit2Sharp.Repository repo) { LibGit2Sharp.Signature author = new LibGit2Sharp.Signature("GitSheller", "@cornerpirate", DateTime.Now); LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); LibGit2Sharp.Signature committer = author; LibGit2Sharp.Commands.Pull(repo, author, options); }
public IResult Pull() { var settings = LoadSettings(); var error = settings.Validate(); if (error != null) { return(this.Error("Pull", $"Failed to load settings: {error}")); } try { using (var repo = new Repository(settings.LocalPath)) { LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); options.FetchOptions.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = settings.GitUser, Password = settings.GithubToken }; var signature = new LibGit2Sharp.Signature(new Identity(settings.GitUser, settings.GitUser), DateTime.Now); Commands.Pull(repo, signature, options); } } catch (System.Exception exception) { return(this.Error("Pull", $"Exception: {exception}")); } return(Result.Success()); }
/// <summary> /// Get's the latest and greatest from remote /// </summary> /// <returns></returns> public bool GitFetch() { if (cfg["UseGitRemote"] == true && GITRepoOffline == false) { toolStripOffline.Visible = false; using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"])) { LibGit2Sharp.Signature Signature = new LibGit2Sharp.Signature("pass4win", "*****@*****.**", new DateTimeOffset(2011, 06, 16, 10, 58, 27, TimeSpan.FromHours(2))); FetchOptions fetchOptions = new FetchOptions(); fetchOptions.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = cfg["GitUser"], Password = DecryptConfig(cfg["GitPass"], "pass4win") }; MergeOptions mergeOptions = new MergeOptions(); PullOptions pullOptions = new PullOptions(); pullOptions.FetchOptions = fetchOptions; pullOptions.MergeOptions = mergeOptions; try { MergeResult mergeResult = repo.Network.Pull(Signature, pullOptions); } catch { return(false); } } } return(true); }
/// <summary> /// Creates an annotated tag with the specified name. /// </summary> /// <param name="name">The name.</param> /// <param name="objectish">Revparse spec for the target object.</param> /// <param name="tagger">The tagger.</param> /// <param name="message">The message.</param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing tag, false otherwise.</param> /// <param name="tags">The <see cref="TagCollection"/> being worked with.</param> public static Tag Add(this TagCollection tags, string name, string objectish, Signature tagger, string message, bool allowOverwrite = false) { Ensure.ArgumentNotNullOrEmptyString(objectish, "target"); GitObject objectToTag = tags.repo.Lookup(objectish, GitObjectType.Any, LookUpOptions.ThrowWhenNoGitObjectHasBeenFound); return tags.Add(name, objectToTag, tagger, message, allowOverwrite); }
public void Pull() { using (var repo = new Repository(DATA_LOCATION)) { var signature = new LibGit2Sharp.Signature(new Identity("ChenTheHolyKnight", "*****@*****.**"), DateTimeOffset.Now); Commands.Pull(repo, signature, new PullOptions() { }); } }
/// <summary> /// 拉取最新代码 /// </summary> /// <returns></returns> public (bool, string, string, string) Fetch() { var lastMessage = string.Empty; var LastEmail = string.Empty; var LastTime = string.Empty; try { // Credential information to fetch LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); options.FetchOptions.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = GitLocalConfig.UserName, Password = GitLocalConfig.Password }); // User information to create a merge commit var signature = new LibGit2Sharp.Signature( new Identity(GitLocalConfig.LocalName, GitLocalConfig.LocalEmail), DateTimeOffset.Now); // Pull var re = Commands.Pull(_repository, signature, options); _logger?.Invoke($"【Git】git pull success >>> " + re.Status.ToString(), LogLevel.Info); var commitLog2 = GetBrandLastCommintInfo(); if (!string.IsNullOrEmpty(commitLog2.Item1)) { lastMessage = commitLog2.Item1; _logger?.Invoke($"【Git】Commit Message:\r\n" + commitLog2.Item1, LogLevel.Info); } if (!string.IsNullOrEmpty(commitLog2.Item2)) { LastEmail = commitLog2.Item2; _logger?.Invoke($"【Git】Commit Author:\r\n" + commitLog2.Item2, LogLevel.Info); } if (!string.IsNullOrEmpty(commitLog2.Item3)) { LastTime = commitLog2.Item3; _logger?.Invoke($"【Git】Commit Time:\r\n" + commitLog2.Item3, LogLevel.Info); } } catch (Exception e) { _logger?.Invoke($"【Git】git pull fail:{e.Message}", LogLevel.Error); return(false, null, null, null); } return(true, lastMessage, LastEmail, LastTime); }
private Commit Commit(string Comments) { CheckinComment = Comments; using (var repo = new LibGit2Sharp.Repository(RepositoryRootFolder)) { // Create the committer's signature and commit Signature author = new LibGit2Sharp.Signature(SolutionSourceControlAuthorName, SolutionSourceControlAuthorEmail, DateTime.Now); Signature committer = author; // Commit to the repository return(repo.Commit(Comments, author, committer)); } }
public CommitRewriteInfo ThisUser(Commit commit) { var sg = new Signature(string.IsNullOrEmpty(_user.Name) ? _user.Login : _user.Name, _user.Email, commit.Author.When); return(new CommitRewriteInfo { Author = sg, Committer = sg, Message = commit.Message }); }
private string Commit(Repository repository, string commitMessage) { var author = new LibGit2Sharp.Signature("GitUITests", "*****@*****.**", DateTimeOffset.Now); var committer = author; var options = new LibGit2Sharp.CommitOptions() { PrettifyMessage = false }; var commit = repository.Commit(commitMessage, author, committer, options); return(commit.Id.Sha); }
private async Task AsyncMain() { _config = Toml.ReadFile <ProxyConfig>("config.toml"); _defaultSignature = new Signature(new Identity(_config.DefaultAuthor.Name, _config.DefaultAuthor.Email), DateTimeOffset.Now); _ghClient = new GitHubClient(new ProductHeaderValue("GitHubProxy")) { Credentials = new GitHubCredentials(_config.Token) }; _ghUser = await _ghClient.User.Current(); Logger.Debug(_ghUser.Id); Logger.Info($"Logged in to GitHub as {_ghUser.Name} ({_ghUser.Login})"); _ghSrc = await _ghClient.Repository.Get(_config.Source.User, _config.Source.Repo); _ghDest = await _ghClient.Repository.Get(_config.Destination.User, _config.Destination.Repo); Logger.Debug(_ghSrc.Id); Logger.Debug(_ghDest.Id); Logger.Info($"Proxying {_ghSrc.Owner.Login}/{_ghSrc.Name} to {_ghDest.Owner.Login}/{_ghDest.Name}"); await SetupSrcRepo(); using (var srcRepo = new GitRepository("srcRepo")) { Logger.Debug(srcRepo.Info.Path); foreach (var branch in srcRepo.Branches) { Logger.Debug(branch.ToString()); } } while (true) { Console.WriteLine(); Logger.Info("Proxying..."); await ProxyCommits(); _ghSrc = await _ghClient.Repository.Get(_config.Source.User, _config.Source.Repo); _ghDest = await _ghClient.Repository.Get(_config.Destination.User, _config.Destination.Repo); await ProxyReleases(); Logger.Info("Done."); await Task.Delay(_config.Interval * 60 * 1000); } }
public void Commit(string commitMessage) { var numberOfChanges = _repository.RetrieveStatus(new LibGit2Sharp.StatusOptions()).Count(); Console.WriteLine($"Committing {numberOfChanges} changed files."); Commands.Stage(_repository, "*"); // equivalent of "git add ." // We need to specify the author for the commit, grab it from config Configuration config = _repository.Config; Signature author = config.BuildSignature(DateTimeOffset.Now); _repository.Commit(commitMessage, author, author); }
/** * Save the locally modified files into the local repository */ private static void GitCommit(LibGit2Sharp.Repository repo) { Commands.Stage(repo, "*"); LibGit2Sharp.Signature author = new LibGit2Sharp.Signature("GitSheller", "@cornerpirate", DateTime.Now); LibGit2Sharp.Signature committer = author; // This line throws a LibGit2Sharp.EmptyCommitException when the file has not been altered. try { LibGit2Sharp.Commit commit = repo.Commit("Committed", author, committer); } catch (LibGit2Sharp.EmptyCommitException ece) { // No changes detected. } }
public static async Task <(bool result, string message)> GitPullold() { using (var repo = new Repository(SettingManager.FolderData)) { // Credential information to fetch LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); //options.FetchOptions.CredentialsProvider = new CredentialsHandler( // (url, usernameFromUrl, types) => // new UsernamePasswordCredentials() // { // Username = SettingManager.UserName, // Password = SettingManager.Password // }); https: //raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-json/dpc-covid19-ita-regioni.json // User information to create a merge commit var signature = new LibGit2Sharp.Signature( new Identity("john.doe", "*****@*****.**"), DateTimeOffset.Now); // Pull return(await Task.Run(() => { try { var result = Commands.Pull(repo, signature, options); switch (result.Status) { case MergeStatus.UpToDate: MessageBox.Show(Properties.Resources.GitUpToDate); break; case MergeStatus.Conflicts: MessageBox.Show(Properties.Resources.GitConflict); break; case MergeStatus.FastForward: MessageBox.Show(Properties.Resources.GitFastForward); break; } return (result.Status == MergeStatus.FastForward, ""); } catch (Exception e) { return (false, e.Message); } })); } }
/// <summary> /// 更新脚本 /// </summary> public static void CheckLuaUpdate() { var gitPath = $"{Path}lua/"; var git = "https://gitee.com/chenxuuu/receiver-meow-lua.git"; if (!Directory.Exists(gitPath)) { Log.Warn("初始化Lua脚本", "没有检测到Lua脚本文件夹,即将下载最新脚本"); try { Log.Info("初始化Lua脚本", "正在获取脚本,请稍后"); Repository.Clone(git, gitPath); Log.Info("初始化Lua脚本", "更新完成!可以开始用了"); } catch (Exception ee) { Log.Error("初始化Lua脚本", $"更新脚本文件失败,错误信息:{ee.Message}\r\n如果始终失败,请手动执行下面的命令,初始化脚本后,再尝试运行:\r\n" + $"git clone {git} lua"); } } else { Log.Info("更新Lua脚本", "正在检查Lua脚本是否有更新。。。"); try { if (Repository.IsValid($"{Path}lua/")) { Log.Info("更新Lua脚本", "正在尝试更新脚本,请稍后"); var options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); var signature = new LibGit2Sharp.Signature( new Identity("MERGE_USER_NAME", "MERGE_USER_EMAIL"), DateTimeOffset.Now); using var repo = new Repository(gitPath); Commands.Pull(repo, signature, options); Log.Info("更新Lua脚本", "更新操作执行完毕"); } else { Log.Warn("更新Lua脚本", "检测不到Git目录结构,如果你是自己写的脚本,请忽略该信息。如果你想恢复到默认脚本,请删除lua文件夹后重启软件"); } } catch (Exception e) { Log.Warn("更新Lua脚本", $"拉取最新脚本代码失败,错误原因:\n{e.Message}"); } } }
/// <summary> /// 更新脚本 /// </summary> /// <returns></returns> public static string UpdateScript() { string gitPath = Common.AppDirectory; if (!Repository.IsValid(gitPath)) { return("未检测到git仓库!工程不存在!"); //return;//工程不存在 } using (var repo = new Repository(gitPath)) { string lastCommit = repo.Commits.First().Sha;//当前提交的特征值 // Credential information to fetch LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions { FetchOptions = new FetchOptions() }; // User information to create a merge commit var signature = new LibGit2Sharp.Signature( new Identity("MERGE_USER_NAME", "MERGE_USER_EMAIL"), DateTimeOffset.Now); // Pull try { Commands.Pull(repo, signature, options); } catch { return("代码拉取失败,请检查网络!"); } string newCommit = repo.Commits.First().Sha;//pull后的特征值 if (lastCommit != newCommit) { Directory.Delete(gitPath + "lua\\", true); Tools.CopyDirectory(gitPath + "appdata\\lua\\", gitPath + "lua\\"); Tools.CopyDirectory(gitPath + "appdata\\xml\\", gitPath + "xml\\", false); return("更新完成!"); } else { return("当前已是最新版本"); } } }
public Task <string> Pull(string localRepository, string author, string email) { var options = new PullOptions { FetchOptions = new FetchOptions { CredentialsProvider = (url, usernameFromUrl, types) => _gitCredential, OnProgress = (string progress) => { _logger.LogInformation(progress); return(true); } }, MergeOptions = new MergeOptions { FileConflictStrategy = CheckoutFileConflictStrategy.Theirs, } }; var repo = new Repository(localRepository); try { var signature = new LibGit2Sharp.Signature(author, email, DateTimeOffset.UtcNow); Commands.Pull(repo, signature, options); return(Task.FromResult("")); } catch (MergeFetchHeadNotFoundException headEx) { // If the master branch is not found, then it's an empty repository, and we should not mark the task as error if (headEx.Message.Contains("refs/heads/master") || headEx.Message.Contains("refs/heads/main")) { _logger.LogWarning(headEx.Message); return(Task.FromResult("")); } else { _logger.LogError(headEx, headEx.Message); return(Task.FromResult(headEx.Message)); } } catch (Exception ex) { _logger.LogError(ex, ex.Message); return(Task.FromResult(ex.Message)); } }
public void Pull(string mergeUserName, string mergeUserEmail, string userName = "", string password = "") { LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); options.FetchOptions.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = userName, Password = password }); var signature = new LibGit2Sharp.Signature( new Identity(mergeUserName, mergeUserEmail), DateTimeOffset.Now); Commands.Pull(repository, signature, options); }
bool PullCore(CommonRepository repository) { using (var repo = new Repository(repository.Path)) { LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); options.FetchOptions.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = "******", Password = "******" }); var signature = new LibGit2Sharp.Signature(new Identity("DXVisualTestsBot", "*****@*****.**"), DateTimeOffset.Now); return(Commands.Pull(repo, signature, options).Status != MergeStatus.Conflicts); } }
public ReferenceRepository(GitModuleTestHelper moduleTestHelper) { _moduleTestHelper = moduleTestHelper; using (var repository = new LibGit2Sharp.Repository(_moduleTestHelper.Module.WorkingDir)) { _moduleTestHelper.CreateRepoFile("A.txt", "A"); repository.Index.Add("A.txt"); var message = "A commit message"; var author = new LibGit2Sharp.Signature("GitUITests", "*****@*****.**", DateTimeOffset.Now); var committer = author; var options = new LibGit2Sharp.CommitOptions(); var commit = repository.Commit(message, author, committer, options); CommitHash = commit.Id.Sha; } }
private void GitPull() { Trace("Pulling current branch"); using (var repo = new Repository(RepositoryPath())) { // Credential information to fetch var options = new LibGit2Sharp.PullOptions { FetchOptions = DefaultFetchOptions, MergeOptions = DefaultMergeOptions, }; // User information to create a merge commit var signature = new LibGit2Sharp.Signature(new Identity("service", "*****@*****.**"), DateTimeOffset.Now); // Pull Commands.Pull(repo, signature, options); } RunSpecialCommand(RepositoryPath(), "lfs pull"); }
private void ValidateGitRepo() { if (Git.Repository.IsValid(Location)) { return; } Git.Repository.Init(Location); using var repo = new Git.Repository(Location); Git.Commands.Stage(repo, "*"); var author = new Git.Signature("JournalCli", "@journalCli", DateTime.Now); var committer = author; var options = new Git.CommitOptions { PrettifyMessage = true }; var commit = repo.Commit("Initial commit", author, committer, options); }
/// <summary> /// Add all changes in service repo and push to remote /// </summary> /// <param name="commitInfo">the commit information for the service</param> public void PushChangesForRepository(CommitInfo commitInfo) { string localServiceRepoFolder = _settings.GetServicePath(commitInfo.Org, commitInfo.Repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); var watch = System.Diagnostics.Stopwatch.StartNew(); using (Repository repo = new Repository(localServiceRepoFolder)) { // Restrict users from empty commit if (repo.RetrieveStatus().IsDirty) { string remoteUrl = FindRemoteRepoLocation(commitInfo.Org, commitInfo.Repository); Remote remote = repo.Network.Remotes["origin"]; if (!remote.PushUrl.Equals(remoteUrl)) { // This is relevant when we switch beteen running designer in local or in docker. The remote URL changes. // Requires adminstrator access to update files. repo.Network.Remotes.Update("origin", r => r.Url = remoteUrl); } Commands.Stage(repo, "*"); // Create the committer's signature and commit LibGit2Sharp.Signature author = new LibGit2Sharp.Signature(AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext), "@jugglingnutcase", DateTime.Now); LibGit2Sharp.Signature committer = author; // Commit to the repository LibGit2Sharp.Commit commit = repo.Commit(commitInfo.Message, author, committer); PushOptions options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GetAppToken(), Password = string.Empty }; repo.Network.Push(remote, @"refs/heads/master", options); } } watch.Stop(); _logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "push cahnges - {0} ", watch.ElapsedMilliseconds); }
public Task UpdateMod(string gamePath, CancellationToken token, Action <float> progressReporter) { if (_currentLoadingTask != null) { return(_currentLoadingTask); } return(_currentLoadingTask = Task.Factory.StartNew(() => { using (var repo = new Repository(ClonePath)) { var originRemoteRep = repo.Network.Remotes["origin"]; var pullOptions = new PullOptions() { FetchOptions = new FetchOptions() { OnTransferProgress = progress => { var percent = (float)progress.ReceivedObjects / progress.TotalObjects; progressReporter?.Invoke(percent); return true; } }, MergeOptions = new MergeOptions() { } }; var signature = new LibGit2Sharp.Signature(new Identity("Anonymous", "*****@*****.**"), DateTimeOffset.Now); Commands.Pull(repo, signature, pullOptions); ActiveModRevision = repo.Head.Commits.FirstOrDefault()?.Message; } RewriteModModule(gamePath); _currentLoadingTask = null; }, token)); }
/// <summary> /// Create a new local branch with the specified name /// </summary> /// <param name="branches">The <see cref="BranchCollection"/> being worked with.</param> /// <param name="name">The name of the branch.</param> /// <param name="committish">Revparse spec for the target commit.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/></param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing branch, false otherwise.</param> /// <returns>A new <see cref="Branch"/>.</returns> public static Branch Add(this BranchCollection branches, string name, string committish, Signature signature, string logMessage = null, bool allowOverwrite = false) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNullOrEmptyString(committish, "committish"); var commit = branches.repo.LookupCommit(committish); if (logMessage == null) { var createdFrom = committish != "HEAD" ? committish : branches.repo.Info.IsHeadDetached ? commit.Sha : branches.repo.Head.Name; logMessage = "branch: Created from " + createdFrom; } return branches.Add(name, commit, signature, logMessage, allowOverwrite); }
public void draw( Console console, int i ) { scroll = GUILayout.BeginScrollView( scroll ); try { pathNodes.Clear(); treeView.nodes.Clear(); changes = changes ?? console.repo.Diff.Compare(); foreach ( TreeEntryChanges change in changes ) { buildTreeView( change ); } foreach ( string untrackedFile in untracked ) { buildTreeView( untrackedFile ); } drawTreeView( console ); } catch {} GUILayout.EndScrollView(); GUILayout.Label( "Commit message:" ); commitText = GUILayout.TextArea( commitText ); if ( GUILayout.Button( "Commit Changes" ) ) { Signature signature = new Signature( "Jerome Doby", "*****@*****.**", System.DateTimeOffset.Now ); //# Stage everything string[] stage = new string[ checkboxValues.Count ]; i = 0; foreach ( KeyValuePair<string, bool> pair in checkboxValues ) { if ( pair.Value ) { stage[ i ] = pair.Key; i++; } } stage = stage.Where( x => !string.IsNullOrEmpty( x ) ).ToArray(); if ( stage.Length == 0 ) { console.currentError = "You cannot commit without staged items."; console.currentErrorLocation = rect; } else if ( commitText.Equals( string.Empty ) ) { console.currentError = "Please enter a commit message."; console.currentErrorLocation = rect; } else { console.repo.Index.Stage( stage ); console.repo.Commit( commitText, signature ); checkboxValues.Clear(); foldoutValues.Clear(); console.fetch(); } commitText = string.Empty; } }
/// <summary> /// Get's the latest and greatest from remote /// </summary> /// <returns></returns> public bool GitFetch() { if (cfg["UseGitRemote"] == true && GITRepoOffline == false) { toolStripOffline.Visible = false; using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"])) { LibGit2Sharp.Signature Signature = new LibGit2Sharp.Signature("pass4win", "*****@*****.**", new DateTimeOffset(2011, 06, 16, 10, 58, 27, TimeSpan.FromHours(2))); FetchOptions fetchOptions = new FetchOptions(); fetchOptions.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = cfg["GitUser"], Password = DecryptConfig(cfg["GitPass"], "pass4win") }; MergeOptions mergeOptions = new MergeOptions(); PullOptions pullOptions = new PullOptions(); pullOptions.FetchOptions = fetchOptions; pullOptions.MergeOptions = mergeOptions; try { MergeResult mergeResult = repo.Network.Pull(Signature, pullOptions); } catch { return false; } } } return true; }
/// <summary> /// Get's the latest and greatest from remote /// </summary> /// <returns></returns> public bool GitFetch() { if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false) { toolStripOffline.Visible = false; using (var repo = new Repository(Cfg["PassDirectory"])) { var signature = new Signature("pass4win", "*****@*****.**", new DateTimeOffset(2011, 06, 16, 10, 58, 27, TimeSpan.FromHours(2))); var fetchOptions = new FetchOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var mergeOptions = new MergeOptions(); var pullOptions = new PullOptions { FetchOptions = fetchOptions, MergeOptions = mergeOptions }; try { repo.Network.Pull(signature, pullOptions); } catch (Exception) { return false; } } } return true; }
private void loadWorker_DoWork(object sender, DoWorkEventArgs e) { try { if (File.Exists("ensage.log")) { string[] strArray = File.ReadAllLines("ensage.log"); int count = strArray.Length - 1000; if (count > 0) File.WriteAllLines("ensage.log", Enumerable.Skip<string>(strArray, count)); } } catch (Exception) { } try { using (WebClient webClient = new WebClient()) { if (Program.IsContributor()) newsBox.Text = webClient.DownloadString("http://zynox.net/ensage/news2.php"); else loadWorker.ReportProgress(1, webClient.DownloadString("http://zynox.net/ensage/news.php")); } } catch (Exception) { if (newsBox.Text == string.Empty) loadWorker.ReportProgress(1, "Can't download news content."); } if (!Directory.Exists(_userPath)) return; string[] directories = Directory.GetDirectories(_userPath); if (directories.Length == 0) { loadWorker.ReportProgress(9); } else { foreach (string path1 in directories) { foreach (string path2 in Directory.GetDirectories(path1)) { try { LibGit2Sharp.Signature merger = new LibGit2Sharp.Signature("local", "localhost", new DateTimeOffset()); using (LibGit2Sharp.Repository repository = new LibGit2Sharp.Repository(path2, null)) { MergeOptions mergeOptions = new MergeOptions() { MergeFileFavor = MergeFileFavor.Theirs }; repository.Network.Pull(merger, new PullOptions() { MergeOptions = mergeOptions }); } } catch (Exception ex) { int num = (int)MessageBox.Show(ex.Message); continue; } string str1 = path2.Substring(_userPath.Length + 1); loadWorker.ReportProgress(2, str1); foreach (string path3 in Directory.GetDirectories(path2)) { string str2 = path3.Substring(path3.LastIndexOf('\\') + 1); bool flag; if (str2 == "Libraries") { flag = true; loadWorker.ReportProgress(3, str1); } else if (str2 == "Scripts") { flag = false; loadWorker.ReportProgress(4, str1); } else continue; foreach (string str3 in Directory.GetFiles(path3)) { string str4 = str3.Substring(str3.LastIndexOf('\\') + 1); string path4 = flag ? Path.Combine("Scripts", "libs", str4) : Path.Combine("Scripts", str4); loadWorker.ReportProgress(flag ? 5 : 6, new string[2] { str1, str4 }); if (File.Exists(path4)) loadWorker.ReportProgress(flag ? 7 : 8, new string[2] { str1, str4 }); } } } } } }
public NodeBranch Checkout(Commit commit, CheckoutOptions options = null, Signature signature = null) { return new NodeBranch(Repository.Checkout(commit, options ?? new CheckoutOptions(), signature)); }
public NodeBranch Checkout(string commitishOrBranchSpec, CheckoutOptions options = null, Signature signature = null) { return new NodeBranch(Repository.Checkout(commitishOrBranchSpec, options ?? new CheckoutOptions(), signature)); }
public CherryPickResult CherryPick(Commit commit, Signature signature, CherryPickOptions options = null) { return Repository.CherryPick(commit, signature, options ?? new CherryPickOptions()); }