Ejemplo n.º 1
0
        } // End Function CloseRepository

        // Since NGit is a port from Java, it doesn’t implement IDisposable when accessing files.
        // To remove its lock on files, you can dispose of the Git object by doing the following:
        public virtual bool CloseRepository(NGit.Api.Git repository, bool resetAttributes)
        {
            // NGit.Api.Git repository = NGit.Api.Git.Open (@"C:\Git\NGit");

            // Handle disposing of NGit's locks
            repository.GetRepository().Close();
            repository.GetRepository().ObjectDatabase.Close();
            repository = null;

            if (resetAttributes)
            {
                string[] files = System.IO.Directory.GetFiles(@"C:\Git\NGit", "*", System.IO.SearchOption.AllDirectories);

                // You may also want to recursively remove any read-only file attributes set by NGit in the repository’s path
                // if you need to remove the repository later or you will receive permission exceptions when attempting to do so.
                // Remove the read-only attribute applied by NGit to some of its files
                // http://stackoverflow.com/questions/7399611/how-to-remove-a-single-attribute-e-g-readonly-from-a-file
                foreach (string file in files)
                {
                    System.IO.FileAttributes attributes = System.IO.File.GetAttributes(file);
                    if ((attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                    {
                        attributes = RemoveAttribute(attributes, System.IO.FileAttributes.ReadOnly);
                        // file.Attributes = System.IO.FileAttributes.Normal;
                        System.IO.File.SetAttributes(file, attributes);
                    } // End if ((attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                }     // Next file
            }         // End if (resetAttributes)

            return(true);
        } // End Function CloseRepository
Ejemplo n.º 2
0
        } // End Function GetRemoteBranchId

        // http://stackoverflow.com/questions/3407575/retrieving-oldest-commit-with-jgit
        public virtual System.DateTime GetLastCommitDate(string path)
        {
            System.DateTime retVal = default(System.DateTime);

            NGit.Revwalk.RevCommit c          = null;
            NGit.Api.Git           repository = NGit.Api.Git.Open(path);


            try
            {
                NGit.Revwalk.RevWalk rw = new NGit.Revwalk.RevWalk(repository.GetRepository());

                NGit.AnyObjectId headid = repository.GetRepository().Resolve(NGit.Constants.HEAD);
                c = rw.ParseCommit(headid);

                // repository.GetRepository().
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }

            // Get author
            NGit.PersonIdent authorIdent = c.GetAuthorIdent();
            System.DateTime  authorDate  = authorIdent.GetWhen();

            retVal = authorDate.ToUniversalTime();

            CloseRepository(repository);

            return(retVal);
        }
Ejemplo n.º 3
0
        } // End Sub Clone

        public virtual string GetCurrentBranch(string path)
        {
            // Wrong result
            // NGit.Storage.File.FileRepository dir = new NGit.Storage.File.FileRepository (path);
            // string branch = dir.GetBranch ();
            // return branch;

            NGit.Api.Git repository = NGit.Api.Git.Open(path);

#if false
            System.Collections.Generic.IList <NGit.Ref> refsR = repository.BranchList().SetListMode(NGit.Api.ListBranchCommand.ListMode.ALL).Call();

            foreach (NGit.Ref refa in refsR)
            {
                //System.out.println("Branch: " + refa + " " + refa.GetName() + " " + ref.GetObjectId().Name);
                System.Console.WriteLine("Branch: {0} \nGetname: {1} \n Name: {2}"
                                         , refa, refa.GetName(), refa.GetObjectId().Name);
            }             // Next refa
#endif
            string branchName = null;
            string head       = repository.GetRepository().GetFullBranch();

            if (head.StartsWith("refs/heads/"))
            {
                // Print branch name with "refs/heads/" stripped.
                branchName = repository.GetRepository().GetBranch();
                // System.Console.WriteLine ("Current branch is \"{0}\".", branchName);
            } // End if (head.StartsWith ("refs/heads/"))

            CloseRepository(repository);

            return(branchName);
        } // End Function GetCurrentBranch
Ejemplo n.º 4
0
        // https://stackoverflow.com/questions/45793800/jgit-read-the-content-of-a-file-at-a-commit-in-a-branch
        private string GetFileContent(string repositoryPath, string path, NGit.Revwalk.RevCommit commit)
        {
            NGit.Api.Git repository = NGit.Api.Git.Open(repositoryPath);

            NGit.Treewalk.TreeWalk treeWalk = NGit.Treewalk.TreeWalk.ForPath(
                repository.GetRepository(), path, commit.Tree);

            NGit.ObjectId blobId = treeWalk.GetObjectId(0);

            NGit.ObjectReader objectReader = repository.GetRepository().NewObjectReader();
            NGit.ObjectLoader objectLoader = objectReader.Open(blobId);

            byte[] bytes = objectLoader.GetBytes();
            return(System.Text.Encoding.UTF8.GetString(bytes));
        }
Ejemplo n.º 5
0
        } // End Sub Init

        public virtual void Init(string path, string url, bool bare)
        {
            // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/InitRepository.java
            // Sharpen.FilePath pth = new Sharpen.FilePath ("path");
            NGit.Api.Git repository = NGit.Api.Git.Init()
                                      .SetDirectory(path)
                                      .SetBare(bare)
                                      .Call();

            if (string.IsNullOrWhiteSpace(url))
            {
                return;
            }



            // NGit.Storage.File.FileRepositoryBuilder frb = new NGit.Storage.File.FileRepositoryBuilder();

            // http://stackoverflow.com/questions/13667988/how-to-use-ls-remote-in-ngit
            // after init, you can call the below line to open
            // Git git = Git.Open(new FilePath(path));


            // git remote origin
            NGit.StoredConfig config = repository.GetRepository().GetConfig();
            // url: @"http://*****:*****@github.com/user/repo1.git"
            config.SetString("remote", "origin", "url", url);

            config.SetBoolean("core", null, "symlinks", false);
            config.SetBoolean("core", null, "ignorecase", true);

            config.Save();

            CloseRepository(repository);
        } // End Sub Init
