public virtual void TestUsingHiddenDeltaBaseFails()
        {
            byte[] delta = new byte[] { unchecked ((int)(0x1)), unchecked ((int)(0x1)), unchecked (
                                            (int)(0x1)), (byte)('c') };
            TestRepository <Repository> s = new TestRepository <Repository>(src);
            RevCommit N = s.Commit().Parent(B).Add("q", s.Blob(BinaryDelta.Apply(dst.Open(b).
                                                                                 GetCachedBytes(), delta))).Create();

            TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024);
            PackHeader(pack, 3);
            Copy(pack, src.Open(N));
            Copy(pack, src.Open(s.ParseBody(N).Tree));
            pack.Write((Constants.OBJ_REF_DELTA) << 4 | 4);
            b.CopyRawTo(pack);
            Deflate(pack, delta);
            Digest(pack);
            TemporaryBuffer.Heap inBuf     = new TemporaryBuffer.Heap(1024);
            PacketLineOut        inPckLine = new PacketLineOut(inBuf);

            inPckLine.WriteString(ObjectId.ZeroId.Name + ' ' + N.Name + ' ' + "refs/heads/s"
                                  + '\0' + BasePackPushConnection.CAPABILITY_REPORT_STATUS);
            inPckLine.End();
            pack.WriteTo(inBuf, PM);
            TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024);
            ReceivePack          rp     = new ReceivePack(dst);

            rp.SetCheckReceivedObjects(true);
            rp.SetCheckReferencedObjectsAreReachable(true);
            rp.SetRefFilter(new ReceivePackRefFilterTest.HidePrivateFilter());
            try
            {
                Receive(rp, inBuf, outBuf);
                NUnit.Framework.Assert.Fail("Expected UnpackException");
            }
            catch (UnpackException failed)
            {
                Exception err = failed.InnerException;
                NUnit.Framework.Assert.IsTrue(err is MissingObjectException);
                MissingObjectException moe = (MissingObjectException)err;
                NUnit.Framework.Assert.AreEqual(b, moe.GetObjectId());
            }
            PacketLineIn r      = AsPacketLineIn(outBuf);
            string       master = r.ReadString();
            int          nul    = master.IndexOf('\0');

            NUnit.Framework.Assert.IsTrue(nul > 0, "has capability list");
            NUnit.Framework.Assert.AreEqual(B.Name + ' ' + R_MASTER, Sharpen.Runtime.Substring
                                                (master, 0, nul));
            NUnit.Framework.Assert.AreSame(PacketLineIn.END, r.ReadString());
            NUnit.Framework.Assert.AreEqual("unpack error Missing blob " + b.Name, r.ReadString
                                                ());
            NUnit.Framework.Assert.AreEqual("ng refs/heads/s n/a (unpacker error)", r.ReadString
                                                ());
            NUnit.Framework.Assert.AreSame(PacketLineIn.END, r.ReadString());
        }
Example #2
0
        public void Open()
        {
            CreateRequestsInRepository(new[] { new DateTime(2014, 1, 1) }, new[] { 10 });
            Repository.Close();
            Context.ClearReceivedCalls();

            Repository.Open(DatabaseFile);
            Context.Received(1).UpdateRecentAccountInformation(Repository.FilePath);
            AssertRepositoryEqualsFileContent(DatabaseFile);
            Assert.That(Repository.FilePath, Is.EqualTo(DatabaseFile));
        }
Example #3
0
        internal static Repository Get(string key)
        {
            var repo = Repositories.GetOrAdd(key, s =>
            {
                var so       = new GridStructure();
                var instance = new Repository();
                instance.Open <GeoGrillas>(Config.Qtree.QtreeDirectory, ref so);
                return(instance);
            });

            return(repo);
        }
