public bool Commit(string message, string authorName, string emailAddress) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var changes = repo.RetrieveStatus(new StatusOptions { DetectRenamesInIndex = false, DetectRenamesInWorkDir = false }).Select(c => c.FilePath); if (!changes.Any()) { return(false); } repo.Stage(changes); if (string.IsNullOrWhiteSpace(authorName) || string.IsNullOrWhiteSpace(emailAddress)) { repo.Commit(message); } else { repo.Commit(message, new Signature(authorName, emailAddress, DateTimeOffset.UtcNow)); } return(true); } }
public void Clean() { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { repo.RemoveUntrackedFiles(); } }
private void Stage(string Path) { using (var repo = new LibGit2Sharp.Repository(RepositoryRootFolder)) { Commands.Stage(repo, Path); } }
public void AddFile(string path) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { repo.Stage(path); } }
internal static void Stage(FileInfo file) { using (var repository = new LibGit2Sharp.Repository(file.DirectoryName)) { repository.Stage(file.FullName); } }
/// <summary> /// This will ensure that the docs exist, this checks by the existence of the /Documentation/sitemap.js file /// </summary> public void EnsureGitHubDocs() { if (Directory.Exists(_rootFolderPath) == false) { Directory.CreateDirectory(_rootFolderPath); } if (Directory.Exists(Path.Combine(_rootFolderPath, ".git"))) { using (var repo = new LibGit2Sharp.Repository(_rootFolderPath)) { var options = new PullOptions { FetchOptions = new FetchOptions() }; var signature = new Signature("Our Umbraco", "*****@*****.**", new DateTimeOffset(DateTime.Now)); Commands.Pull(repo, signature, options); } } else { // clone if the repo doesn't yet exist LibGit2Sharp.Repository.Clone("https://github.com/umbraco/UmbracoDocs", _rootFolderPath); } BuildSitemap(_rootFolderPath); //YUCK, this is horrible but unfortunately the way that the doc indexes are setup are not with // a consistent integer id per document. I'm sure we can make that happen but I don't have time right now. ExamineManager.Instance.IndexProviderCollection["documentationIndexer"].RebuildIndex(); }
/// <summary> /// Main entry point. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { bool resetmode = args.Contains("reset"); // Find the project root string root = Path.GetFullPath(Path.Combine(LibGit2Sharp.Repository.Discover("."), "..")); // Lets find the repo Repository repo = new LibGit2Sharp.Repository(root); // Lets find all the project.json files in the src folder (don't care about versioning `tests`) IEnumerable <string> projectFiles = Directory.EnumerateFiles(Path.Combine(root, "src"), "*.csproj", SearchOption.AllDirectories); ResetProject(projectFiles); // Open them and convert them to source projects List <SourceProject> projects = projectFiles.Select(x => ProjectRootElement.Open(x, ProjectCollection.GlobalProjectCollection, true)) .Select(x => new SourceProject(x, repo.Info.WorkingDirectory)) .ToList(); if (!resetmode) { CaclulateProjectVersionNumber(projects, repo); UpdateVersionNumbers(projects); CreateBuildScript(projects, root); foreach (SourceProject p in projects) { Console.WriteLine($"{p.Name} {p.FinalVersionNumber}"); } } }
internal static void Revert(FileInfo file) { using (var repository = new LibGit2Sharp.Repository(file.DirectoryName)) { repository.CheckoutPaths(repository.Head.Name, new[] { file.FullName }, ForceCheckoutOptions); } }
private async Task ProxyCommits() { Logger.Info("Proxying commits..."); foreach (var branch in _config.Source.Branches) { await PullSrcRepo(branch); } await AsyncDirectory.Copy("srcRepo", "destRepo"); if (_config.Destination.Anonymize) { await AnonymizeDestRepo(); } using (var destRepo = new GitRepository("destRepo")) { destRepo.Network.Remotes.Add("proxy", _ghDest.CloneUrl); } foreach (var branch in _config.Source.Branches) { await PushDestRepo(branch); } }
private async Task PullSrcRepo(string branch) { Logger.Info($"Pulling branch {branch} from source repo..."); var options = new PullOptions { FetchOptions = new FetchOptions { CredentialsProvider = GitCredentials } }; await Task.Run(() => { using var repo = new GitRepository("srcRepo"); if (repo.Branches[branch] == null) { var remoteBranch = repo.Branches[$"origin/{branch}"]; var newBranch = repo.CreateBranch(branch, remoteBranch.Tip); repo.Branches.Update(newBranch, b => b.TrackedBranch = remoteBranch.CanonicalName); } Commands.Checkout(repo, repo.Branches[branch]); Commands.Pull(repo, _defaultSignature, options); }); }
public void FetchWithoutConflict(string remoteUrl, string branchName) { var tracer = _tracerFactory.GetTracer(); try { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var trackedBranchName = string.Format("{0}/{1}", _remoteAlias, branchName); var refSpec = string.Format("+refs/heads/{0}:refs/remotes/{1}", branchName, trackedBranchName); // Configure the remote var remote = repo.Network.Remotes.Add(_remoteAlias, remoteUrl, refSpec); // This will only retrieve the "master" repo.Network.Fetch(remote); // Optionally set up the branch tracking configuration var trackedBranch = repo.Branches[trackedBranchName]; if (trackedBranch == null) { throw new BranchNotFoundException(branchName, null); } var branch = repo.Branches[branchName] ?? repo.CreateBranch(branchName, trackedBranch.Tip); repo.Branches.Update(branch, b => b.TrackedBranch = trackedBranch.CanonicalName); //Update the raw ref to point the head of branchName to the latest fetched branch UpdateRawRef(string.Format("refs/heads/{0}", branchName), trackedBranchName); // Now checkout out our branch, which points to the right place Update(branchName); } } catch (LibGit2SharpException exception) { tracer.TraceWarning("LibGit2SharpRepository fetch failed with {0}", exception); // LibGit2Sharp doesn't support SSH yet. Use GitExeRepository // LibGit2Sharp only supports smart Http protocol if (exception.Message.Equals("Unsupported URL protocol") || exception.Message.Equals("Received unexpected content-type")) { tracer.TraceWarning("LibGit2SharpRepository fallback to git.exe"); _legacyGitExeRepository.FetchWithoutConflict(remoteUrl, branchName); } else { throw; } } finally { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { repo.Network.Remotes.Remove(_remoteAlias); } } }
public void OpenLocalRepoTest() { using (var repo = new LibGit2Sharp.Repository(@"c:\\projects2010\\markdownmonster")) { Assert.IsNotNull(repo); } }
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); }
public void UpdateRawRef(string toBeUpdatedRef, string toBeUpdatedToRef) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { repo.Refs.UpdateTarget(toBeUpdatedRef, toBeUpdatedToRef); } }
/// <summary> /// Get the git configuration /// </summary> /// <returns>A Config object.</returns> public Config GetConfig() { //Run at startup, this will create the global repository, only needs to be run once. Repository.Init(GlobalGitRepositoryLocation, true); //Run at startup, this will create the instance specific clone on the local machine, should be run on every service start. //Don't need to do this more than once the first time if (!Repository.IsValid(LocalGitRepositoryLocation)) { Repository.Clone(GlobalGitRepositoryLocation, LocalGitRepositoryLocation, new CloneOptions { IsBare = true }); } //In application code attempt to use the git repository using (var repository = new Repository(LocalGitRepositoryLocation)) { try { repository.Network.Fetch(repository.Network.Remotes[ConfigurationRemote]); } catch { } var refOriginMaster = repository.Refs[ConfigurationRemoteRef]; if (refOriginMaster == null) { return new Config(); } var sha = refOriginMaster.TargetIdentifier; var configFile = repository.Lookup<Commit>(sha)[GitConfigurationFile]; if (configFile == null || !(configFile.Target is Blob)) { return new Config(); } using (var fileStream = ((Blob)configFile.Target).GetContentStream()) using (var reader = new StreamReader(fileStream, Encoding.UTF8)) { var result = reader.ReadToEnd(); try { return new JavaScriptSerializer().Deserialize<Config>(result); } catch { return new Config(); } } } }
public override bool Revert(string path, ref string error) { try { using (var repo = new LibGit2Sharp.Repository(RepositoryRootFolder)) { if (Path.GetFullPath(new Uri(RepositoryRootFolder).LocalPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToUpperInvariant() == Path.GetFullPath(new Uri(path).LocalPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToUpperInvariant()) { //undo all changes repo.Reset(ResetMode.Hard); } else { //undo specific changes string committishOrBranchSpec = SourceControlBranch; CheckoutOptions checkoutOptions = new CheckoutOptions(); checkoutOptions.CheckoutModifiers = CheckoutModifiers.Force; checkoutOptions.CheckoutNotifyFlags = CheckoutNotifyFlags.Ignored; repo.CheckoutPaths(committishOrBranchSpec, new[] { path }, checkoutOptions); } } } catch (Exception e) { error = e.Message + Environment.NewLine + e.InnerException; return(false); } return(true); }
public void Fetch(string remoteName) { using var repository = new LibGit2Sharp.Repository(Module.WorkingDir); var options = new LibGit2Sharp.FetchOptions(); Commands.Fetch(repository, remoteName, Array.Empty <string>(), options, null); }
public void CheckoutMaster() { using var repository = new LibGit2Sharp.Repository(Module.WorkingDir); Commands.Checkout(repository, "master", new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force }); }
// GET api/values public HttpResponseMessage Get(string path) { using (var repo = new Repository(path)) { var files = repo .RetrieveStatus(new StatusOptions() { IncludeUnaltered = true }) .Where(s => s.State != FileStatus.Ignored && s.State != FileStatus.NewInWorkdir) .Select(s => s.FilePath) .ToList(); var diffs = files.Select(f => new { path = f, history = repo.Commits.QueryBy(f).Select(x => x.Commit).ToList() }) .ToList(); var patches = diffs.Select( d => new { d.path, history = d.history.Where(p => p.Parents.Any()) .SelectMany( c => repo.Diff.Compare<Patch>(c.Parents.First().Tree,c.Tree) .Where(p => p.Path == d.path) .Select(p => new { p.LinesAdded, p.LinesDeleted, c.Author.When }) .ToArray()) .ToArray() }).ToArray(); return Request.CreateResponse(HttpStatusCode.OK, patches); } }
RepositoryWriter( Repository r, string userName = null, string userEmail = null ) { if( (userEmail == null) != (userName== null ) ) throw new ArgumentException(); _repo = r; _userEmail = userEmail; _userName = userName; }
internal RepositoryInformation(Repository repo, string posixPath, string posixWorkingDirectoryPath, bool isBare) { this.repo = repo; Path = PosixPathHelper.ToNative(posixPath); IsBare = isBare; WorkingDirectory = PosixPathHelper.ToNative(posixWorkingDirectoryPath); }
public override IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { var repositoryLocation = Repository.Discover(context.InputFolder); if (repositoryLocation == null) throw new ArgumentException("No git repository found"); using (Repository repository = new Repository(repositoryLocation)) { var data = GetCommitInformation(repository); var lookup = data.ToLookup(x => x.Path.ToLower()); return inputs.Select(x => { string relativePath = GetRelativePath(Path.GetDirectoryName(Path.GetDirectoryName(repositoryLocation.ToLower())), x.Source.ToLower()); // yes we need to do it twice if (!lookup.Contains(relativePath)) return x; var commitsOfFile = lookup[relativePath] .GroupBy(y => y.Author) .ToDictionary(y => y.Key, y => y.OrderByDescending(z => z.AuthorDateTime).First()) .Select(y => y.Value) .ToArray(); return x.Clone(new[] { new KeyValuePair<string, object>(_metadataName, commitsOfFile) }); }).ToArray(); // Don't do it lazy or Commit is disposed. } }
public static Uri GetScmUri(Repository repo) { var repoUri = new UriBuilder(repo.Network.Remotes["origin"].Url); repoUri.Query = null; repoUri.Path = null; return repoUri.Uri; }
public virtual void Commit() { EnsureIsInState(TransactionState.Active); var canCommit = CanCommit(); if (!canCommit) { State = TransactionState.Failed; OnTransactionAborted(); throw new TransactionFailedException("The changes from the transaction could not be pushed back to the remote repository because changes were made there"); } try { using (var localRepository = new Repository(LocalPath)) { // push all branches with local changes and all tags var branchesToPush = GetBranchesToPush(localRepository).ToList(); var refSpecs = branchesToPush.ToRefSpecs().Union(localRepository.Tags.ToRefSpecs()); localRepository.Network.Push(localRepository.Network.Remotes[s_Origin], refSpecs); } State = TransactionState.Completed; OnTransactionCompleted(); } catch (NonFastForwardException ex) { State = TransactionState.Failed; OnTransactionAborted(); throw new TransactionFailedException("The changes from the transaction could not be pushed back to the remote repository because changes were made there", ex); } }
public static void NormalizeGitDirectory(string gitDirectory, Arguments arguments, string branch = null) { using (var repo = new Repository(gitDirectory)) { var remote = EnsureOnlyOneRemoteIsDefined(repo); AddMissingRefSpecs(repo, remote); Logger.WriteInfo(string.Format("Fetching from remote '{0}' using the following refspecs: {1}.", remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification)))); var fetchOptions = BuildFetchOptions(arguments.Username, arguments.Password); repo.Network.Fetch(remote, fetchOptions); CreateMissingLocalBranchesFromRemoteTrackingOnes(repo, remote.Name); if (!repo.Info.IsHeadDetached) { Logger.WriteInfo(string.Format("HEAD points at branch '{0}'.", repo.Refs.Head.TargetIdentifier)); return; } Logger.WriteInfo(string.Format("HEAD is detached and points at commit '{0}'.", repo.Refs.Head.TargetIdentifier)); if (branch != null) { Logger.WriteInfo(string.Format("Checking out local branch 'refs/heads/{0}'.", branch)); repo.Checkout("refs/heads/" + branch); } else { CreateFakeBranchPointingAtThePullRequestTip(repo); } } }
public static bool SplitRepositoryPath(string filePath, out string gitDirectory, out string fileName) { string currentDirectory = filePath; do { gitDirectory = Path.Combine(currentDirectory, ".git"); if (Directory.Exists(gitDirectory)) { string probeFileName = filePath.Substring(currentDirectory.Length + 1); using (Repository repo = new Repository(gitDirectory)) { var entry = repo.Index.FirstOrDefault(x => string.Equals(x.Path, probeFileName, StringComparison.OrdinalIgnoreCase)); fileName = entry != null ? entry.Path : probeFileName; return true; } } currentDirectory = Path.GetDirectoryName(currentDirectory); } while (currentDirectory != null); Log.WarnFormat("Can't find .git directory for {0}", filePath); gitDirectory = null; fileName = null; return false; }
/// <summary> /// Builds the file history from a repository path, file path and the reference to object SysVersionControlTmpItem /// </summary> /// <param name="repoPath">Repository main path</param> /// <param name="filePath">File to be pulling the commits</param> /// <param name="tmpItem">Ref to the SysVersionControlTmpItem object to be inserting to</param> /// <returns>A SysVersionControlTmpItem filled with the commits</returns> public static SysVersionControlTmpItem BuildFileHistory(string repoPath, string filePath, ref SysVersionControlTmpItem tmpItem) { FileInfo fileInfo = new FileInfo(filePath); using (var repo = new Repository(repoPath)) { var indexPath = fileInfo.FullName.Replace(repo.Info.WorkingDirectory, string.Empty); var commits = repo.Head.Commits.Where(c => c.Parents.Count() == 1 && c.Tree[indexPath] != null && (c.Parents.FirstOrDefault().Tree[indexPath] == null || c.Tree[indexPath].Target.Id != c.Parents.FirstOrDefault().Tree[indexPath].Target.Id)); foreach (Commit commit in commits) { tmpItem.User = commit.Author.ToString(); tmpItem.GTXShaShort = commit.Sha.Substring(0, 7); tmpItem.GTXSha = commit.Sha; tmpItem.Comment = commit.Message; tmpItem.ShortComment = commit.MessageShort; tmpItem.VCSDate = commit.Committer.When.Date; tmpItem.VCSTime = (int)commit.Committer.When.DateTime.TimeOfDay.TotalSeconds; tmpItem.Filename_ = FileGetVersion(repoPath, fileInfo.FullName, commit.Sha, Path.Combine(Path.GetTempPath(), string.Format("{0}_{1}", commit.Sha.Substring(0, 7), fileInfo.Name))); tmpItem.InternalFilename = fileInfo.FullName; tmpItem.ItemPath = indexPath; tmpItem.GTXFileRepoStatus = GetFileStatus(repoPath, fileInfo.FullName); tmpItem.insert(); } } return tmpItem; }
private static void Run(GitHubFlowArguments arguments, string workingDirectory) { var fallbackStrategy = new LocalBuild(); var buildServers = new IBuildServer[] {new TeamCity()}; var currentBuildServer = buildServers.FirstOrDefault(s => s.IsRunningInBuildAgent()) ?? fallbackStrategy; var gitDirectory = GitDirFinder.TreeWalkForGitDir(workingDirectory); if (string.IsNullOrEmpty(gitDirectory)) { if (currentBuildServer.IsRunningInBuildAgent()) //fail the build if we're on a TC build agent { // This exception might have to change when more build servers are added throw new Exception("Failed to find .git directory on agent. " + "Please make sure agent checkout mode is enabled for you VCS roots - " + "http://confluence.jetbrains.com/display/TCD8/VCS+Checkout+Mode"); } throw new Exception("Failed to find .git directory."); } Console.WriteLine("Git directory found at {0}", gitDirectory); var repositoryRoot = Directory.GetParent(gitDirectory).FullName; var gitHelper = new GitHelper(); var gitRepo = new Repository(gitDirectory); var lastTaggedReleaseFinder = new LastTaggedReleaseFinder(gitRepo, gitHelper); var nextSemverCalculator = new NextSemverCalculator(new NextVersionTxtFileFinder(repositoryRoot), lastTaggedReleaseFinder); var buildNumberCalculator = new BuildNumberCalculator(nextSemverCalculator, lastTaggedReleaseFinder, gitHelper, gitRepo, currentBuildServer); var nextBuildNumber = buildNumberCalculator.GetBuildNumber(); WriteResults(arguments, nextBuildNumber, currentBuildServer); }
public BranchWrapper(Repository repo, Branch branch) { this.repo = repo; this.branch = branch; IsRemote = branch.IsRemote; if (branch.TrackedBranch != null) { TrackedBranch = new BranchWrapper(repo, branch.TrackedBranch); } IsTracking = branch.IsTracking; TrackingDetails = (Func<object, Task<object>>)(async (j) => { return branch.TrackingDetails; }); IsCurrentRepositoryHead = (Func<object, Task<object>>)(async (j) => { return branch.IsCurrentRepositoryHead; }); Tip = async (j) => { return new CommitWrapper(branch.Tip); }; UpstreamBranchCanonicalName = (Func<object, Task<object>>)(async (j) => { return branch.UpstreamBranchCanonicalName; }); Remote = branch.Remote; CanonicalName = branch.CanonicalName; Commits = (Func<object, Task<object>>)(async (j) => { if (j != null) { Commit after = repo.Lookup<Commit>((string)j); Commit until = branch.Tip; Commit ancestor = repo.Commits.FindMergeBase(after, until) ?? after; return CommitsAfter(after, until, ancestor).Distinct().Select(c => new CommitWrapper(c)); } else { return branch.Commits.Select(c => new CommitWrapper(c)); } }); Name = branch.Name; }
internal ObjectDatabase(Repository repo) { this.repo = repo; handle = Proxy.git_repository_odb(repo.Handle); repo.RegisterForCleanup(handle); }
internal ContentChanges(Repository repo, Blob oldBlob, Blob newBlob, GitDiffOptions options) { Proxy.git_diff_blobs(repo.Handle, oldBlob != null ? oldBlob.Id : null, newBlob != null ? newBlob.Id : null, options, FileCallback, HunkCallback, LineCallback); }
public static void AddUpdateFile(string FileName, string RepoPath) { using (var repo = new Repository(RepoPath)) { repo.Index.Stage(FileName); } }
public void CreateEmptyRepo() { _repoPath = Environment.CurrentDirectory + "\\myRepo"; var directory = Directory.CreateDirectory(_repoPath); LibGit2Sharp.Repository.Init(_repoPath); _repo = new LibGit2Sharp.Repository(_repoPath); }
public void TestLibGit2_CreateLocalBranches() { using (var myRepository = new Repository(@"C:\dev1\Gsx.Monitor.Project")) { Trace.WriteLine(string.Join("\n", from b in myRepository.Branches select $"{b.FriendlyName}({b.IsRemote})")); } }
public override string GetCurrentBranchForSolution() { using (var repo = new LibGit2Sharp.Repository(RepositoryRootFolder)) { return(repo.Head.FriendlyName); } }
private void btnCommit_Click(object sender, RibbonControlEventArgs e) { //Get Active Project var pj = Globals.ThisAddIn.Application.ActiveProject; //Get Project Filename. var projectFile = pj.FullName; //Get Directory from File Name var directory = Path.GetDirectoryName(projectFile); //Create a new Git Repository Repository.Init(directory); //Open the git repository in a using context so its automatically disposed of. using (var repo = new Repository(directory)) { // Stage the file repo.Index.Stage(projectFile); // Create the committer's signature and commit var author = new Signature("Richard", "@ARM", DateTime.Now); var committer = author; // Commit to the repository var commit = repo.Commit("Initial commit", author, committer); } }
protected RepositoryBase(string path, string repoName, string userName, string password) { Repository = new Repository(path); RepositoryName = repoName; UserName = userName; Password = password; }
public override bool Execute() { using (var repository = new Repository(RepositoryRoot)) { string branchName = repository.Head.Name; // get the git commit associated with this build string sourceGetVersion = Environment.GetEnvironmentVariable("TF_BUILD_SOURCEGETVERSION"); if (!string.IsNullOrEmpty(sourceGetVersion)) { // TF_BUILD_SOURCEGETVERSION has the branch and commit encoded (LG:branch:commit) // Example: TF_BUILD_SOURCEGETVERSION = LG:refs/heads/master:e0bfee0d37677f4cb9bc28a0f5506f33b60c3712 int startIndex = sourceGetVersion.LastIndexOf('/') + 1; int endIndex = sourceGetVersion.LastIndexOf(':'); branchName = sourceGetVersion.Substring(startIndex, endIndex - startIndex); } Remote remote = repository.Network.Remotes.Add("gitpushremote", RemoteUri); Branch branch = repository.Branches[branchName]; if (branch == null) { // Create branch branch = repository.Branches.Add(branchName, repository.Head.Tip); } repository.Branches.Update( branch, b => b.Remote = remote.Name, b => b.UpstreamBranch = branchName); Action<string> pushAction = (string pushRefSpec) => { repository.Network.Push( repository.Network.Remotes["gitpushremote"], pushRefSpec, new PushOptions { CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) => new UsernamePasswordCredentials { Username = RemoteUsername, Password = RemotePassword }) }); Log.LogMessage("Pushed {0} to {1}", pushRefSpec, RemoteUri); }; // Force push current branch pushAction(string.Format("refs/heads/{0}", branchName)); // Push tags foreach (Tag tag in repository.Tags) { //pushAction(tag.CanonicalName); } } return true; }
public BranchInfoActor() { Receive<GetBranchInfo>(message => { Logger.WriteLine($"Starting Branch info {message.DirPath} -> {message.BranchName}"); using (var repository = new Repository(message.RepositoryPath)) { var branch = repository.Branches[message.BranchName]; var branchLastCommit = branch.Tip; var branchInfo = new BranchInfo { Name = branch.Name, CommitterDate = branchLastCommit.Committer.When, CommitterName = branchLastCommit.Committer.Name, CommitterEmail = branchLastCommit.Committer.Email, Message = branchLastCommit.Message, Sha = branchLastCommit.Sha, }; var repoAndBranchInfo = new RepoAndBranchInfo(message.DirPath, branchInfo); Context.ActorSelection(ActorSelectionRouting.BranchInfoAggregationActorPath) .Tell(new RepositoryAndBranchInfo(repoAndBranchInfo)); } }); }
//readonly Tree masterTree; //readonly Tree currentTree; public Stalker(String localRepo, String sourceFileName, String ignoreFileName, String localStalkBranch = null, String targetTag = null, String localMaster = "master") { repo = new Repository (localRepo); master = repo.Branches.Single (branch => branch.FriendlyName == localMaster); if (targetTag != null) { tag = repo.Tags.Single (t => t.FriendlyName == targetTag); } // if (localStalkBranch != null) head = repo.Branches.Single (branch => branch.FriendlyName == localStalkBranch); // else // head = repo.Head; // if (head != repo.Branches.Single (b => b.IsCurrentRepositoryHead)) { // repo.Checkout(head); // } // head = repo.Branches.Single(b => b.IsCurrentRepositoryHead); //var filter = new CommitFilter { Since = repo.Branches["master"], Until = repo.Branches["development"] }; //masterTree = repo.Lookup<Tree>(master.Tip.Sha); //currentTree = repo.Lookup<Tree>(head.Tip.Sha); try { sources = File.ReadAllLines (Path.Combine (localRepo, sourceFileName)); } catch { } finally { } try { ignore = File.ReadAllLines (Path.Combine (localRepo, ignoreFileName)); } catch { } finally { } }
private static string HashWithLibGit2Sharp(Stream file) { var repository = new Repository(Environment.CurrentDirectory); var temp = new FileStream(Path.GetTempFileName(),FileMode.Open); file.CopyTo(temp); return repository.ObjectDatabase.CreateBlob(temp.Name).Sha.ToString(); }
private void button2_Click(object sender, EventArgs e) { using (var repo = new Repository(@"C:\MergeRep\GitDashboard")) { TreeChanges changes = repo.Diff.Compare(repo.Head.Tip.Tree, repo.Branches["newb"].Tip.Tree); } }
public Task<List<ISourceItem>> FetchAllFiles(BuildConfig config) { string gitFolder = config.BuildFolder + "\\git"; //// temporary hack... //// git-pull does not work //if (Directory.Exists(gitFolder)) { // Directory.Delete(gitFolder, true); //} if (!Directory.Exists(gitFolder)) { Directory.CreateDirectory(gitFolder); Console.WriteLine("Cloning repository " + config.SourceUrl); CloneOptions clone = new CloneOptions(); clone.CredentialsProvider = CredentialsHandler; var rep = Repository.Clone(config.SourceUrl, gitFolder, clone); Console.WriteLine("Repository clone successful"); } else { Console.WriteLine("Fetching remote Repository"); var rep = new Repository(gitFolder); FetchOptions options = new FetchOptions(); options.CredentialsProvider = CredentialsHandler; Remote remote = rep.Network.Remotes["origin"]; //Commands.Fetch(rep,remote.Name,) //rep.Fetch(remote.Name, options); var master = rep.Branches["master"]; Commands.Pull(rep, new Signature("IISCI", "*****@*****.**", DateTime.Now), new PullOptions() { FetchOptions = options, MergeOptions = new MergeOptions() { MergeFileFavor = MergeFileFavor.Theirs, CommitOnSuccess = true } }); Console.WriteLine("Fetch successful"); } List<ISourceItem> files = new List<ISourceItem>(); EnumerateFiles( new DirectoryInfo(gitFolder), files, "" ); Parallel.ForEach(files, file => { var md5 = System.Security.Cryptography.MD5.Create(); ((GitSourceItem)file).Version = Convert.ToBase64String(md5.ComputeHash(File.ReadAllBytes(file.Url))); }); return Task.FromResult(files); }
private static DirectReference GetRemoteReference(Repository repository, string branchName, string repositoryUrl) { var targetBranchName = branchName.GetCanonicalBranchName(); var remoteReferences = repository.Network.ListReferences(repositoryUrl); return remoteReferences.FirstOrDefault(remoteRef => string.Equals(remoteRef.CanonicalName, targetBranchName)); }
static void Main(string[] args) { string ruta = @"C:\Users\developer\Documents\GitHub\libgit2sharp"; var repo = new Repository(ruta); //Listar(repo); int numCommits = 0; int programadores = 8; int años = 2014 - 2010; //desde 2010 Console.WriteLine("Numero de commits por branch:"); foreach (var rama in repo.Branches) { Console.WriteLine("Rama: " + rama.Name + " tiene " + rama.Commits.Count() + " commits"); numCommits += rama.Commits.Count(); } Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("\r\nRamas listadas " + repo.Branches.Count()); Console.WriteLine("Total commits: " + numCommits); float lineas = ((numCommits/programadores)/(años*365)); Console.WriteLine("Lineas media por dia: " + lineas); //ObtenerComits(repo); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.Write("\r\nFin"); Console.Read(); }
public Dictionary<string, Package> GetMods(string root) { var re = new Dictionary<string, Package>(); //Delete any old repo if (Directory.Exists("tmp")) { //some studped fraking(Battlestar Galactica) bug with perms SetDirPerms("tmp"); Directory.Delete("tmp", true); } //create tmp folder Directory.CreateDirectory("tmp"); //Clone repo int tmp folder var repoFile = Repository.Clone(root, "tmp\\repo\\"); var repo = new Repository(repoFile); for (int i = 97; i < 122; i++) { var f = Path.Combine(repo.Info.WorkingDirectory, ((char)i).ToString(), "index.dat"); foreach(var z in File.ReadAllText(f).Replace("\r\n","\n").Split('\n')) { if(!string.IsNullOrEmpty(z)) { if(!re.ContainsKey(z)) { re.Add(z, JsonConvert.DeserializeObject<Package>(File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, ((char)i).ToString(), z + ".pak")))); } } } } return re; }
public PersistentInfo( Repository r ) : this() { if( r == null ) RepositoryError = "No repository."; else { var branch = r.Head; if( branch.Tip == null ) RepositoryError = "Unitialized repository."; else { CommitSha = branch.Tip.Sha; var repositoryStatus = r.Index.RetrieveStatus(); IsDirty = repositoryStatus.Added.Any() || repositoryStatus.Missing.Any() || repositoryStatus.Modified.Any() || repositoryStatus.Removed.Any() || repositoryStatus.Staged.Any(); ReleasedTag = FindReleasedVersion( r, branch.Tip ); if( ReleasedTag.IsValid ) { BranchName = ReleasedTag.BranchName; } else { BranchName = branch.Name; } } } }
public void CheckoutRevision() { using var repository = new LibGit2Sharp.Repository(Module.WorkingDir); Commands.Checkout(repository, CommitHash, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force }); }
private void ToolStripbtnAdd_Click(object sender, EventArgs e) { // get the new entryname InputBoxValidation validation = delegate(string val) { if (val == "") { return("Value cannot be empty."); } if (new Regex(@"[a-zA-Z0-9-\\_]+/g").IsMatch(val)) { return(Strings.Error_valid_filename); } if (File.Exists(cfg["PassDirectory"] + "\\" + @val + ".gpg")) { return(Strings.Error_already_exists); } return(""); }; string value = ""; if (InputBox.Show(Strings.Input_new_name, Strings.Input_new_name_label, ref value, validation) == DialogResult.OK) { // parse path string tmpPath = cfg["PassDirectory"] + "\\" + @value + ".gpg";; Directory.CreateDirectory(Path.GetDirectoryName(tmpPath)); using (File.Create(tmpPath)) { } ResetDatagrid(); // set the selected item. foreach (DataGridViewRow row in dataPass.Rows) { if (row.Cells[1].Value.ToString().Equals(value)) { dataPass.CurrentCell = row.Cells[1]; row.Selected = true; dataPass.FirstDisplayedScrollingRowIndex = row.Index; break; } } // add to git using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"])) { // Stage the file repo.Stage(tmpPath); } // dispose timer thread and clear ui. KillTimer(); // Set the text detail to the correct state txtPassDetail.Text = ""; txtPassDetail.ReadOnly = false; txtPassDetail.BackColor = Color.White; txtPassDetail.Visible = true; btnMakeVisible.Visible = false; txtPassDetail.Focus(); } }
public bool Checkout(Api.Git.Repository repository, string branchName) { using (var repo = new LibGit2Sharp.Repository(repository.Path)) { var branch = Commands.Checkout(repo, branchName); return(branch.FriendlyName == branchName); } }
public Repository(string path) { Id = CreateId(); Path = path; Name = System.IO.Path.GetFileName(path); GitRepository = new LibGit2Sharp.Repository(path); InitialiseWorkbooks(); }
public static void Stage(FileInfo file) { using (var repository = new LibGit2Sharp.Repository(file.DirectoryName)) { repository.Stage(file.FullName); Log.Add($"Staged: {file.Name}"); } }
public void Push() { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var masterBranch = repo.Branches["master"]; repo.Network.Push(masterBranch); } }
public void CreateCommit(string commitMessage, string content = null) { using var repository = new LibGit2Sharp.Repository(_moduleTestHelper.Module.WorkingDir); _moduleTestHelper.CreateRepoFile("A.txt", content ?? commitMessage); repository.Index.Add("A.txt"); _commitHash = Commit(repository, commitMessage); }
public static void PullAll() { var settings = GetGitSettings(); var dirs = Directory.EnumerateDirectories(settings.RootDir, ".git", SearchOption.AllDirectories); foreach (var dir in dirs.Select(d => new DirectoryInfo(d).Parent.FullName)) { using (var repo = new LibGit2Sharp.Repository(dir, new RepositoryOptions())) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(Path.GetFileName(dir)); Console.ForegroundColor = color; PullOptions pullOptions = new PullOptions() { MergeOptions = new MergeOptions() { FastForwardStrategy = FastForwardStrategy.Default }, FetchOptions = new FetchOptions() { CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = settings.Username, Password = settings.Password }), OnTransferProgress = OnCloneProgress } }; Task.Run(() => { try { MergeResult mergeResult = Commands.Pull( repo, new LibGit2Sharp.Signature(settings.Username, settings.Username, DateTimeOffset.Now), pullOptions ); if (mergeResult.Commit != null) { Console.WriteLine(); Console.WriteLine(mergeResult.Status); Console.WriteLine(mergeResult.Commit.ToString()); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); Console.ForegroundColor = ConsoleColor.White; } }).Wait(); } } }
public void Update(string id) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { repo.Checkout(id, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force }); } }
public ChangeSet GetChangeSet(string id) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { LibGit2Sharp.Commit commit = repo.Lookup <LibGit2Sharp.Commit>(id); return(commit == null ? null : new ChangeSet(commit.Sha, commit.Author.Name, commit.Author.Email, commit.Message, commit.Author.When)); } }
public void InitTestRepo() { string repoPath = Path.Combine(Path.GetTempPath(), "getgitversiontest"); FileSystemHelper.DeleteDirectory(repoPath); Directory.CreateDirectory(repoPath); LibGit2Sharp.Repository.Init(repoPath); repo = new LibGit2Sharp.Repository(repoPath); }
public void ChangeBranch(RepositoryItem repository, string BranchName) { var repo = new LibGit2Sharp.Repository(repository.Path); var branches = repo.Branches.Where(b => b.Name == BranchName).ToList(); if (branches.Any()) { var localBranch = branches.FirstOrDefault(x => !x.IsRemote); if (localBranch != null) { repo.Checkout(localBranch, new CheckoutOptions(), new Signature(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.Now)); } else { throw new Exception("You must checkout manually the first time"); //COMMENTED THIS OUT AS IT CREATES DUPLICATE REMOTE BRANCHES, For instance R15_Release will duplicate as origin/R15_Release. //Current work around is to get them to check out the branch manually the first time around. //var remoteBranch = branches.FirstOrDefault(x => x.IsRemote); //if (remoteBranch != null) //{ // var newLocalBranch = repo.CreateBranch(BranchName, remoteBranch.Tip); // newLocalBranch = repo.Branches.Update(newLocalBranch, // b => // { // b.TrackedBranch = remoteBranch.CanonicalName; // }); // repo.Checkout(newLocalBranch, new CheckoutOptions(), new Signature(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.Now)); //} } } }