Ejemplo n.º 6
0
        RevCommit[] GetBlameForFile(string revision, string filePath)
        {
            RevCommit[] blame;
            string      path = PROJECT_ROOT + filePath;
            string      key  = path + revision;

            blames.TryGetValue(key, out blame);

            if (blame == null)
            {
                var git    = new NGit.Api.Git(repo);
                var commit = git.GetRepository().Resolve(revision);
                var result = git.Blame().SetFilePath(filePath).SetStartCommit(commit).Call();
                if (result == null)
                {
                    return(null);
                }

                blame = new RevCommit [result.GetResultContents().Size()];
                for (int i = 0; i < result.GetResultContents().Size(); i++)
                {
                    blame [i] = result.GetSourceCommit(i);
                }
                blames.Add(key, blame);
            }

            return(blame);
        }
Ejemplo n.º 7
0
        // http://stackoverflow.com/questions/3407575/retrieving-oldest-commit-with-jgit
        public virtual void GetOldestCommit(string path)
        {
            NGit.Revwalk.RevCommit c          = null;
            NGit.Api.Git           repository = NGit.Api.Git.Open(path);


            try
            {
                NGit.Revwalk.RevWalk rw = new NGit.Revwalk.RevWalk(repository.GetRepository());

                NGit.AnyObjectId       headid = repository.GetRepository().Resolve(NGit.Constants.HEAD);
                NGit.Revwalk.RevCommit root   = rw.ParseCommit(headid);

                string msg1 = root.GetFullMessage();


                rw.Sort(NGit.Revwalk.RevSort.REVERSE);

                rw.MarkStart(root);
                c = rw.Next();
                // repository.GetRepository().
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }

            string msg2 = c.GetFullMessage();

            // Get author
            NGit.PersonIdent    authorIdent    = c.GetAuthorIdent();
            System.DateTime     authorDate     = authorIdent.GetWhen();
            System.TimeZoneInfo authorTimeZone = authorIdent.GetTimeZone();

            NGit.PersonIdent committerIdent = c.GetCommitterIdent();
            // http://stackoverflow.com/questions/12608610/how-do-you-get-the-author-date-and-commit-date-from-a-jgit-revcommit

            System.Console.WriteLine(authorIdent);
            System.Console.WriteLine(authorDate);
            System.Console.WriteLine(authorTimeZone);
            System.Console.WriteLine(committerIdent);

            CloseRepository(repository);
        }
        private RevWalk CreateRevWalker()
        {
            var repository = _git.GetRepository();

            try
            {
                var revWalk = new RevWalk(repository);

                foreach (var reference in repository.GetAllRefs())
                {
                    revWalk.MarkStart(revWalk.ParseCommit(reference.Value.GetObjectId()));
                }
                return(revWalk);
            }
            finally
            {
                repository.Close();
            }
        }