Example #4
0
        /// <summary>
        /// Updates the file in the working tree with content and mode from an entry
        /// in the index.
        /// </summary>
        /// <remarks>
        /// Updates the file in the working tree with content and mode from an entry
        /// in the index. The new content is first written to a new temporary file in
        /// the same directory as the real file. Then that new file is renamed to the
        /// final filename.
        /// TODO: this method works directly on File IO, we may need another
        /// abstraction (like WorkingTreeIterator). This way we could tell e.g.
        /// Eclipse that Files in the workspace got changed
        /// </remarks>
        /// <param name="repo"></param>
        /// <param name="f">
        /// the file to be modified. The parent directory for this file
        /// has to exist already
        /// </param>
        /// <param name="entry">the entry containing new mode and content</param>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public static void CheckoutEntry(Repository repo, FilePath f, DirCacheEntry entry
                                         )
        {
            ObjectLoader     ol        = repo.Open(entry.GetObjectId());
            FilePath         parentDir = f.GetParentFile();
            FilePath         tmpFile   = FilePath.CreateTempFile("._" + f.GetName(), null, parentDir);
            FileOutputStream channel   = new FileOutputStream(tmpFile);

            try
            {
                ol.CopyTo(channel);
            }
            finally
            {
                channel.Close();
            }
            FS fs = repo.FileSystem;
            WorkingTreeOptions opt = repo.GetConfig().Get(WorkingTreeOptions.KEY);

            if (opt.IsFileMode() && fs.SupportsExecute())
            {
                if (FileMode.EXECUTABLE_FILE.Equals(entry.RawMode))
                {
                    if (!fs.CanExecute(tmpFile))
                    {
                        fs.SetExecute(tmpFile, true);
                    }
                }
                else
                {
                    if (fs.CanExecute(tmpFile))
                    {
                        fs.SetExecute(tmpFile, false);
                    }
                }
            }
            if (!tmpFile.RenameTo(f))
            {
                // tried to rename which failed. Let' delete the target file and try
                // again
                FileUtils.Delete(f);
                if (!tmpFile.RenameTo(f))
                {
                    throw new IOException(MessageFormat.Format(JGitText.Get().couldNotWriteFile, tmpFile
                                                               .GetPath(), f.GetPath()));
                }
            }
            entry.LastModified = f.LastModified();
            entry.SetLength((int)ol.GetSize());
        }
Example #5
0
        private static Repository InitializeRepository(DependencyArguments dependencyArguments, string commandLineArguments)
        {
            Repository repository = new Repository(dependencyArguments.depDb);

            try
            {
                repository.Open();

                // check if this is a valid repository database
                if (repository.IsValidRepository() == false)
                {
                    repository.CreateRepository();
                }

                if (dependencyArguments.clearDatabase)
                {
                    repository.DeleteExistingRepository();
                }
                else
                {
                    repository.LoadExisingRepository();
                }

                if (commandLineArguments.Length > 512)
                {
                    repository.InitialiseRepository(commandLineArguments.Substring(0, 512));
                }
                else
                {
                    repository.InitialiseRepository(commandLineArguments);
                }
                repository.DatabaseNameOnlyCompare = dependencyArguments.matchDBOnly;

                foreach (string dbPrefix in dependencyArguments.dbPrefix)
                {
                    repository.DatabasePrefixExclusions.Add(dbPrefix);
                }

                return(repository);
            }
            catch (Exception ex)
            {
                log.Error(string.Format("Unable to connect to Dependency Database: {0}", dependencyArguments.depDb));
                log.Error(string.Format("Message: {0}", ex.Message));
                return(null);
            }
        }
 public static ObjectLoader  open(this Repository repository, string sha1)
 {
     try
     {
         if (repository.notNull())
         {
             var objectId = sha1.objectId();
             if (objectId.valid())
             {
                 return(repository.Open(objectId));
             }
         }
     }
     catch (Exception ex)
     {
         ex.log("[API_NGit][open]");
     }
     return(null);
 }
Example #7
0
        public static DisgaeaProject GetProject(string path)
        {
            Repository repository;

            if (File.Exists(path))
            {
                repository = Repository.Open(path);
            }
            else
            {
                repository = Repository.Create(path);

                repository.InsertConfig("OUTPUT_REPLACEMENT", "1");
                repository.InsertConfig("OUTPUT_ENCODING", "UTF-8");

                repository.InsertReplacement("á", "a");
                repository.InsertReplacement("é", "e");
                repository.InsertReplacement("í", "i");
                repository.InsertReplacement("ó", "o");
                repository.InsertReplacement("ú", "u");
                repository.InsertReplacement("ü", "u");

                repository.InsertReplacement("Á", "A");
                repository.InsertReplacement("É", "E");
                repository.InsertReplacement("Í", "I");
                repository.InsertReplacement("Ó", "O");
                repository.InsertReplacement("Ú", "U");
                repository.InsertReplacement("Ü", "U");

                repository.InsertReplacement("ñ", "n");
                repository.InsertReplacement("Ñ", "N");

                repository.InsertReplacement("¡", "!");
                repository.InsertReplacement("¿", "?");
            }

            var result = new DisgaeaProject(repository)
            {
                Path = path
            };

            return(result);
        }
