public ActionResult Clone(string id, RepositoryDetailModel model) { if (!User.IsInRole(Definitions.Roles.Administrator) && !UserConfiguration.Current.AllowUserRepositoryCreation) { return(RedirectToAction("Unauthorized", "Home")); } if (model != null && !String.IsNullOrEmpty(model.Name)) { model.Name = Regex.Replace(model.Name, @"\s", ""); } if (String.IsNullOrEmpty(model.Name)) { ModelState.AddModelError("Name", Resources.Repository_Create_NameFailure); } else if (ModelState.IsValid) { if (RepositoryRepository.Create(ConvertRepositoryDetailModel(model))) { string targetRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, model.Name); if (!Directory.Exists(targetRepositoryPath)) { string sourceRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, id); LibGit2Sharp.CloneOptions options = new LibGit2Sharp.CloneOptions() { IsBare = true, Checkout = false }; LibGit2Sharp.Repository.Clone(sourceRepositoryPath, targetRepositoryPath, options); using (var repo = new LibGit2Sharp.Repository(targetRepositoryPath)) { if (repo.Network.Remotes.Any(r => r.Name == "origin")) { repo.Network.Remotes.Remove("origin"); } } TempData["CloneSuccess"] = true; return(RedirectToAction("Index")); } else { RepositoryRepository.Delete(model.Name); ModelState.AddModelError("", Resources.Repository_Create_DirectoryExists); } } else { ModelState.AddModelError("", Resources.Repository_Create_Failure); } } ViewBag.ID = id; PopulateEditData(); return(View(model)); }
public static async Task BUYLCloneOrUpdateRepository() { if (!CheckForContentRepositoryDirectory()) { //prg.ShowDialog(); Directory.CreateDirectory(pathToLocalContentRepository); LibGit2Sharp.CloneOptions op = new LibGit2Sharp.CloneOptions(); LibGit2Sharp.Repository.Clone(urlContentRepository, pathToLocalContentRepository, op); LogManager.FileLogService.Instance.Info(string.Format("Repository cloned to {0}", pathToLocalContentRepository), typeof(GitContentLoader)); //prg.Close(); } else { using (var repo = new LibGit2Sharp.Repository(pathToLocalContentRepository)) { LibGit2Sharp.Remote remote = repo.Network.Remotes["origin"]; LibGit2Sharp.FetchOptions op = new LibGit2Sharp.FetchOptions(); repo.Network.Fetch(remote); LogManager.FileLogService.Instance.Info(string.Format("Repository update fetched to {0}", pathToLocalContentRepository), typeof(GitContentLoader)); } } }
public JarFinder(IPandoraGitSettings gitSettings, IPandoraContext context) { _gitSettings = gitSettings; _context = context; var cloneOptions = new LibGit2Sharp.CloneOptions { IsBare = false, Checkout = true, CredentialsProvider = new LibGit2Sharp.Handlers.CredentialsHandler((a, b, c) => new LibGit2Sharp.UsernamePasswordCredentials() { Username = gitSettings.Username, Password = gitSettings.Password }) }; try { _checkoutDir = LibGit2Sharp.Repository.Clone(gitSettings.SourceUrl, gitSettings.WorkingDir, cloneOptions); } catch (LibGit2Sharp.LibGit2SharpException ex) { Exception error = new Exception("Unable to checkout repository. Please check the credentials", ex); throw error; } }
/// <summary> /// Clone a remote git repo. /// </summary> /// <param name="repoUri">Repository uri to clone</param> /// <param name="commit">Branch, commit, or tag to checkout</param> /// <param name="targetDirectory">Target directory to clone to</param> /// <param name="gitDirectory">Location for the .git directory, or null for default</param> /// <returns></returns> protected void Clone(string repoUri, string commit, string targetDirectory, ILogger _logger, string pat, string gitDirectory) { string dotnetMaestro = "dotnet-maestro"; LibGit2Sharp.CloneOptions cloneOptions = new LibGit2Sharp.CloneOptions { Checkout = false, 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 (_logger.BeginScope("Cloning {repoUri} to {targetDirectory}", repoUri, targetDirectory)) { try { _logger.LogDebug($"Cloning {repoUri} to {targetDirectory}"); string repoPath = LibGit2Sharp.Repository.Clone( repoUri, targetDirectory, cloneOptions); LibGit2Sharp.CheckoutOptions checkoutOptions = new LibGit2Sharp.CheckoutOptions { CheckoutModifiers = LibGit2Sharp.CheckoutModifiers.Force, }; _logger.LogDebug($"Reading local repo from {repoPath}"); using (LibGit2Sharp.Repository localRepo = new LibGit2Sharp.Repository(repoPath)) { if (commit == null) { commit = localRepo.Head.Reference.TargetIdentifier; _logger.LogInformation($"Repo {localRepo.Info.WorkingDirectory} has no commit to clone at, assuming it's {commit}"); } _logger.LogDebug($"Attempting to checkout {commit} as commit in {localRepo.Info.WorkingDirectory}"); LibGit2SharpHelpers.SafeCheckout(localRepo, commit, checkoutOptions, _logger); } // LibGit2Sharp doesn't support a --git-dir equivalent yet (https://github.com/libgit2/libgit2sharp/issues/1467), so we do this manually if (gitDirectory != null) { Directory.Move(repoPath, gitDirectory); File.WriteAllText(repoPath.TrimEnd('\\', '/'), $"gitdir: {gitDirectory}"); } using (LibGit2Sharp.Repository localRepo = new LibGit2Sharp.Repository(targetDirectory)) { CheckoutSubmodules(localRepo, cloneOptions, gitDirectory, _logger); } } catch (Exception exc) { throw new Exception($"Something went wrong when cloning repo {repoUri} at {commit ?? "<default branch>"} into {targetDirectory}", exc); } } }
public ActionResult Clone(string id, RepositoryDetailModel model) { if (!User.IsInRole(Definitions.Roles.Administrator) && !UserConfiguration.Current.AllowUserRepositoryCreation) { return RedirectToAction("Unauthorized", "Home"); } if (model != null && !String.IsNullOrEmpty(model.Name)) { model.Name = Regex.Replace(model.Name, @"\s", ""); } if (String.IsNullOrEmpty(model.Name)) { ModelState.AddModelError("Name", Resources.Repository_Create_NameFailure); } else if (ModelState.IsValid) { if (RepositoryRepository.Create(ConvertRepositoryDetailModel(model))) { string targetRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, model.Name); if (!Directory.Exists(targetRepositoryPath)) { string sourceRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, id); LibGit2Sharp.CloneOptions options = new LibGit2Sharp.CloneOptions() { IsBare = true, Checkout = false }; LibGit2Sharp.Repository.Clone(sourceRepositoryPath, targetRepositoryPath, options); TempData["CloneSuccess"] = true; return RedirectToAction("Index"); } else { RepositoryRepository.Delete(model.Name); ModelState.AddModelError("", Resources.Repository_Create_DirectoryExists); } } else { ModelState.AddModelError("", Resources.Repository_Create_Failure); } } ViewBag.ID = id; PopulateEditData(); return View(model); }
private static void CheckoutSubmodules(LibGit2Sharp.Repository repo, LibGit2Sharp.CloneOptions submoduleCloneOptions, string gitDirParentPath, ILogger log) { foreach (LibGit2Sharp.Submodule sub in repo.Submodules) { log.LogDebug($"Updating submodule {sub.Name} at {sub.Path} for {repo.Info.WorkingDirectory}. GitDirParent: {gitDirParentPath}"); repo.Submodules.Update(sub.Name, new LibGit2Sharp.SubmoduleUpdateOptions { CredentialsProvider = submoduleCloneOptions.CredentialsProvider, Init = true }); string normalizedSubPath = sub.Path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); string subRepoPath = Path.Combine(repo.Info.WorkingDirectory, normalizedSubPath); string relativeGitDirPath = File.ReadAllText(Path.Combine(subRepoPath, ".git")).Substring(8); log.LogDebug($"Submodule {sub.Name} has .gitdir {relativeGitDirPath}"); string absoluteGitDirPath = Path.GetFullPath(Path.Combine(subRepoPath, relativeGitDirPath)); string relocatedGitDirPath = absoluteGitDirPath.Replace(repo.Info.Path.TrimEnd(new[] { '/', '\\' }), gitDirParentPath.TrimEnd(new[] { '/', '\\' })); string subRepoGitFilePath = Path.Combine(subRepoPath, ".git"); log.LogDebug($"Writing new .gitdir path {relocatedGitDirPath} to submodule at {subRepoPath}"); // File.WriteAllText gets access denied for some reason using (FileStream s = File.OpenWrite(subRepoGitFilePath)) using (StreamWriter w = new StreamWriter(s)) { w.Write($"gitdir: {relocatedGitDirPath}"); w.Flush(); s.SetLength(s.Position); } // The worktree is stored in the .gitdir/config file, so we have to change it // to get it to check out to the correct place. LibGit2Sharp.ConfigurationEntry <string> oldWorkTree = null; using (LibGit2Sharp.Repository subRepo = new LibGit2Sharp.Repository(subRepoPath)) { oldWorkTree = subRepo.Config.Get <string>("core.worktree"); if (oldWorkTree != null) { log.LogDebug($"{subRepoPath} old worktree is {oldWorkTree.Value}, setting to {subRepoPath}"); subRepo.Config.Set("core.worktree", subRepoPath); } else { log.LogDebug($"{subRepoPath} has default worktree, leaving unchanged"); } } using (LibGit2Sharp.Repository subRepo = new LibGit2Sharp.Repository(subRepoPath)) { log.LogDebug($"Resetting {sub.Name} to {sub.HeadCommitId.Sha}"); subRepo.Reset(LibGit2Sharp.ResetMode.Hard, subRepo.Commits.QueryBy(new LibGit2Sharp.CommitFilter { IncludeReachableFrom = subRepo.Refs }).Single(c => c.Sha == sub.HeadCommitId.Sha)); // Now we reset the worktree back so that when we can initialize a Repository // from it, instead of having to figure out which hash of the repo was most recently checked out. if (oldWorkTree != null) { log.LogDebug($"resetting {subRepoPath} worktree to {oldWorkTree.Value}"); subRepo.Config.Set("core.worktree", oldWorkTree.Value); } else { log.LogDebug($"leaving {subRepoPath} worktree as default"); } log.LogDebug($"Done checking out {subRepoPath}, checking submodules"); CheckoutSubmodules(subRepo, submoduleCloneOptions, absoluteGitDirPath, log); } if (File.Exists(subRepoGitFilePath)) { log.LogDebug($"Deleting {subRepoGitFilePath} to orphan submodule {sub.Name}"); File.Delete(subRepoGitFilePath); } else { log.LogDebug($"{sub.Name} doesn't have a .gitdir redirect at {subRepoGitFilePath}, skipping delete"); } } }
public ActionResult Clone(Guid id, RepositoryDetailModel model) { if (!RepositoryPermissionService.HasCreatePermission(User.Id())) { return(RedirectToAction("Unauthorized", "Home")); } if (model != null && !String.IsNullOrEmpty(model.Name)) { model.Name = Regex.Replace(model.Name, @"\s", ""); } if (model != null && String.IsNullOrEmpty(model.Name)) { ModelState.AddModelError("Name", Resources.Repository_Create_NameFailure); } else if (ModelState.IsValid) { var repo_model = ConvertRepositoryDetailModel(model); if (RepositoryRepository.Create(repo_model)) { string targetRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, model.Name); if (!Directory.Exists(targetRepositoryPath)) { var source_repo = RepositoryRepository.GetRepository(id); string sourceRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, source_repo.Name); LibGit2Sharp.CloneOptions options = new LibGit2Sharp.CloneOptions() { IsBare = true, Checkout = false }; LibGit2Sharp.Repository.Clone(sourceRepositoryPath, targetRepositoryPath, options); using (var repo = new LibGit2Sharp.Repository(targetRepositoryPath)) { if (repo.Network.Remotes.Any(r => r.Name == "origin")) { repo.Network.Remotes.Remove("origin"); } } TempData["CloneSuccess"] = true; return(RedirectToAction("Index")); } else { RepositoryRepository.Delete(model.Id); ModelState.AddModelError("", Resources.Repository_Create_DirectoryExists); } } else { ModelState.AddModelError("", Resources.Repository_Create_Failure); } } ViewBag.ID = id; PopulateCheckboxListData(ref model); return(View(model)); }
public ActionResult Clone(Guid id, RepositoryDetailModel model) { if (!RepositoryPermissionService.HasCreatePermission(User.Id())) { return RedirectToAction("Unauthorized", "Home"); } if (model != null && !String.IsNullOrEmpty(model.Name)) { model.Name = Regex.Replace(model.Name, @"\s", ""); } if (model != null && String.IsNullOrEmpty(model.Name)) { ModelState.AddModelError("Name", Resources.Repository_Create_NameFailure); } else if (ModelState.IsValid) { var repo_model = ConvertRepositoryDetailModel(model); if (RepositoryRepository.Create(repo_model)) { string targetRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, model.Name); if (!Directory.Exists(targetRepositoryPath)) { var source_repo = RepositoryRepository.GetRepository(id); string sourceRepositoryPath = Path.Combine(UserConfiguration.Current.Repositories, source_repo.Name); LibGit2Sharp.CloneOptions options = new LibGit2Sharp.CloneOptions() { IsBare = true, Checkout = false }; LibGit2Sharp.Repository.Clone(sourceRepositoryPath, targetRepositoryPath, options); using (var repo = new LibGit2Sharp.Repository(targetRepositoryPath)) { if (repo.Network.Remotes.Any(r => r.Name == "origin")) { repo.Network.Remotes.Remove("origin"); } } TempData["CloneSuccess"] = true; return RedirectToAction("Index"); } else { RepositoryRepository.Delete(model.Id); ModelState.AddModelError("", Resources.Repository_Create_DirectoryExists); } } else { ModelState.AddModelError("", Resources.Repository_Create_Failure); } } ViewBag.ID = id; PopulateCheckboxListData(ref model); return View(model); }
public static void PullFromRemote(string url, string path, Credentials credentials) { logger.InfoFormat("Start repository sync: {0}", path); if (!Directory.Exists(path)) { logger.Info("Repository does not exist"); logger.InfoFormat("Clone from {0}", url); var cloneOptions = new LibGit2Sharp.CloneOptions(); if (credentials != null) { cloneOptions.CredentialsProvider = (_url, _user, _cred) => new LibGit2Sharp.UsernamePasswordCredentials { Username = credentials.Username, Password = credentials.Password }; } LibGit2Sharp.Repository.Clone(url, path, cloneOptions); } else { logger.Info("Repository exists"); var fetchOptions = new LibGit2Sharp.FetchOptions(); if (credentials != null) { fetchOptions.CredentialsProvider = (_url, _user, _cred) => new LibGit2Sharp.UsernamePasswordCredentials { Username = credentials.Username, Password = credentials.Password }; } using (var repository = new LibGit2Sharp.Repository(path)) { foreach (var remote in repository.Network.Remotes) { IEnumerable <string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); logger.InfoFormat("Fetch repository from {0}: {1}", remote.Name, remote.Url); LibGit2Sharp.Commands.Fetch(repository, remote.Name, refSpecs, fetchOptions, ""); } var branchesUpdated = 0; var branchesCreated = 0; foreach (var branch in repository.Branches.Where(b => b.IsRemote)) { var localBranchName = branch.FriendlyName.Replace(branch.RemoteName + "/", ""); if (repository.Branches[localBranchName] == null) { logger.InfoFormat("Branch does not exist: {0}", localBranchName); logger.InfoFormat("Create branch from {0}: {1}", branch.FriendlyName, branch.Tip.Sha.Substring(0, 7)); repository.Branches.Update( repository.Branches.Add(localBranchName, branch.Tip), b => b.TrackedBranch = branch.CanonicalName); branchesCreated++; } var localBranch = repository.Branches[localBranchName]; if (localBranch.Tip.Sha != branch.Tip.Sha) { //check out branch and reset logger.InfoFormat("Branch {0} is behind: {1}", localBranchName, localBranch.Tip.Sha.Substring(0, 7)); logger.InfoFormat("Fast-forward to {0}", branch.Tip.Sha.Substring(0, 7)); LibGit2Sharp.Commands.Checkout(repository, localBranchName); repository.Reset(LibGit2Sharp.ResetMode.Hard, branch.Tip); branchesUpdated++; } else { logger.InfoFormat("Branch {0} is in sync: {1}", localBranch.FriendlyName, localBranch.Tip.Sha.Substring(0, 7)); } } logger.InfoFormat("Created branches: {0}", branchesCreated); logger.InfoFormat("Updated branches: {0}", branchesUpdated); logger.InfoFormat("Repository sync ready: {0}", path); } } }