Ejemplo n.º 9
0
        public virtual bool IsBare(string path)
        {
            bool retVal = false;

            NGit.Api.Git repository = NGit.Api.Git.Open(path);

            retVal = repository.GetRepository().IsBare;

            CloseRepository(repository);

            return(retVal);
        }
Ejemplo n.º 10
0
        } // End Function IsRepository

        public virtual string GetRepoPath(string path)
        {
            string retVal = null;

            NGit.Api.Git repository = NGit.Api.Git.Open(path);

            retVal = repository.GetRepository().Directory.GetPath();
            // string base = repository.GetRepository ().Directory.GetParent ();
            // System.Console.WriteLine (base);

            CloseRepository(repository);

            return(retVal);
        }
Ejemplo n.º 11
0
        } // End Function RemoveAttribute

        // https://code.google.com/p/egit/wiki/JGitTutorialRepository
        // http://www.codeaffine.com/2014/09/22/access-git-repository-with-jgit/
        // Git is lazy. An empty, just initialized repository does not have an object database
        // Therefore the test will return false for an empty repository even though it is a perfectly valid repository.
        // What has proven a better approach so far is to test if the HEAD reference exists:
        // Even an empty repository has a HEAD and getRef() returns only null if there is actually no repository.
        public virtual bool IsRepository(string path)
        {
            // Git git = Git.open( new F‌ile( "/path/to/repo/.git" ) );

            // The method expects a File parameter that denotes the directory in which the repository is located.
            // The directory can either point to the work directory or the git directory.
            // Again, I recommend to use the git directory here.

            try
            {
                NGit.Api.Git repository = NGit.Api.Git.Open(path);
                bool         b          = repository.GetRepository().ObjectDatabase.Exists();
                if (repository.GetRepository().GetRef("HEAD") != null)
                {
                    b = true;
                }

                // string name = repository.GetRepository().GetRef("HEAD").GetName();
                // System.Console.WriteLine(name);

                CloseRepository(repository);

                return(b);
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);

                if (ex is System.TypeInitializationException)
                {
                    throw;
                }
            }

            return(false);
        } // End Function IsRepository
Ejemplo n.º 12
0
        } // End Sub ListBranches

        // https://stackoverflow.com/questions/40590039/how-to-get-the-file-list-for-a-commit-with-jgit
        // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/GetRevCommitFromObjectId.java
        public virtual void ListFilesIncmt(string path, NGit.Revwalk.RevCommit commit)
        {
            NGit.Api.Git  repository = NGit.Api.Git.Open(path);
            NGit.ObjectId treeId     = commit.Tree.Id;

            NGit.Treewalk.TreeWalk treeWalk = new NGit.Treewalk.TreeWalk(repository.GetRepository());

            treeWalk.Reset(treeId);

            while (treeWalk.Next())
            {
                string filePath = treeWalk.PathString;
                System.Console.WriteLine(filePath);
            }

            NGit.Ref      @ref = repository.GetRepository().GetRef("refs/heads/master");
            NGit.ObjectId head = @ref.GetObjectId();
            using (NGit.Revwalk.RevWalk walk = new NGit.Revwalk.RevWalk(repository.GetRepository()))
            {
                NGit.Revwalk.RevCommit headCommit = walk.ParseCommit(head);
            }

            NGit.ObjectId commitIdFromHash = repository.GetRepository().Resolve("revstr");
        }