Example #8
0
        public QtreeInstanceManager(DAOFactory factory)
        {
            _factory = factory;

            var coches = _factory.CocheDAO.GetList(new[] { -1 }, new[] { -1 });

            foreach (var c in coches)
            {
                var key = c.Dispositivo.GetQtreeType() + "|" + c.Dispositivo.GetQtreeFile();

                var repo = repositories.GetOrAdd(key, s =>
                {
                    var so       = new GridStructure();
                    var instance = new Repository();
                    instance.Open <GeoGrillas>(Config.Qtree.QtreeDirectory, ref so);
                    return(instance);
                });

                speedSpecs.TryAdd(c.Id, DispositivoSpeedSpec.Build(c.Dispositivo, repo));
            }
        }
        public static string GetFileContent(this RevCommit commit, string path, Repository repository)
        {
            var treeWalk = new TreeWalk(repository) {Recursive = true, Filter = PathFilter.Create(path)};
            treeWalk.AddTree(commit.Tree);

            if (!treeWalk.Next())
            {
                return string.Empty;
            }

            var objectId = treeWalk.GetObjectId(0);
            var loader = repository.Open(objectId);

            using (var stream = loader.OpenStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
Example #10
0
        private static string GetSnapshot(Repository repository, Git git, RevTree revTree, String file)
        {
            //Get snapshot , Retrive older version of an object
            TreeWalk treeWalk = TreeWalk.ForPath(git.GetRepository(), file, revTree);

            byte[] data = repository.Open(treeWalk.GetObjectId(0)).GetBytes();
            return(System.Text.Encoding.UTF8.GetString(data));


            //ObjectLoader loader = repository.Open(rev.ToObjectId());
            //InputStream ttt = loader.OpenStream();
            //string result = ttt.ToString();
            //Retrive older version of an object
            //RevTree revTree = rev.Tree;
            //TreeWalk treeWalk = new TreeWalk(git.GetRepository());
            //treeWalk.AddTree(revTree);
            //while (treeWalk.Next())
            //{
            //    //compare treeWalk.NameString yourself
            //    byte[] bytes = treeWalk.ObjectReader.Open(rev.ToObjectId()).GetCachedBytes();
            //    string result = System.Text.Encoding.UTF8.GetString(rev.RawBuffer);
            //}
        }
Example #11
0
        public static SRRProject GetProject(string path)
        {
            Repository repository;

            if (File.Exists(path))
            {
                repository = Repository.Open(path);
            }
            else
            {
                repository = Repository.Create(path);

                repository.InsertConfig("OUTPUT_REPLACEMENT", "0");
                repository.InsertConfig("OUTPUT_ENCODING", "UTF-8");
            }

            var result = new SRRProject(repository)
            {
                Path = path
            };

            return(result);
        }
        /// <summary>Check out content of the specified index entry</summary>
        /// <param name="wd">workdir</param>
        /// <param name="e">index entry</param>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public virtual void CheckoutEntry(FilePath wd, GitIndex.Entry e)
        {
            ObjectLoader ol   = db.Open(e.sha1, Constants.OBJ_BLOB);
            FilePath     file = new FilePath(wd, e.GetName());

            file.Delete();
            FileUtils.Mkdirs(file.GetParentFile(), true);
            FileOutputStream dst = new FileOutputStream(file);

            try
            {
                ol.CopyTo(dst);
            }
            finally
            {
                dst.Close();
            }
            if (Config_filemode() && File_hasExecute())
            {
                if (FileMode.EXECUTABLE_FILE.Equals(e.mode))
                {
                    if (!File_canExecute(file))
                    {
                        File_setExecute(file, true);
                    }
                }
                else
                {
                    if (File_canExecute(file))
                    {
                        File_setExecute(file, false);
                    }
                }
            }
            e.mtime = file.LastModified() * 1000000L;
            e.ctime = e.mtime;
        }
Example #13
0
        static void Main(string[] args)
        {
            Repository repo = Repository.Open(@"C:\Projects\dotGit");

            Console.WriteLine(repo.Storage);


            WalkTree(repo.HEAD.Commit.Tree, 0);



            //dotGit.Objects.Storage.Pack.LoadPack(System.IO.Path.Combine(repo.GitDir.FullName, "objects\\pack\\pack-209b24047b294e1d9a97680d62a5b9e1d4bef33c"));

            //Tag firstTag = repo.Tags["0.1-alpha"];
            //Branch master = repo.Branches["master"];
            Console.WriteLine(repo.HEAD.Commit.Tree.Children);

            //IStorableObject obj = repo.Storage.GetObject("bf6ae5d04bcd11d035be3654973ff5339d3f4e1b");

            //Index idx = repo.Index;

            //TreeNodeCollection nodes = repo.HEAD.Commit.Tree.Children;

            //Commit obj = repo.Storage.GetObject<Commit>("5202e973f3d38c583b1a4645d23a638acc012c41");
            //Blob b = repo.Storage.GetObject<Blob>("58d11b659b2c71a0cbdc0d037e237243cfec8a88");

            //IStorableObject o = repo.Storage.GetObject("54040746289fd8beff929bcdcdd2b33be8a3700b");

            //foreach (Tag tag in repo.Tags)
            //{
            //				Console.WriteLine(String.Format("Tag: '{0}' points to {1}", tag.Name, tag.SHA));
            //}


            Console.ReadLine();
        }
Example #14
0
        public static ShenmueProject GetProject(string path)
        {
            Repository repository;

            if (File.Exists(path))
            {
                repository = Repository.Open(path);
            }
            else
            {
                repository = Repository.Create(path);

                repository.InsertConfig("OUTPUT_REPLACEMENT", "1");
                repository.InsertConfig("OUTPUT_ENCODING", "UTF-8");

                repository.InsertReplacement("á", "à");
                repository.InsertReplacement("í", "ï");
                repository.InsertReplacement("ó", "ô");
                repository.InsertReplacement("ú", "ù");
                repository.InsertReplacement("ü", "ë");

                repository.InsertReplacement("Ú", "û");

                repository.InsertReplacement("ñ", "â");

                repository.InsertReplacement("¡", "Î");
                repository.InsertReplacement("¿", "Ê");
            }

            var result = new ShenmueProject(repository)
            {
                Path = path
            };

            return(result);
        }
Example #15
0
        } // End Function GetDiff


        // https://stackoverflow.com/questions/13537734/how-to-use-jgit-to-get-list-of-changed-files
        // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowChangedFilesBetweenCommits.java
        public static void GetChanges(Git git, Repository repo, RevCommit oldCommit, RevCommit newCommit)
        {
            System.Console.WriteLine("Printing diff between commit: " + oldCommit.ToString() + " and " + newCommit.ToString());
            ObjectReader reader = repo.NewObjectReader();

            // prepare the two iterators to compute the diff between
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.Reset(reader, oldCommit.Tree.Id);
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.Reset(reader, newCommit.Tree.Id);

            // DiffStatFormatter df = new DiffStatFormatter(newCommit.Name, repo);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                DiffFormatter diffFormatter = new DiffFormatter(ms);
                diffFormatter.SetRepository(repo);

                int entryCount = 0;
                foreach (DiffEntry entry in diffFormatter.Scan(oldCommit, newCommit))
                {
                    string pathToUse = null;

                    TreeWalk treeWalk = new TreeWalk(repo);
                    treeWalk.Recursive = true;

                    if (entry.GetChangeType() == DiffEntry.ChangeType.DELETE)
                    {
                        treeWalk.AddTree(oldCommit.Tree);
                        pathToUse = entry.GetOldPath();
                    }
                    else
                    {
                        treeWalk.AddTree(newCommit.Tree);
                        pathToUse = entry.GetNewPath();   
                    }

                    treeWalk.Filter = PathFilter.Create(pathToUse); 
                        
                    if (!treeWalk.Next())
                    {
                        throw new System.Exception("Did not find expected file '" + pathToUse + "'");
                    }

                    ObjectId objectId = treeWalk.GetObjectId(0);
                    ObjectLoader loader = repo.Open(objectId);

                    string strModifiedFile = ReadFile(loader);
                    System.Console.WriteLine(strModifiedFile);

                    //////////////
                    // https://stackoverflow.com/questions/27361538/how-to-show-changes-between-commits-with-jgit
                    diffFormatter.Format(diffFormatter.ToFileHeader(entry));

                    string diff = GetDiff(repo, entry);
                    System.Console.WriteLine(diff);

                    entryCount++;
                } // Next entry 

                System.Console.WriteLine(entryCount);

                ms.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ms))
                {
                    string strAllDiffs = sr.ReadToEnd();
                    System.Console.WriteLine(strAllDiffs);
                } // End Using sr 
                
            } // End Using ms 


            System.Collections.Generic.IList<DiffEntry> diffs = git.Diff()
                             .SetNewTree(newTreeIter)
                             .SetOldTree(oldTreeIter)
                             .Call();

            foreach (DiffEntry entry in diffs)
            {
                System.Console.WriteLine("Entry: " + entry);
                System.Console.WriteLine("Entry: " + entry.GetChangeType());
            } // Next entry 

            System.Console.WriteLine("Done");
        } // End Sub GetChanges 
        public void Refresh()
        {
            this.index = null;
            this.commitTree = null;

            this.cache.Clear();
            this.changedFiles = null;
            this.repositoryGraph = null;
            this.dirCache = null;
            this.head = null;
            this.ignoreRules = null;
            this.remotes = null;
            this.configs = null;
            if (!string.IsNullOrEmpty(initFolder))
            {
                try
                {
                    this.repository = Open(new DirectoryInfo(initFolder));
                    if (this.repository != null)
                    {
                        dirCache = repository.ReadDirCache();
                        head = repository.Resolve(Constants.HEAD);

                        if (head == null)
                        {
                            this.commitTree = new Tree(repository);
                        }
                        else
                        {
                            var treeId = ObjectId.FromString(repository.Open(head).GetBytes(), 5);
                            this.commitTree = new Tree(repository, treeId, repository.Open(treeId).GetBytes());
                        }

                        if (repository.IsBare)
                            throw new NoWorkTreeException();

                        this.index = new GitIndex(repository);
                        this.index.Read();
                        this.index.RereadIfNecessary();

                        try
                        {
                            //load local .gitignore file
                            var ignoreFile = Path.Combine(this.initFolder,
                                Constants.GITIGNORE_FILENAME);
                            if (File.Exists(ignoreFile))
                            {
                                ignoreRules = File.ReadAllLines(ignoreFile)
                                                  .Where(line => !line.StartsWith("#") && line.Trim().Length > 0)
                                                  .Select(line => new IgnoreRule(line)).ToList();
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLine("ReadIgnoreFile: {0}\r\n{1}", this.initFolder, ex.ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.repository = null;
                    Log.WriteLine("Refresh: {0}\r\n{1}", this.initFolder, ex.ToString());
                }
            }
        }
Example #17
0
        public void TestDirectoryHierarchy()
        {
            var fileSystem = new Repository();

            var nodeOne   = new LocalFileTree();
            var nodeTwo   = new LocalFileTree();
            var nodeThree = new ZipNodeTree();

            string appPath = Path.Combine(TestingUtils.GetTestingBaseFolder(), "testdata");

            var tempDir = Path.Combine(Path.Combine(appPath, @"Data2\temp"));

            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }


            Assert.IsTrue(nodeOne.Build(Path.Combine(appPath, @"Data\")));
            Assert.IsTrue(nodeTwo.Build(Path.Combine(appPath, @"Data2\")));
            Assert.IsTrue(nodeThree.Build(Path.Combine(appPath, @"Data.zip")));

            fileSystem.AddSystem("First", nodeOne);
            fileSystem.AddSystem("Second", nodeTwo);
            fileSystem.AddSystem("Third", nodeThree);

            Assert.IsTrue(fileSystem.DirExists(@"subfolder01"));
            Assert.IsTrue(fileSystem.DirExists(@"subfolder02"));
            Assert.IsTrue(fileSystem.DirExists(@"alphabetagamma"));
            Assert.IsTrue(fileSystem.DirExists(@"subfolder02\subfolder_a"));
            Assert.IsTrue(fileSystem.DirExists(@"subfolder02\subfolder_a\subfolder_a_b"));
            Assert.IsTrue(fileSystem.DirExists(@"subfolder02\subfolder_a\subfolder_a_c"));

            Assert.IsTrue(fileSystem.FileExists(@"colours.txt"));
            Assert.IsTrue(fileSystem.FileExists(@"File01.txt"));
            Assert.IsTrue(fileSystem.FileExists(@"subfolder02\booga.txt"));
            Assert.IsTrue(fileSystem.FileExists(@"subfolder02\subfolder_a\geoip.txt"));
            Assert.IsTrue(fileSystem.FileExists(@"subfolder02\subfolder_a\subfolder_a_b\another_test.folder.txt"));
            Assert.IsTrue(fileSystem.FileExists(@"subfolder01\map01.txt"));

            // Get Data from various filesystems
            // This should be coming from nodeOne
            using (Stream fs = fileSystem.Open(@"alphabetagamma\db.sample.txt"))
            {
                byte[]       buffer = new byte[1024];
                UTF8Encoding temp   = new UTF8Encoding(true);

                int amountRead   = fs.Read(buffer, 0, buffer.Length);
                int accumulation = amountRead;
                while (amountRead > 0)
                {
                    string contents = temp.GetString(buffer, 0, amountRead);
                    Console.Write(contents);
                    amountRead    = fs.Read(buffer, 0, buffer.Length);
                    accumulation += amountRead;
                }
                Console.WriteLine("");
                Console.WriteLine("Read {0} bytes", accumulation);
            }

            // This should be coming from nodeTwo
            using (Stream fs = fileSystem.Open(@"File01.txt"))
            {
                byte[]       buffer = new byte[1024];
                UTF8Encoding temp   = new UTF8Encoding(true);

                int amountRead   = fs.Read(buffer, 0, buffer.Length);
                int accumulation = amountRead;
                while (amountRead > 0)
                {
                    string contents = temp.GetString(buffer, 0, amountRead);
                    Console.Write(contents);
                    amountRead    = fs.Read(buffer, 0, buffer.Length);
                    accumulation += amountRead;
                }
                Console.WriteLine("");
                Console.WriteLine("Read {0} bytes", accumulation);
            }

            // This should be coming from nodeThree
            using (Stream fs = fileSystem.Open(@"subfolder02\subfolder_a\subfolder_a_c\data.data.data.txt"))
            {
                byte[]       buffer = new byte[1024];
                UTF8Encoding temp   = new UTF8Encoding(true);

                int amountRead   = fs.Read(buffer, 0, buffer.Length);
                int accumulation = amountRead;
                while (amountRead > 0)
                {
                    string contents = temp.GetString(buffer, 0, amountRead);
                    Console.Write(contents);
                    amountRead    = fs.Read(buffer, 0, buffer.Length);
                    accumulation += amountRead;
                }
                Console.WriteLine("");
                Console.WriteLine("Read {0} bytes", accumulation);
            }

            // Write a file - this should go into nodeTwo
            Byte[] info = new UTF8Encoding(true).GetBytes("This is a test of data being written into the FileSystem.");
            Assert.IsTrue(fileSystem.Write(@"temp\sample_file.txt", info, info.Length));
            Assert.IsTrue(fileSystem.FileExists(@"temp\sample_file.txt"));
            Assert.IsTrue(nodeTwo.FileExists(@"temp\sample_file.txt"));
            Assert.IsTrue(fileSystem.Delete(@"temp\sample_file.txt"));
        }
Example #18
0
 protected Repository SandboxRepository(string resource)
 {
     return(Repository.Open(SandboxResource(resource)));
 }
		/// <summary>
		/// Updates the file in the working tree with content and mode from an entry
		/// in the index.
		/// </summary>
		/// <remarks>
		/// Updates the file in the working tree with content and mode from an entry
		/// in the index. The new content is first written to a new temporary file in
		/// the same directory as the real file. Then that new file is renamed to the
		/// final filename.
		/// TODO: this method works directly on File IO, we may need another
		/// abstraction (like WorkingTreeIterator). This way we could tell e.g.
		/// Eclipse that Files in the workspace got changed
		/// </remarks>
		/// <param name="repo"></param>
		/// <param name="f">
		/// the file to be modified. The parent directory for this file
		/// has to exist already
		/// </param>
		/// <param name="entry">the entry containing new mode and content</param>
		/// <exception cref="System.IO.IOException">System.IO.IOException</exception>
		public static void CheckoutEntry(Repository repo, FilePath f, DirCacheEntry entry
			)
		{
			ObjectLoader ol = repo.Open(entry.GetObjectId());
			FilePath parentDir = f.GetParentFile();
			FilePath tmpFile = FilePath.CreateTempFile("._" + f.GetName(), null, parentDir);
			FileOutputStream channel = new FileOutputStream(tmpFile);
			try
			{
				ol.CopyTo(channel);
			}
			finally
			{
				channel.Close();
			}
			FS fs = repo.FileSystem;
			WorkingTreeOptions opt = repo.GetConfig().Get(WorkingTreeOptions.KEY);
			if (opt.IsFileMode() && fs.SupportsExecute())
			{
				if (FileMode.EXECUTABLE_FILE.Equals(entry.RawMode))
				{
					if (!fs.CanExecute(tmpFile))
					{
						fs.SetExecute(tmpFile, true);
					}
				}
				else
				{
					if (fs.CanExecute(tmpFile))
					{
						fs.SetExecute(tmpFile, false);
					}
				}
			}
			if (!tmpFile.RenameTo(f))
			{
				// tried to rename which failed. Let' delete the target file and try
				// again
				FileUtils.Delete(f);
				if (!tmpFile.RenameTo(f))
				{
					throw new IOException(MessageFormat.Format(JGitText.Get().couldNotWriteFile, tmpFile
						.GetPath(), f.GetPath()));
				}
			}
			entry.LastModified = f.LastModified();
			entry.SetLength((int)ol.GetSize());
		}
        public void Refresh()
        {
            this.cache.Clear();
            this.changedFiles = null;
            this.repositoryGraph = null;

            if (!string.IsNullOrEmpty(initFolder))
            {
                try
                {
                    this.repository = Git.Open(initFolder).GetRepository();

                    if (this.repository != null)
                    {
                        var id = repository.Resolve(Constants.HEAD);
                        //var commit = repository.MapCommit(id);
                        //this.commitTree = (commit != null ? commit.TreeEntry : new Tree(repository));
                        if (id == null)
                        {
                            this.commitTree = new Tree(repository);
                        }
                        else
                        {
                            var treeId = ObjectId.FromString(repository.Open(id).GetBytes(), 5);
                            this.commitTree = new Tree(repository, treeId, repository.Open(treeId).GetBytes());
                        }
                        this.index = repository.GetIndex();
                        this.index.RereadIfNecessary();

                        ignoreRules = File.ReadAllLines(Path.Combine(this.initFolder, Constants.GITIGNORE_FILENAME))
                                          .Where(line => !line.StartsWith("#") && line.Trim().Length > 0)
                                          .Select(line => new IgnoreRule(line)).ToList();
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
		/// <exception cref="System.IO.IOException"></exception>
		private static RawText GetRawText(ObjectId id, Repository db)
		{
			if (id.Equals(ObjectId.ZeroId))
			{
				return new RawText(new byte[] {  });
			}
			return new RawText(db.Open(id, Constants.OBJ_BLOB).GetCachedBytes());
		}
Example #22
0
        static void Main(string[] args)
        {
            Console.Write("QuadTree Tester Inicializando v 1.0\r\n");

            string basedir = @"C:\QTREE_REPO";

            var repo = new Repository();

            if (!System.IO.Directory.Exists(basedir))
            {
                Console.Write("El repositorio [{0}] no existe, lo creamos.\r\n", basedir);
                StorageGeometry sgeom = new StorageGeometry()
                {
                    Signature       = "0123456789ABCDEF",
                    CellBits        = (char)4,
                    ActiveKey       = 0x55AA55AA,
                    DataStart       = 2,
                    FileSectorCount = 64,
                    Lat_OffSet      = 340000000,
                    Lon_OffSet      = 580000000,
                    Lat_Grid        = 5000,
                    Lon_Grid        = 5000,
                    Lat_GridCount   = 2000,
                    Lon_GridCount   = 2000
                };

                if (!repo.Init(basedir, sgeom))
                {
                    Console.Write("Imposible inicializar el repositorio GR2\r\n");
                    Console.ReadLine();
                    return;
                }
            }

            StorageGeometry sgeom2 = new StorageGeometry();

            if (!repo.Open(basedir, ref sgeom2))
            {
                Console.Write("El repositorio GR2 parece corrupto.\r\n");
                Console.ReadLine();
                return;
            }


            Console.WriteLine("Header Signature: {0}", sgeom2.Signature);
            Console.ReadLine();


            var Cartografia = new Cartografia("C:\\MapasCopia");

            foreach (var map in Cartografia)
            {
                for (int j = map.Poligonos.Count - 1; j >= 0; j--)
                {
                    var poligono = map.Poligonos[j];
                    if (poligono.Nivel != 5000)
                    {
                        continue;
                    }
                    int[] vertices = map.Poligonos.GetVertices(j);


                    for (int i = 0; i < vertices.Length; i++)
                    {
                        var vertex = vertices[i];
                        var lonlat = new LonLat(map.Coords[vertex]);
                        //6T.TRACE("Creando vertice #{0} {1} {2}", vertex, lonlat.Latitud, lonlat.Longitud);
                        repo.SetPositionClass((float)lonlat.Latitud, (float)lonlat.Longitud, 1);
                        var Gr2Cache = repo.IndexCatalog.OfType <GR2>().FirstOrDefault();
                        Gr2Cache.SetReference((float)lonlat.Latitud, (float)lonlat.Longitud, "v", map.Vertices[vertex]);
                    }
                }
            }

            repo.SetPositionClass(34.5665F, 55.2235F, 12);
            int clase     = repo.GetPositionClass(34.5665F, 55.2235F);
            var Gr2Cache2 = repo.IndexCatalog.OfType <GR2>().FirstOrDefault();
            var rd        = Gr2Cache2.GetReference <Vertice>(34.5665F, 55.2235F, "vertices");

            Vertice ppp = new Vertice()
            {
                Tipo = 22123123, Prioridad = 1234, NReg = 2357
            };

            Gr2Cache2.SetReference(34.5665F, 55.2235F, "vertices", ppp);
            Console.Write("sample: clase leida {0}\r\n", clase);
            Console.Write("\r\n");

            /*
             * qtree.SetPositionClass(34.2665, 55.4235, 3);
             * qtree.SetPositionClass(34.267, 55.4235, 4);
             * qtree.SetPositionClass(34.268, 55.4235, 5);
             * qtree.SetPositionClass(34.269, 55.4235, 6);
             * qtree.SetPositionClass(34.270, 55.4235, 7);
             * qtree.SetPositionClass(34.271, 55.4235, 8);
             *
             * clase = qtree.GetPositionClass(34.2665, 55.4235);
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * clase = qtree.GetPositionClass(34.5665, 55.2235);
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * clase = qtree.GetPositionClass(34.2665, 55.4235);
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * qtree.SetPositionClass(37.5665, 55.2235, 12);
             * clase = qtree.GetPositionClass(37.5665, 55.2235);
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * qtree.SetPositionClass(37.2665, 55.4235, 3);
             * clase = qtree.GetPositionClass(37.2665, 55.4235);
             *
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * clase = qtree.GetPositionClass(37.5665, 55.2235);
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * clase = qtree.GetPositionClass(37.2665, 55.4235);
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * qtree.SetPositionClass(37.2665, 55.4235, 8);
             * clase = qtree.GetPositionClass(37.2665, 55.4235);
             * Console.Write("sample: clase leida {0}\r\n", clase);
             * Console.Write("\r\n");
             *
             * qtree.SetPositionClass(34.0, 55.0, 4);
             * qtree.SetPositionClass(34.99999, 55.99999, 4);
             *
             * qtree.SetPositionClass(46.5, 65.5, 5);
             * qtree.SetPositionClass(47.2, 56.4, 15); */


            repo.Close();
            Console.ReadLine();
        }
        public void Refresh()
        {
            this.cache.Clear();
            this.changedFiles = null;

            if (!string.IsNullOrEmpty(initFolder))
            {
                try
                {
                    this.repository = Git.Open(initFolder).GetRepository();

                    if (this.repository != null)
                    {
                        var id = repository.Resolve(Constants.HEAD);
                        //var commit = repository.MapCommit(id);
                        //this.commitTree = (commit != null ? commit.TreeEntry : new Tree(repository));
                        if (id == null)
                        {
                            this.commitTree = new Tree(repository);
                        }
                        else
                        {
                            var treeId = ObjectId.FromString(repository.Open(id).GetBytes(), 5);
                            this.commitTree = new Tree(repository, treeId, repository.Open(treeId).GetBytes());
                        }
                        this.index = repository.GetIndex();
                        this.index.RereadIfNecessary();
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }