public void CreateRepository() { path = Path.Combine(Path.GetTempPath(), "test-" + Guid.NewGuid().ToString()); if (Directory.Exists(path)) { UpdateFileAttributes(new DirectoryInfo(path)); Directory.Delete(path, true); } Directory.CreateDirectory(path); LibGit2Sharp.Repository.Init(path); var author = new LibGit2Sharp.Signature("Bjoern", "*****@*****.**", DateTime.Now); var commitOptions = new LibGit2Sharp.CommitOptions(); CopyWorkbook("Book1_v1.xlsx", Path.Combine(path, "xlwings", "tests", "test book.xlsx")); CopyWorkbook("Book2_v1.xlsx", Path.Combine(path, "Book2.xlsx")); using (var gitRepo = new LibGit2Sharp.Repository(path)) { LibGit2Sharp.Commands.Stage(gitRepo, "*"); gitRepo.Commit("Added Book1 and Book2", author, author, new LibGit2Sharp.CommitOptions()); gitRepo.Branches.Add("dev", "HEAD"); LibGit2Sharp.Commands.Checkout(gitRepo, "dev"); File.Delete(Path.Combine(path, "Book2.xlsx")); //delete Book2.xlsx CopyWorkbook("Book1_v2.xlsx", Path.Combine(path, "xlwings", "tests", "test book.xlsx")); //new version LibGit2Sharp.Commands.Stage(gitRepo, "*"); gitRepo.Commit("Modified Book1, Deleted Book2", author, author, new LibGit2Sharp.CommitOptions()); } }
public Signature _mapSignature(LibGit2Sharp.Signature signature) { if (signature == null) { return(null); } var signatureModel = new Signature { Name = signature.Name, When = signature.When, }; return(signatureModel); }
public ReferenceRepository() { _moduleTestHelper = new GitModuleTestHelper(); 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; } }
public void Commit(string path, string userName, string email) { var fileRepositoryPath = System.IO.Path.Combine(Workbook.Repository.Path.Replace("/", "\\"), Workbook.Path.Replace("/", "\\")); //checkout branch LibGit2Sharp.Commands.Checkout(Workbook.Repository.GitRepository, Name); //copy file File.Copy(path, fileRepositoryPath, true); //stage LibGit2Sharp.Commands.Stage(Workbook.Repository.GitRepository, fileRepositoryPath); //prepare commit details var author = new LibGit2Sharp.Signature(userName, email, DateTime.Now); var commitOptions = new LibGit2Sharp.CommitOptions(); var commitMessage = "Updated " + Workbook.Path; var committer = author; //commit Workbook.Repository.GitRepository.Commit(commitMessage, author, committer, commitOptions); }
static void PushChangedFiles(IEnumerable <string> paths, string message, string token, string name, string email) { var dir = LibGit2Sharp.Repository.Discover("."); using (var repo = new LibGit2Sharp.Repository(dir)) { LibGit2Sharp.Commands.Stage(repo, paths); var author = new LibGit2Sharp.Signature(name, email, DateTimeOffset.Now); repo.Commit(message, author, author, new LibGit2Sharp.CommitOptions { }); var remote = repo.Network.Remotes["origin"]; var options = new LibGit2Sharp.PushOptions { CredentialsProvider = (_url, _user, _cred) => new LibGit2Sharp.UsernamePasswordCredentials { Username = "******", Password = token } }; repo.Network.Push(remote, @"refs/heads/master", options); } }
public void Checkout(String name, LibGit2Sharp.Signature sig) { if (commitRepo.HasUncommittedChanges()) { throw new InvalidOperationException("Cannot change branches with uncommitted changes. Please commit first and try again."); } var localRef = localRefRoot + name; LibGit2Sharp.Branch branch = repo.Branches[localRef]; var remoteRef = remoteRefRoot + name; var remoteBranch = repo.Branches[remoteRef]; //Found a local branch, use it if (branch != null) { LibGit2Sharp.Commands.Checkout(repo, branch); if (remoteBranch != null && remoteBranch.Tip != repo.Head.Tip) { repo.Merge(remoteBranch, sig, new LibGit2Sharp.MergeOptions()); } return; //Was able to do a simple checkout to a local branch } //No local branch, use the remote branch and create a new local branch if (remoteBranch != null) { //Since we already know there is not a local branch, create it var localBranch = repo.Branches.Add(name, remoteBranch.Tip); LinkBranchToRemote(localBranch); LibGit2Sharp.Commands.Checkout(repo, localBranch); return; //Was able to find branch in remote repo. Checkout to it } throw new InvalidOperationException($"Cannot find branch {name} in current local or remote branches. Do you need to create the branch or pull in updates?"); }
/// <summary> /// We used to group commits in a tree object so there would be only one commit per /// change but this doesn't work for trees that end up being too big (around 20K files). /// By using LibGit2Sharp we still group changes in one and we don't need to create a new /// tree. Everything happens locally in the host executing the push. /// </summary> /// <param name="filesToCommit">Collection of files to update.</param> /// <param name="repoUri">The repository to push the files to.</param> /// <param name="branch">The branch to push the files to.</param> /// <param name="commitMessage">The commmit message.</param> /// <returns></returns> protected async Task CommitFilesAsync( List <GitFile> filesToCommit, string repoUri, string branch, string commitMessage, ILogger _logger, string pat) { string dotnetMaestro = "dotnet-maestro"; using (_logger.BeginScope("Pushing files to {branch}", branch)) { string tempRepoFolder = Path.Combine(TemporaryRepositoryPath, Path.GetRandomFileName()); try { string repoPath = LibGit2Sharp.Repository.Clone( repoUri, tempRepoFolder, new LibGit2Sharp.CloneOptions { BranchName = branch, Checkout = true, CredentialsProvider = (url, user, cred) => new LibGit2Sharp.UsernamePasswordCredentials { // The PAT is actually the only thing that matters here, the username // will be ignored. Username = dotnetMaestro, Password = pat } }); using (LibGit2Sharp.Repository localRepo = new LibGit2Sharp.Repository(repoPath)) { foreach (GitFile file in filesToCommit) { string filePath = Path.Combine(tempRepoFolder, file.FilePath); if (file.Operation == GitFileOperation.Add) { if (!File.Exists(filePath)) { string parentFolder = Directory.GetParent(filePath).FullName; Directory.CreateDirectory(parentFolder); } using (FileStream stream = File.Create(filePath)) { byte[] contentBytes = GetUtf8ContentBytes(file.Content, file.ContentEncoding); await stream.WriteAsync(contentBytes, 0, contentBytes.Length); } } else { File.Delete(Path.Combine(tempRepoFolder, file.FilePath)); } } LibGit2Sharp.Commands.Stage(localRepo, "*"); LibGit2Sharp.Signature author = new LibGit2Sharp.Signature(dotnetMaestro, $"@{dotnetMaestro}", DateTime.Now); LibGit2Sharp.Signature commiter = author; localRepo.Commit(commitMessage, author, commiter, new LibGit2Sharp.CommitOptions { AllowEmptyCommit = false, PrettifyMessage = true }); localRepo.Network.Push(localRepo.Branches[branch], new LibGit2Sharp.PushOptions { CredentialsProvider = (url, user, cred) => new LibGit2Sharp.UsernamePasswordCredentials { // The PAT is actually the only thing that matters here, the username // will be ignored. Username = dotnetMaestro, Password = pat } }); } } catch (LibGit2Sharp.EmptyCommitException) { _logger.LogInformation("There was nothing to commit..."); } catch (Exception exc) { // This was originally a DarcException. Making it an actual Exception so we get to see in AppInsights if something failed while // commiting the changes throw new Exception($"Something went wrong when pushing the files to repo {repoUri} in branch {branch}", exc); } finally { try { // Libgit2Sharp behaves similarly to git and marks files under the .git/objects hierarchy as read-only, // thus if the read-only attribute is not unset an UnauthorizedAccessException is thrown. GitFileManager.NormalizeAttributes(tempRepoFolder); Directory.Delete(tempRepoFolder, true); } catch (DirectoryNotFoundException) { // If the directory wasn't found, that means that the clone operation above failed // but this error isn't interesting at all. } } } }
/// <summary> /// We used to group commits in a tree object so there would be only one commit per /// change but this doesn't work for trees that end up being too big (around 20K files). /// By using LibGit2Sharp we still group changes in one and we don't need to create a new /// tree. Everything happens locally in the host executing the push. /// </summary> /// <param name="filesToCommit">Collection of files to update.</param> /// <param name="repoUri">The repository to push the files to.</param> /// <param name="branch">The branch to push the files to.</param> /// <param name="commitMessage">The commmit message.</param> /// <returns></returns> public async Task PushFilesAsync( List <GitFile> filesToCommit, string repoUri, string branch, string commitMessage) { string dotnetMaestro = "dotnet-maestro"; using (_logger.BeginScope("Pushing files to {branch}", branch)) { (string owner, string repo) = ParseRepoUri(repoUri); string tempRepoFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); try { string repoPath = LibGit2Sharp.Repository.Clone( repoUri, tempRepoFolder, new LibGit2Sharp.CloneOptions { BranchName = branch, Checkout = true }); using (LibGit2Sharp.Repository localRepo = new LibGit2Sharp.Repository(repoPath)) { foreach (GitFile file in filesToCommit) { string filePath = Path.Combine(tempRepoFolder, file.FilePath); if (file.Operation == GitFileOperation.Add) { if (!File.Exists(filePath)) { string parentFolder = Directory.GetParent(filePath).FullName; Directory.CreateDirectory(parentFolder); } using (FileStream stream = File.Create(filePath)) { byte[] contentBytes = this.GetContentBytes(file.Content); await stream.WriteAsync(contentBytes, 0, contentBytes.Length); } } else { File.Delete(Path.Combine(tempRepoFolder, file.FilePath)); } } LibGit2Sharp.Commands.Stage(localRepo, "*"); LibGit2Sharp.Signature author = new LibGit2Sharp.Signature(dotnetMaestro, $"@{dotnetMaestro}", DateTime.Now); LibGit2Sharp.Signature commiter = author; localRepo.Commit(commitMessage, author, commiter, new LibGit2Sharp.CommitOptions { AllowEmptyCommit = false, PrettifyMessage = true }); localRepo.Network.Push(localRepo.Branches[branch], new LibGit2Sharp.PushOptions { CredentialsProvider = (url, user, cred) => new LibGit2Sharp.UsernamePasswordCredentials { Username = dotnetMaestro, Password = Client.Credentials.Password } }); } } catch (LibGit2Sharp.EmptyCommitException) { _logger.LogInformation("There was nothing to commit..."); } catch (Exception exc) { throw new DarcException($"Something went wrong when pushing the files to repo {repo} in branch {branch}", exc); } finally { // Libgit2Sharp behaves similarly to git and marks files under the .git/objects hierarchy as read-only, // thus if the read-only attribute is not unset an UnauthorizedAccessException is thrown. GitFileManager.NormalizeAttributes(tempRepoFolder); Directory.Delete(tempRepoFolder, true); } } }
public void Checkout(String friendlyName, [FromServices] LibGit2Sharp.Signature sig) { branchRepo.Checkout(friendlyName, sig); }