Ejemplo n.º 13
0
        public string ReadCommit(string commitId, string fileName)
        {
            var repo = m_git.GetRepository();
            var id   = ObjectId.FromString(commitId);

            RevCommit commit = null;

            try
            {
                commit = ParseCommit(repo, id);
                if (commit == null)
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                return(null);
            }
            //var commits = m_git.Log().AddRange(id, id).Call();
            //var commit = commits.SingleOrDefault();
            //if (commit == null)
            //    return null;

            TreeWalk walk = new TreeWalk(repo);

            //RevWalk r = new RevWalk(m_git.GetRepository());
            //var tree = r.ParseTree(commit.Tree.Id);
            //r.LookupTree(
            //walk.AddTree(new FileTreeIterator(repo));

            //var tree = ParseTree(repo, commit.Tree.Id);
            walk.AddTree(commit.Tree);
            var filter = GetGitFriendlyName(fileName);

            walk.Filter = PathFilterGroup.CreateFromStrings(new string[] { filter });
            //walk.EnterSubtree();
            while (walk.Next())
            {
                var path = walk.PathString;
                if (walk.IsSubtree)
                {
                    walk.EnterSubtree();
                    continue;
                }
                if (path == filter)
                {
                    var          cur = walk.GetObjectId(0);
                    ObjectLoader ol  = repo.Open(cur);

                    //    //Console.WriteLine(string.Format("Path: {0}{1}", walk.PathString, walk.IsSubtree ? "/" : ""));
                    //    //var loader = reader.Open(commit.Tree.Id);
                    var text = "";
                    using (var stream = ol.OpenStream())
                        using (var sr = new System.IO.StreamReader(stream))
                        {
                            text = sr.ReadToEnd();
                        }
                    return(text);
                }
            }
            //walk.Reset();
            //reader.Open();
            return("");
        }
		RevCommit[] GetBlameForFile (string revision, string filePath)
		{
			RevCommit[] blame = null;
			string path = PROJECT_ROOT + filePath;
			string key = path + revision;
			blames.TryGetValue(key, out blame);
			
			if (blame == null)
			{
				var git = new NGit.Api.Git (repo);
				var commit = git.GetRepository ().Resolve (revision);
				var result = git.Blame ().SetFilePath (filePath).SetStartCommit (commit).Call ();
				if (result == null)
					return null;

				blame = new RevCommit [result.GetResultContents ().Size ()];
				for (int i = 0; i < result.GetResultContents ().Size (); i ++)
					blame [i] = result.GetSourceCommit (i);
				blames.Add(key, blame);
			}
			
			return blame;
		}
Ejemplo n.º 15
0
        private void SetupOperatorGitRepository()
        {
            const string NewtonSoftDllFilename = "Newtonsoft.Json.dll";

            if (File.Exists(NewtonSoftDllFilename))
            {
                throw new ShutDownException("Please remove " + NewtonSoftDllFilename + " from Tooll's directory because it will break compilation of Operators.",
                                            "Incorrect Settings");
            }

            var          operatorRepository       = new OperatorGitRepository(MetaManager.OPERATOR_PATH);
            const string operatorRepositoryUrl    = "Git.OperatorRepositoryURL";
            const string operatorRepositoryBranch = "Git.OperatorRepositoryBranch";

            if (ProjectSettings.Contains(operatorRepositoryUrl))
            {
                if (!ProjectSettings.Contains("Git.OperatorRepositoryBranch"))
                {
                    // https://streber.framefield.com/1636#5__operatorrepositoryremoteurl_definiert_aber_gitbranch_undefiniert_oder_fehlerhaft
                    throw new ShutDownException("Your project settings misses a definition for GitBranch.\n\nPlease fix this before restarting Tooll.",
                                                "Incorrect Settings");
                }

                var repositoryUrl = ProjectSettings[operatorRepositoryUrl] as string;
                var branchToUse   = ProjectSettings[operatorRepositoryBranch] as string;
                OperatorRepository            = operatorRepository;
                OperatorRepository.RemotePath = repositoryUrl;
                if (!Directory.Exists(MetaManager.OPERATOR_PATH))
                {
                    ShutdownMode = ShutdownMode.OnExplicitShutdown;

                    // https://streber.framefield.com/1636#1__operatorrepositoryremoteurl_definiert_aber_operators_fehlt
                    // fetch operators from url
                    var progressDialog = new CloneRepositoryProgressDialog(OperatorRepository)
                    {
                        LocalPath  = OperatorRepository.LocalPath,
                        RemotePath = OperatorRepository.RemotePath
                    };
                    progressDialog.ShowDialog();

                    ShutdownMode = ShutdownMode.OnMainWindowClose;
                }
                else if (!operatorRepository.IsValid)
                {
                    // https://streber.framefield.com/1636#2__operatorrepositoryremoteurl_definiert_aber_operators__git_fehlt
                    throw new ShutDownException(String.Format("git-repository is set to '{0}' in project settings, but 'Operators/.git' is missing or broken.\n\nPlease fix this or remove the Operators directory. Tooll will then fetch the Operators from the server.", repositoryUrl),
                                                "Missing Operator");
                }

                if (operatorRepository.LocalRepo.GetBranch() != branchToUse)
                {
                    // https://streber.framefield.com/1636#4__operatorrepositoryremoteurl_existiert_aber_operators__git__gt_branch____projectsettings_gitbranch
                    throw new ShutDownException(String.Format("Error: Your 'Operators/.git' branch '{0}' doesn't match the project settings '{1}'.\n\nPlease fix this before restarting Tooll.", operatorRepository.LocalRepo.GetBranch(), branchToUse),
                                                "Incorrect Settings");
                }

                var developerGit = new NGit.Api.Git(new FileRepository("./.git"));
                if (developerGit.GetRepository().GetAllRefs().Any())
                {
                    // valid developer git repository available, so check if branch of developer git repos matches operators repos branch
                    var developerGitBranch = developerGit.GetRepository().GetBranch();
                    if (developerGitBranch != branchToUse)
                    {
                        throw new ShutDownException(String.Format("Error: You starting Tooll as developer but your 'Operators/.git' branch '{0}' doesn't match the Tooll/.git branch '{1}'.\n\nPlease fix this before restarting Tooll.", branchToUse, developerGitBranch),
                                                    "Incorrect Settings");
                    }
                }

                OperatorRepository.Branch = branchToUse;
            }
            else
            {
                if (!Directory.Exists(MetaManager.OPERATOR_PATH) || !Directory.GetFiles(MetaManager.OPERATOR_PATH, "*.mop").Any())
                {
                    // https://streber.framefield.com/1636#6__operatorsrepositoryremoteurl_nicht_definiert_aber_operators__existiert_nicht
                    throw new ShutDownException("Your Operator directory is missing or empty.\n\nYou can define Git.OperatorsRepositoryURL and Git.OperatorRepositoryBranch in your projects settings to fetch a fresh copy.",
                                                "Incorrect Settings");
                }

                if (operatorRepository.IsValid)
                {
                    // https://streber.framefield.com/1636#3__operatorrepositoryremoteurl_nicht_definiert_aber_operators__git_existiert
                    throw new ShutDownException("Although you didn't specify a git repository in your project settings, the directory 'Operators/.git' exists.\n\nPlease fix this.",
                                                "Incorrect Settings");
                }
            }
        }