Ejemplo n.º 1
0
        public TreeEntry BuildEntryGraph(Rectangle layout)
        {
            var root = new TreeEntry
            {
                Item = null, 
                Layout = null, 
                Name = null, 
                FullName = string.Empty, 
                Children = new List<TreeEntry>(), 
                SegmentCount = 0
            };
            foreach (var item in _items.OrderBy(x => x.Text).ToArray())
            {
                var parent = FindParentForItem(root, item);
                if (parent == null)
                {
                    BackfillParentsForItem(root, item);
                }

                parent = FindParentForItem(root, item);
                var entry = new TreeEntry
                {
                    Item = item, 
                    Layout = null, 
                    Name = item.Text.Split('.').Last(), 
                    FullName = (parent.FullName + "." + item.Text.Split('.').Last()).Trim('.'), 
                    Children = new List<TreeEntry>(), 
                    SegmentCount = parent.SegmentCount + 1
                };
                parent.Children.Add(entry);
            }

            return root;
        }
Ejemplo n.º 2
0
        protected override void AddTreeEntry(string path, TreeEntry entry, DateTimeOffset modificationTime)
        {
            switch (entry.Mode)
            {
                case Mode.GitLink:
                case Mode.Directory:
                    writer.Write(path + "/", null, modificationTime, "775".OctalToInt32(),
                        "0", "0", '5', "root", "root", "0", "0", entry.TargetId.Sha, false);
                    break;
                case Mode.ExecutableFile:
                case Mode.NonExecutableFile:
                case Mode.NonExecutableGroupWritableFile:
                    var blob = ((Blob) entry.Target);

                    WriteStream(path, entry, modificationTime,
                        () => blob.IsBinary ? blob.GetContentStream() : blob.GetContentStream(new FilteringOptions(path)));
                    break;
                case Mode.SymbolicLink:
                    using (Stream contentStream = ((Blob)entry.Target).GetContentStream(new FilteringOptions(path)))
                    {
                        writer.Write(path, contentStream, modificationTime, "777".OctalToInt32(),
                            "0", "0", '2', "root", "root", "0", "0", entry.TargetId.Sha, true);
                    }
                    break;
                default:
                    throw new InvalidOperationException(string.Format("Unsupported file mode: {0} (sha1: {1}).", entry.Mode, entry.TargetId.Sha));
            }
        }
Ejemplo n.º 3
0
 void IndexTreeVisitor.VisitEntry(TreeEntry treeEntry, TreeEntry auxEntry, GitIndex.Entry indexEntry, FileInfo file)
 {
     VisitEntryAuxDelegate handler = VisitEntryAux;
     if (handler != null)
     {
         handler(treeEntry, auxEntry, indexEntry, file);
     }
 }
Ejemplo n.º 4
0
 private void WriteStream(string path, TreeEntry entry, DateTimeOffset modificationTime, Func<Stream> streamer)
 {
     using (Stream contentStream = streamer())
     {
         writer.Write(path, contentStream, modificationTime,
             (entry.Mode == Mode.ExecutableFile) ? "775".OctalToInt32() : "664".OctalToInt32(),
             "0", "0", '0', "root", "root", "0", "0", entry.TargetId.Sha, false);
     }
 }
Ejemplo n.º 5
0
		public static void Fill(TreeEntry entry, double chance)
		{
			double f;
			while ((f = r.NextDouble()) < chance) {
				var e = new TextTreeEntry(f.ToString());
				entry.Add(e);
				Fill(e, chance * chance);
			}
		}
Ejemplo n.º 6
0
		public int SetDimElements(int x, int y, int w, TreeEntry entry)
		{
			int heigth = entry.Height;
			entry.SetDim(x, y, w, heigth);
			foreach (TreeEntry child in entry) {
				heigth += SetDimElements(x + 2, y + heigth, w - 1, child);
			}
			return heigth;
		}
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleEntry" /> struct.
 /// </summary>
 /// <param name="repo">The repo.</param>
 /// <param name="entry">The tree entry.</param>
 /// <exception cref="System.ArgumentNullException">
 /// repo
 /// or
 /// entry
 /// </exception>
 internal SimpleEntry(Repository repo, TreeEntry entry)
     : this()
 {
     if (repo == null) throw new ArgumentNullException("repo");
     if (entry == null) throw new ArgumentNullException("entry");
     this.repo = repo;
     this.entry = entry;
     target = entry.Target;
     this.blob = entry.Target as Blob;
     this.link = entry.Target as GitLink;
 }
Ejemplo n.º 8
0
        public void CanConvertEntryToTree()
        {
            using (var repo = new Repository(BareTestRepoPath))
            {
                var       tree      = repo.Lookup <Tree>(sha);
                TreeEntry treeEntry = tree["1"];

                var subtree = treeEntry.Target as Tree;
                Assert.NotNull(subtree);
            }
        }
Ejemplo n.º 9
0
        public void CanConvertEntryToBlob()
        {
            using (var repo = new Repository(BareTestRepoPath))
            {
                var       tree      = repo.Lookup <Tree>(sha);
                TreeEntry treeEntry = tree["README"];

                var blob = treeEntry.Target as Blob;
                Assert.NotNull(blob);
            }
        }
Ejemplo n.º 10
0
 public void CanCompareTwoTreeEntries()
 {
     using (var repo = new Repository(BareTestRepoPath))
     {
         var       tree       = repo.Lookup <Tree>(sha);
         TreeEntry treeEntry1 = tree["README"];
         TreeEntry treeEntry2 = tree["README"];
         Assert.Equal(treeEntry2, treeEntry1);
         Assert.True((treeEntry1 == treeEntry2));
     }
 }
Ejemplo n.º 11
0
 public void CanCompareTwoTreeEntries()
 {
     using (var repo = new Repository(BareTestRepoPath))
     {
         var       tree       = repo.Lookup <Tree>(sha);
         TreeEntry treeEntry1 = tree["README"];
         TreeEntry treeEntry2 = tree["README"];
         treeEntry1.ShouldEqual(treeEntry2);
         (treeEntry1 == treeEntry2).ShouldBeTrue();
     }
 }
Ejemplo n.º 12
0
        public void GettingAnUknownTreeEntryReturnsNull()
        {
            string path = SandboxBareTestRepo();

            using (var repo = new Repository(path))
            {
                var tree = repo.Lookup <Tree>(sha);
                Assert.False(tree.IsMissing);
                TreeEntry treeEntry = tree["I-do-not-exist"];
                Assert.Null(treeEntry);
            }
        }
Ejemplo n.º 13
0
        public void CanGetEntryByName()
        {
            string path = SandboxBareTestRepo();

            using (var repo = new Repository(path))
            {
                var       tree      = repo.Lookup <Tree>(sha);
                TreeEntry treeEntry = tree["README"];
                Assert.Equal("a8233120f6ad708f843d861ce2b7228ec4e3dec6", treeEntry.Target.Sha);
                Assert.Equal("README", treeEntry.Name);
            }
        }
Ejemplo n.º 14
0
        public static TreeEntry ShouldBeFile(this TreeEntry treeEntry, string filePath)
        {
            treeEntry.type.ShouldBe("commit_file");
            treeEntry.path.ShouldBe(filePath);
            treeEntry.size.ShouldNotBeNull();
            treeEntry.size?.ShouldBeGreaterThan(0);
            treeEntry.attributes.ShouldNotBeNull();
            ////treeEntry.mimetype.ShouldNotBeNull(); // mime type is filled only when the extension is recognized by BitBucket, otherwise it's null
            treeEntry.links.history.href.ShouldNotBeNull();

            return(treeEntry);
        }
Ejemplo n.º 15
0
        public static string GetFileContent(this TreeEntry treeEntry)
        {
            var blob          = (Blob)treeEntry.Target;
            var contentStream = blob.GetContentStream();

            Debug.Assert(blob.Size == contentStream.Length);

            using (var tr = new StreamReader(contentStream, Encoding.UTF8))
            {
                return(tr.ReadToEnd());
            }
        }
Ejemplo n.º 16
0
        protected void SetRootNode(TreeEntry <nwdbTree> t)
        {
            if (this._TreeBindingSource != null)
            {
                throw new ApplicationException("Error in Tree control:SetRootNode: use SetSystree or TreeBindingSource but not both");
            }

            this.Nodes.Clear();
            this._sysTree  = t;
            this._RootNode = t;  //Captures that we are in SetBySysTreeMode , not BindingSource mode
            UpdateTree();
        }
Ejemplo n.º 17
0
		void Discover(TreeEntry entry, DirectoryInfo di, int level, int maxlevel) 
		{
			if (level > maxlevel) {
				return;
			}

			var child = new TextTreeEntry(di.Name);
			entry.Add(child);

			foreach (var dir in di.GetDirectories()) {
				Discover(child, dir, level + 1, maxlevel);
			}
		}
Ejemplo n.º 18
0
 private void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
 {
     Dispatcher.Invoke(() =>
     {
         var G1      = new TreeEntry();
         var C1      = new RDP();
         C1.EntryID  = 1;
         C1.ParentID = 0;
         C1.Name     = "G1";
         G1.Config   = C1;
         RootEntry.Children.Add(G1);
     });
 }
Ejemplo n.º 19
0
        public void CanCompareTwoTreeEntries()
        {
            string path = SandboxBareTestRepo();

            using (var repo = new Repository(path))
            {
                var tree = repo.Lookup <Tree>(sha);
                Assert.False(tree.IsMissing);
                TreeEntry treeEntry1 = tree["README"];
                TreeEntry treeEntry2 = tree["README"];
                Assert.Equal(treeEntry2, treeEntry1);
                Assert.True((treeEntry1 == treeEntry2));
            }
        }
Ejemplo n.º 20
0
        public void CanConvertEntryToTree()
        {
            string path = SandboxBareTestRepo();

            using (var repo = new Repository(path))
            {
                var tree = repo.Lookup <Tree>(sha);
                Assert.False(tree.IsMissing);
                TreeEntry treeEntry = tree["1"];

                var subtree = treeEntry.Target as Tree;
                Assert.NotNull(subtree);
            }
        }
Ejemplo n.º 21
0
        public IActionResult GetRawBlob(string userName, string repoName, string id, string path)
        {
            return(TryGetResult(repoName, () =>
            {
                if (path == null)
                {
                    return Redirect(Url.UnencodedRouteLink("GetTreeView", new { repoName = repoName, id = id, path = path }));
                }

                var DCRepositoriesService = Ioc.Create <IDCRepositoriesService>();

                repoName = Path.Combine(userName, repoName);
                Repository repo = DCRepositoriesService.GetRepository(repoName);
                Commit commit = repo.Branches[id]?.Tip ?? repo.Lookup <Commit>(id);

                if (commit == null)
                {
                    return NotFound();
                }

                TreeEntry entry = commit[path.Replace('/', Path.DirectorySeparatorChar)];
                if (entry == null)
                {
                    return NotFound();
                }

                switch (entry.TargetType)
                {
                case TreeEntryTargetType.Blob:
                    {
                        Blob blob = (Blob)entry.Target;

                        if (blob.IsBinary)
                        {
                            return File(blob.GetContentStream(), "application/octet-stream", entry.Name);
                        }
                        else
                        {
                            return File(blob.GetContentStream(), "text/plain");
                        }
                    }

                case TreeEntryTargetType.Tree:
                    return Redirect(Url.UnencodedRouteLink("GetTreeView", new { repoName = repoName, id = id, path = path }));

                default:
                    return BadRequest();
                }
            }));
        }
Ejemplo n.º 22
0
        public void CanConvertEntryToBlob()
        {
            string path = SandboxBareTestRepo();

            using (var repo = new Repository(path))
            {
                var tree = repo.Lookup <Tree>(sha);
                Assert.False(tree.IsMissing);
                TreeEntry treeEntry = tree["README"];

                var blob = treeEntry.Target as Blob;
                Assert.NotNull(blob);
            }
        }
Ejemplo n.º 23
0
 private static void TreeEntryParsing(TreeEntry file)
 {
     if (file.Mode == Mode.Directory)
     {
         foreach (var child in (file.Target as Tree))
         {
             TreeEntryParsing(child);
         }
     }
     else
     {
         UpdateFileFrequency(file.Path);
     }
 }
Ejemplo n.º 24
0
 private void LocateChangedFiles(TreeEntry treeEntry, List <MetricsModel> filesContainer)
 {
     if (treeEntry.Mode == Mode.Directory)
     {
         foreach (var child in ((Tree)treeEntry.Target))
         {
             LocateChangedFiles(child, filesContainer);
         }
     }
     else
     {
         AddChangeToFile(treeEntry.Path, filesContainer);
     }
 }
Ejemplo n.º 25
0
 private RepositoryTreeDetailModel CreateRepositoryDetailModel(TreeEntry entry, Commit ancestor, string treeName)
 {
     return(new RepositoryTreeDetailModel
     {
         Name = entry.Name,
         CommitDate = ancestor != null ? ancestor.Author.When.LocalDateTime : default(DateTime?),
         CommitMessage = ancestor != null ? ancestor.MessageShort : String.Empty,
         Author = ancestor != null ? ancestor.Author.Name : String.Empty,
         IsTree = entry.TargetType == TreeEntryTargetType.Tree,
         TreeName = treeName,
         Path = entry.Path.Replace('\\', '/'),
         IsImage = FileDisplayHandler.IsImage(entry.Name),
     });
 }
 private static void CountUpdatedFilesFrequency(TreeEntry file)
 {
     if (file.Mode == Mode.Directory)
     {
         foreach (var child in (file.Target as Tree))
         {
             CountUpdatedFilesFrequency(child);
         }
     }
     else
     {
         UpdateFileFrequency(file.Path);
     }
 }
Ejemplo n.º 27
0
        public static void ShowDiffPrev(string path)
        {
            if (string.IsNullOrEmpty(path) && Repository != null)
            {
                return;
            }

            TreeEntry entry  = null;
            string    lastId = null;

            foreach (var commit in Repository.Head.Commits)
            {
                TreeEntry e = commit.Tree[path];
                if (e == null)
                {
                    continue;
                }
                if (lastId == null)
                {
                    lastId = e.Target.Sha;
                }
                else if (lastId != e.Target.Sha)
                {
                    entry = e;
                    break;
                }
            }

            if (entry == null)
            {
                return;
            }
            Blob blob = entry.Target as Blob;

            if (blob == null || blob.IsBinary)
            {
                return;
            }
            string newPath = Application.dataPath.Replace("Assets", "Temp/") + "Git-diff-tmp-file";

            if (!string.IsNullOrEmpty(newPath))
            {
                using (FileStream file = File.Create(newPath))
                {
                    blob.GetContentStream().CopyTo(file);
                }
            }
            EditorUtility.InvokeDiffTool(Path.GetFileName(path) + " - " + entry.Target.Sha, newPath, Path.GetFileName(path) + " - Working Tree", path, "", "");
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Compare a file in the given commit with the previous version of the file.
        /// </summary>
        /// <param name="fileName">The file name to get the diff for.</param>
        /// <param name="commit">The commit to compare with.</param>
        /// <returns>The diff for the file.</returns>
        public string GetChangedFileDiff(string fileName, SimpleRepositoryCommit commit)
        {
            if (commit == null)
            {
                throw new ArgumentNullException("commit");
            }
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentException("fileName is null or whitespace.", "fileName");
            }

            if (!String.IsNullOrWhiteSpace(SubFolder))
            {
                fileName = Path.Combine(SubFolder, fileName);
            }

            string newerText = String.Empty;
            string olderText = String.Empty;

            Validate();

            using (Repository repo = Init(false))
            {
                Commit c = repo.Lookup(commit.Sha) as Commit;
                if (c != null)
                {
                    TreeEntry newerEntry = c[fileName];
                    if (newerEntry != null && newerEntry.Target is Blob)
                    {
                        newerText = (newerEntry.Target as Blob).GetContentText();
                    }

                    if (c.Parents != null)
                    {
                        Commit p = c.Parents.FirstOrDefault();
                        if (p != null)
                        {
                            TreeEntry olderEntry = p[fileName];
                            if (olderEntry != null && olderEntry.Target is Blob)
                            {
                                olderText = (olderEntry.Target as Blob).GetContentText();
                            }
                        }
                    }
                }
            }

            return(DiffUtility.Diff(olderText, newerText));
        }
Ejemplo n.º 29
0
        private Stream OpenEntry(TreeEntry entry)
        {
            if (!(entry.Target is Blob blob))
            {
                return(null);
            }

            using (var s = blob.GetContentStream())
            {
                var buffer = new SlimMemoryStream();
                s.CopyTo(buffer);
                buffer.Position = 0;
                return(buffer);
            }
        }
Ejemplo n.º 30
0
        private Blob FindAndLoadBlob(string[] dirHierarchy, int i)
        {
            if (i == dirHierarchy.Length - 1)
            {
                if (!_blobs.ContainsKey(dirHierarchy[i]))
                {
                    return(null);
                }
                return(_blobs[dirHierarchy[i]].LoadBlob());
            }

            TreeEntry subTreeEntry = _subTrees[dirHierarchy[i]];

            return(subTreeEntry.LoadTree().FindAndLoadBlob(dirHierarchy, i + 1));
        }
Ejemplo n.º 31
0
 private static int Compare(TreeEntry t, GitIndex.Entry i)
 {
     if ((t == null) && (i == null))
     {
         return 0;
     }
     if (t == null)
     {
         return 1;
     }
     if (i == null)
     {
         return -1;
     }
     return Tree.CompareNames(t.FullNameUTF8, i.NameUTF8, TreeEntry.LastChar(t), TreeEntry.LastChar(i));
 }
Ejemplo n.º 32
0
        /// <summary>
        /// The normalize tree.
        /// </summary>
        /// <param name="tree">
        /// The tree.
        /// </param>
        /// <param name="exclude">
        /// The exclude.
        /// </param>
        /// <returns>
        /// The <see cref="List{TreeEntry}"/>.
        /// </returns>
        public List <TreeEntry> NormalizeTree(TreeEntry tree, bool exclude)
        {
            var list = new List <TreeEntry>();

            if (!exclude)
            {
                list.Add(tree);
            }

            foreach (var child in tree.Children)
            {
                list.AddRange(this.NormalizeTree(child, false));
            }

            return(list);
        }
Ejemplo n.º 33
0
        private Tree FindAndLoadSubTree(string[] dirHierarchy, int i)
        {
            if (dirHierarchy.Length == 1 || i == dirHierarchy.Length - 1)
            {
                return(this);
            }

            if (!_subTrees.ContainsKey(dirHierarchy[i + 1]))
            {
                return(null);
            }

            TreeEntry subTreeEntry = _subTrees[dirHierarchy[i + 1]];

            return(subTreeEntry.LoadTree().FindAndLoadSubTree(dirHierarchy, i + 1));
        }
Ejemplo n.º 34
0
        public static void ShowDiff(string path, Commit commit, [CanBeNull] Commit other)
        {
            TreeEntry entry = commit[path];

            if (entry != null)
            {
                Blob blob = entry.Target as Blob;
                if (blob == null || blob.IsBinary)
                {
                    return;
                }
                string oldFilePath = Application.dataPath.Replace("Assets", "Temp/") + "Git-diff-tmp-file";
                if (!string.IsNullOrEmpty(oldFilePath))
                {
                    using (FileStream file = File.Create(oldFilePath))
                    {
                        blob.GetContentStream().CopyTo(file);
                    }
                }
                string otherFilePath = path;
                if (other != null)
                {
                    TreeEntry otherEntry = other[path];
                    if (otherEntry == null)
                    {
                        return;
                    }
                    Blob otherBlob = otherEntry.Target as Blob;
                    if (otherBlob == null || otherBlob.IsBinary)
                    {
                        return;
                    }
                    otherFilePath = Application.dataPath.Replace("Assets", "Temp/") + "Git-diff-tmp-file-other";
                    if (string.IsNullOrEmpty(otherFilePath))
                    {
                        return;
                    }
                    using (FileStream file = File.Create(otherFilePath))
                    {
                        otherBlob.GetContentStream().CopyTo(file);
                    }
                }

                var asset = AssetDatabase.LoadAssetAtPath(path, typeof(Object));
                GitExternalManager.ShowDiff(Path.GetFileName(path) + " - " + entry.Target.Sha, oldFilePath, Path.GetFileName(path) + " - " + (other == null ? "Working Tree" : other.Id.Sha), otherFilePath, asset != null ? asset.GetType() : null);
            }
        }
Ejemplo n.º 35
0
        public void ComparingReliesOnProvidedConfigEntriesIfAny()
        {
            const string file = "1/branch_file.txt";

            string path = CloneStandardTestRepo();

            using (var repo = new Repository(path))
            {
                TreeEntry entry = repo.Head[file];
                Assert.Equal(Mode.ExecutableFile, entry.Mode);

                // Recreate the file in the workdir without the executable bit
                string fullpath = Path.Combine(repo.Info.WorkingDirectory, file);
                File.Delete(fullpath);
                using (var stream = ((Blob)(entry.Target)).GetContentStream())
                {
                    Touch(repo.Info.WorkingDirectory, file, stream);
                }

                // Unset the local core.filemode, if any.
                repo.Config.Unset("core.filemode");
            }

            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();

            var options = BuildFakeSystemConfigFilemodeOption(scd, true);

            using (var repo = new Repository(path, options))
            {
                var changes = repo.Diff.Compare <TreeChanges>(new[] { file });

                Assert.Equal(1, changes.Count());

                var change = changes.Modified.Single();
                Assert.Equal(Mode.ExecutableFile, change.OldMode);
                Assert.Equal(Mode.NonExecutableFile, change.Mode);
            }

            options = BuildFakeSystemConfigFilemodeOption(scd, false);

            using (var repo = new Repository(path, options))
            {
                var changes = repo.Diff.Compare <TreeChanges>(new[] { file });

                Assert.Equal(0, changes.Count());
            }
        }
Ejemplo n.º 36
0
        public void CanRetrieveTreeEntryPath()
        {
            string path = SandboxBareTestRepo();

            using (var repo = new Repository(path))
            {
                /* From a commit tree */
                var commitTree = repo.Lookup <Commit>("4c062a6").Tree;
                Assert.False(commitTree.IsMissing);

                TreeEntry treeTreeEntry = commitTree["1"];
                Assert.Equal("1", treeTreeEntry.Path);

                string completePath = "1/branch_file.txt";

                TreeEntry blobTreeEntry = commitTree["1/branch_file.txt"];
                Assert.Equal(completePath, blobTreeEntry.Path);

                // A tree entry is now fetched through a relative path to the
                // tree but exposes a complete path through its Path property
                var subTree = treeTreeEntry.Target as Tree;
                Assert.NotNull(subTree);
                Assert.False(subTree.IsMissing);
                TreeEntry anInstance = subTree["branch_file.txt"];

                Assert.NotEqual("branch_file.txt", anInstance.Path);
                Assert.Equal(completePath, anInstance.Path);
                Assert.Equal(completePath, subTree.First().Path);

                /* From a random tree */
                var       tree            = repo.Lookup <Tree>(treeTreeEntry.Target.Id);
                TreeEntry anotherInstance = tree["branch_file.txt"];
                Assert.Equal("branch_file.txt", anotherInstance.Path);

                // From a rev-parse statement
                var       revparseTree       = repo.Lookup <Tree>("master:1");
                TreeEntry yetAnotherInstance = revparseTree["branch_file.txt"];
                Assert.Equal(completePath, yetAnotherInstance.Path);

                Assert.Equal(tree, subTree);
                Assert.Equal(revparseTree, tree);
                Assert.Equal(anotherInstance, anInstance);
                Assert.Equal(yetAnotherInstance, anotherInstance);
                Assert.NotEqual(anotherInstance.Path, anInstance.Path);
                Assert.NotSame(anotherInstance, anInstance);
            }
        }
        /// <summary>
        /// Gets the contents of the file inside of the project,
        /// only files in the root of the project can be fetched.
        /// </summary>
        /// <param name="commit">Represents revision of the project, which from file is read</param>
        /// <param name="name">Name of the file</param>
        public static string GetFileContents(this Commit commit, string name)
        {
            if (commit == null || commit.Tree == null || name == null)
            {
                return(null);
            }

            TreeEntry te = commit.Tree.FirstOrDefault <TreeEntry>(t => t.Name == name);

            if (te != null && te.TargetType == TreeEntryTargetType.Blob)
            {
                var blob = (Blob)te.Target;
                return(blob.GetContentText());
            }

            return(null);
        }
        public string GetFileContents(string repoName, string filePath)
        {
            Tree      fileTree = GetFileTree(repoName);
            TreeEntry entry    = fileTree[filePath];

            if (entry == null)
            {
                throw new GitException($"No file found at path \"{filePath}\"", null);
            }

            if (entry.TargetType != TreeEntryTargetType.Blob)
            {
                throw new GitException("Path doesn't point to a file", null);
            }

            return(((Blob)entry.Target).GetContentText());
        }
        private async System.Threading.Tasks.Task ShareCommit(Repository repository, Commit commit)
        {
            using (MultipartFormDataContent formData = new MultipartFormDataContent())
            {
                CweEntry selectedEntry = cweComboBox.SelectedItem as CweEntry;
                formData.Add(new StringContent(selectedEntry.Id.ToString()), "CweId");
                formData.Add(new StringContent(commit.Message), "CommitMessage");
                formData.Add(new StringContent(commentTextBox.Text), "Comment");
                formData.Add(new StringContent((fixesButton.IsChecked == true).ToString()), "FixedWithCommit");
                await TaskScheduler.Default;
                int    fileCount    = 0;
                Commit parentCommit = commit.Parents.First();
                Patch  patch        = repository.Diff.Compare <Patch>(parentCommit.Tree, commit.Tree);
                int    totalChanges = patch.Count();
                foreach (PatchEntryChanges change in patch)
                {
                    fileCount++;
                    string fileName = Path.GetFileName(change.Path);
                    await WriteToOutput($"Retrieving change {fileCount}/{totalChanges} ({fileName})");

                    TreeEntry treeEntry = commit.Tree[change.Path];
                    if (treeEntry != null && treeEntry.TargetType == TreeEntryTargetType.Blob)
                    {
                        Blob blob = treeEntry.Target as Blob;
                        formData.Add(new StringContent(((int)change.Status).ToString()), $"File{fileCount}ChangeKind");
                        formData.Add(new StreamContent(blob.GetContentStream()), $"CurrentFile{fileCount}", treeEntry.Path);
                        TreeEntry previousVersion = GetPreviousVersionOfFile(repository, treeEntry, commit);
                        if (previousVersion != null)
                        {
                            Blob previousBlob = previousVersion.Target as Blob;
                            formData.Add(new StreamContent(previousBlob.GetContentStream()), $"PreviousFile{fileCount}", previousVersion.Path);
                        }
                    }
                    await UpdateProgress(fileCount / (totalChanges + 1.0));
                }

                string apiUrl = "https://micscan.azurewebsites.net/api/Share";
                using (HttpClient httpClient = new HttpClient())
                {
                    await WriteToOutput($"Uploading commit.");

                    HttpResponseMessage response = await httpClient.PostAsync(apiUrl, formData);
                    await UpdateProgress(1.0);
                }
            }
        }
Ejemplo n.º 40
0
		public int DrawGrid(int x, int y, int w, TreeEntry entry)
		{
			switch (entry.Count) {
			case 0:
				return entry.Height;
			case 1:
				Set(x    , y + 1, ACS.LLCORNER);
				Set(x + 1, y + 1, '-');
				return DrawGrid(x + Offset, y + 1, w, entry[0]) + entry.Height;
			default:
				int height = 0;
				int i = 0, c = entry.Count - 1;
				foreach (TreeEntry child in entry) {
					bool first = i == 0;
					bool last = i == c;
					bool middle = !first && !last;
					if (first || middle) {
						Set(x,     y + height + 1, ACS.LTEE);
						Set(x + 1, y + height + 1, '-');
					} else {
						Set(x,     y + height + 1, ACS.LLCORNER);
						Set(x + 1, y + height + 1, '-');
					}

					int childHeight = DrawGrid(x + Offset, y + height + child.Height, w - 1, child);

					if (!last) {
						for (int j = 1; j < childHeight; j++) {
							Set(x, y + height + j + 1, ACS.VLINE);
						}
					}

					height += childHeight;
					i++;
				}
				return height + entry.Height;
			}
		}
Ejemplo n.º 41
0
        private RepositoryTreeDetailModel CreateRepositoryDetailModel(TreeEntry entry, Commit ancestor, string treeName)
        {
            var maximumMessageLength = 50; //FIXME Propbably in appSettings?
            var originMessage = ancestor != null ? ancestor.Message : String.Empty;
            var commitMessage = !String.IsNullOrEmpty(originMessage)
                ? RepositoryCommitModelHelpers.MakeCommitMessage(originMessage, maximumMessageLength).ShortTitle : String.Empty;

            return new RepositoryTreeDetailModel
            {
                Name = entry.Name,
                CommitDate = ancestor != null ? ancestor.Author.When.LocalDateTime : default(DateTime?),
                CommitMessage = commitMessage,
                Author = ancestor != null ? ancestor.Author.Name : String.Empty,
                IsTree = entry.TargetType == TreeEntryTargetType.Tree,
                IsLink = entry.TargetType == TreeEntryTargetType.GitLink,
                TreeName = treeName,
                Path = entry.Path.Replace('\\', '/'),
                IsImage = FileDisplayHandler.IsImage(entry.Name),
            };
        }
Ejemplo n.º 42
0
 public GitTreeEntry(TreeEntry entry)
 {
     _entry = entry;
 }
Ejemplo n.º 43
0
		internal void RemoveEntry(TreeEntry e)
		{
			TreeEntry[] c = _contents;
			int p = BinarySearch(c, e.NameUTF8, GitSharp.Core.TreeEntry.LastChar(e), 0, e.NameUTF8.Length);
			if (p >= 0)
			{
				var n = new TreeEntry[c.Length - 1];
				for (int k = c.Length - 1; k > p; k--)
				{
					n[k - 1] = c[k];
				}

				for (int k = p - 1; k >= 0; k--)
				{
					n[k] = c[k];
				}

				_contents = n;
				SetModified();
			}
		}
Ejemplo n.º 44
0
		///	<summary>
		/// Add the specified tree entry to this tree.
		///	</summary>
		///	<param name="e"> </param>
		///	<exception cref="IOException"></exception>
		public void AddEntry(TreeEntry e)
		{
			EnsureLoaded();
			int p = BinarySearch(_contents, e.NameUTF8, GitSharp.Core.TreeEntry.LastChar(e), 0, e.NameUTF8.Length);
			if (p < 0)
			{
				e.AttachParent(this);
				InsertEntry(p, e);
			}
			else
			{
				throw new EntryExistsException(e.Name);
			}
		}
Ejemplo n.º 45
0
        private void ProcessEntry(TreeEntry h, TreeEntry m, GitIndex.Entry i)
        {
            ObjectId iId = (i == null ? null : i.ObjectId);
            ObjectId mId = (m == null ? null : m.Id);
            ObjectId hId = (h == null ? null : h.Id);

            string name = (i != null ? i.Name : (h != null ? h.FullName : m.FullName));

            if (i == null)
            {
                //                    
                //				    I (index)                H        M        Result
                //			        -------------------------------------------------------
                //			        0 nothing             nothing  nothing  (does not happen)
                //			        1 nothing             nothing  exists   use M
                //			        2 nothing             exists   nothing  remove path from index
                //			        3 nothing             exists   exists   use M 

                if (h == null)
                {
                    _updated.Add(name, mId);
                }
                else if (m == null)
                {
                    Removed.Add(name);
                }
                else
                {
                    _updated.Add(name, mId);
                }
            }
            else if (h == null)
            {
                //                    
                //					  clean I==H  I==M       H        M        Result
                //			         -----------------------------------------------------
                //			        4 yes   N/A   N/A     nothing  nothing  keep index
                //			        5 no    N/A   N/A     nothing  nothing  keep index
                //			
                //			        6 yes   N/A   yes     nothing  exists   keep index
                //			        7 no    N/A   yes     nothing  exists   keep index
                //			        8 yes   N/A   no      nothing  exists   fail
                //			        9 no    N/A   no      nothing  exists   fail       

                if (m == null || mId.Equals(iId))
                {
                    if (HasParentBlob(_merge, name))
                    {
                        if (i.IsModified(_root, true))
                        {
                            Conflicts.Add(name);
                        }
                        else
                        {
                            Removed.Add(name);
                        }
                    }
                }
                else
                {
                    Conflicts.Add(name);
                }
            }
            else if (m == null)
            {
                //                    
                //					10 yes   yes   N/A     exists   nothing  remove path from index
                //			        11 no    yes   N/A     exists   nothing  fail
                //			        12 yes   no    N/A     exists   nothing  fail
                //			        13 no    no    N/A     exists   nothing  fail
                //					 

                if (hId.Equals(iId))
                {
                    if (i.IsModified(_root, true))
                    {
                        Conflicts.Add(name);
                    }
                    else
                    {
                        Removed.Add(name);
                    }
                }
                else
                {
                    Conflicts.Add(name);
                }
            }
            else
            {
                if (!hId.Equals(mId) && !hId.Equals(iId) && !mId.Equals(iId))
                {
                    Conflicts.Add(name);
                }
                else if (hId.Equals(iId) && !mId.Equals(iId))
                {
                    if (i.IsModified(_root, true))
                    {
                        Conflicts.Add(name);
                    }
                    else
                    {
                        _updated.Add(name, mId);
                    }
                }
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Adds or replaces a <see cref="TreeEntryDefinition"/>, built from the provided <see cref="TreeEntry"/>, at the specified <paramref name="targetTreeEntryPath"/> location.
        /// </summary>
        /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
        /// <param name="treeEntry">The <see cref="TreeEntry"/> to be stored at the described location.</param>
        /// <returns>The current <see cref="TreeDefinition"/>.</returns>
        public virtual TreeDefinition Add(string targetTreeEntryPath, TreeEntry treeEntry)
        {
            Ensure.ArgumentNotNull(treeEntry, "treeEntry");

            TreeEntryDefinition ted = TreeEntryDefinition.From(treeEntry);

            return Add(targetTreeEntryPath, ted);
        }
Ejemplo n.º 47
0
        private void OnButtonClick (UIComponent uiComponent,
            UIMouseEventParameter mouseEventParam)
        {
            // Get the global TreeManager singleton.
            if (!Singleton<TreeManager>.exists) {
                Util.Log("TreeManager doesn't exist for some reason.");
                return;
            }
            var tm = Singleton<TreeManager>.instance;
            Util.Log("TreeManager count: " + tm.m_treeCount.ToString());
/*
    So here's how trees in Cities: Skylines are stored.
    First, take a look at these three bare-bones "documentation" pages:
    - https://github.com/cities-skylines/Assembly-CSharp/wiki/TreeManager
    - https://github.com/cities-skylines/Assembly-CSharp/wiki/TreeInstance
    - https://github.com/cities-skylines/Assembly-CSharp/wiki/Array32%601
    
    TreeManager - or rather Singleton<TreeManager>.instance - keeps an Array32
    of TreeInstance objects (m_trees). Each tree is referred to by its index
    number in this Array32, with 0 meaning it doesn't exist. Unfortunately,
    Array32 is a sparse array that doesn't let us iterate over its items.
    Fortunately, looping over each possible index and checking the x/z coords
    against 0 does find all the trees with little to no problem.
    
    TreeManager also stores a 540x540 grid of tree indices (m_treeGrid), and
    each TreeInstance seems to hold an index to the "next" tree in its grid
    position (m_nextGridTree), but this isn't really useful for what I'm doing.
*/ 
            var trees = tm.m_trees;
            var treeEntries = new TreeEntry[tm.m_treeCount];
            var toRemove = new uint[tm.m_treeCount];

            uint treeEntryCount = 0;
            uint toRemoveCount = 0;

            for (uint i=1; i < trees.m_size; i++) {
                short x = trees.m_buffer[i].m_posX;
                short z = trees.m_buffer[i].m_posZ;
                if (x != 0 || z != 0) {
                    // Search through treeEntries for an entry with the same
                    // x and z values.
                    bool treeEntryMatched = false;
                    for (uint j=0; j < treeEntryCount; j++) {
                        if (treeEntries[j].x == x && treeEntries[j].z == z) {
                            treeEntryMatched = true;
                            break;
                        }
                    }
                    // If the tree does overlap with one we've already found,
                    // queue it up for removal. If not, add it to treeEntries.
                    if (treeEntryMatched) {
                        toRemove[toRemoveCount] = i;
                        toRemoveCount++;
                    } else {
                        treeEntries[treeEntryCount].id = i;
                        treeEntries[treeEntryCount].x = x;
                        treeEntries[treeEntryCount].z = z;
                        treeEntryCount++;
                    }
                }
            }

            Util.Log(treeEntryCount.ToString() + " single trees found.");
            Util.Log(toRemoveCount.ToString() + " duplicate trees found.");

            if (toRemoveCount > 0) {
                var oldCount = tm.m_treeCount;
                for (uint i=0; i < toRemoveCount; i++) {
                    tm.ReleaseTree(toRemove[i]);
                }
                var newCount = tm.m_treeCount;
                if (oldCount == newCount) {
                    Util.Log("Failed to remove the duplicate trees.");
                } else {
                    if (newCount == treeEntryCount) {
                        Util.Log(toRemoveCount.ToString() +
                            " trees removed successfully.");
                    } else {
                        Util.Log("Something went wrong.");
                        Util.Log("oldCount = " + oldCount.ToString());
                        Util.Log("newCount = " + newCount.ToString());
                    }
                }
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// The find parent for item.
        /// </summary>
        /// <param name="current">
        /// The current.
        /// </param>
        /// <param name="item">
        /// The item.
        /// </param>
        /// <returns>
        /// The <see cref="TreeEntry"/>.
        /// </returns>
        private TreeEntry FindParentForItem(TreeEntry current, TreeItem item)
        {
            var segments = item.Text == null ? -1 : item.Text.Split('.').Length;
            if (current.SegmentCount == segments - 1 && item.Text.StartsWith(current.FullName))
            {
                return current;
            }

            foreach (var child in current.Children)
            {
                var result = this.FindParentForItem(child, item);
                if (result != null)
                {
                    return result;
                }
            }

            return null;
        }
Ejemplo n.º 49
0
        /// <summary>
        /// The backfill parents for item.
        /// </summary>
        /// <param name="root">
        /// The root.
        /// </param>
        /// <param name="item">
        /// The item.
        /// </param>
        private void BackfillParentsForItem(TreeEntry root, TreeItem item)
        {
            var segments = item.Text.Split('.').Reverse().Where((x, id) => id >= 1).Reverse().ToArray();
            var current = root;
            var i = 1;
            var built = string.Empty;
            foreach (var segment in segments)
            {
                built += "." + segment;
                built = built.Trim('.');
                var next = current.Children.FirstOrDefault(x => x.Name == segment);
                if (next == null)
                {
                    var newItem = new TreeItem { Text = built, Parent = this };
                    this.m_Items.Add(newItem);
                    var created = new TreeEntry
                    {
                        Item = newItem,
                        Layout = null,
                        Name = segment,
                        FullName = built,
                        Children = new List<TreeEntry>(),
                        SegmentCount = i
                    };
                    current.Children.Add(created);
                    current = created;
                }
                else
                {
                    current = next;
                }

                i++;
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// The normalize tree.
        /// </summary>
        /// <param name="tree">
        /// The tree.
        /// </param>
        /// <param name="exclude">
        /// The exclude.
        /// </param>
        /// <returns>
        /// The <see cref="List{TreeEntry}"/>.
        /// </returns>
        public List<TreeEntry> NormalizeTree(TreeEntry tree, bool exclude)
        {
            var list = new List<TreeEntry>();
            if (!exclude)
            {
                list.Add(tree);
            }

            foreach (var child in tree.Children)
            {
                list.AddRange(this.NormalizeTree(child, false));
            }

            return list;
        }
Ejemplo n.º 51
0
 private void AddTreeEntry(Tree tree, TreeEntry entry)
 {
     if (entry.Target is Tree)
     {
         AddTree(entry.Target as Tree);
     }
     else if (entry.Target is Blob)
     {
         AddBlob(entry.Target as Blob);
     }
     else
     {
         throw new NotSupportedException("Invalid tree entry, not supported: " + entry.Target.GetType());
     }
     var edge = new GraphContents.Edge {Source = tree.Sha, Target = entry.Target.Sha, Tag = entry.Name};
     _contents.AddEdge(edge);
 }
Ejemplo n.º 52
0
 public static FileStatusViewModel FromTreeEntry(TreeEntry entry)
 {
     return new FileStatusViewModel() {
         Path = entry.Path,
         State = RepositoryFileStatus.Added
     };
 }
Ejemplo n.º 53
0
 private static void AssertBlobContent(TreeEntry entry, string expectedContent)
 {
     Assert.Equal(GitObjectType.Blob, entry.Type);
     Assert.Equal(expectedContent, ((Blob)(entry.Target)).ContentAsUtf8());
 }
Ejemplo n.º 54
0
 private static void AssertBlobContent(TreeEntry entry, string expectedContent)
 {
     Assert.Equal(TreeEntryTargetType.Blob, entry.TargetType);
     Assert.Equal(expectedContent, ((Blob)(entry.Target)).GetContentText());
 }
Ejemplo n.º 55
0
		private static int BinarySearch(TreeEntry[] entries, byte[] nameUTF8, int nameUTF8Last, int nameStart, int nameEnd)
		{
			if (entries.Length == 0) return -1;

			int high = entries.Length;
			int low = 0;
			do
			{
			    int mid = (int) (((uint) (low + high)) >> 1);
				int cmp = CompareNames(entries[mid].NameUTF8, nameUTF8,
					nameStart, nameEnd, GitSharp.Core.TreeEntry.LastChar(entries[mid]), nameUTF8Last);

				if (cmp < 0)
				{
					low = mid + 1;
				}
				else if (cmp == 0)
				{
					return mid;
				}
				else
				{
					high = mid;
				}

			} while (low < high);
			return -(low + 1);
		}
Ejemplo n.º 56
0
 protected override void AddTreeEntry(string path, TreeEntry entry, DateTimeOffset modificationTime)
 {
     Files.Add(new { Path = path, entry.Target.Sha });
 }
Ejemplo n.º 57
0
		private void InsertEntry(int p, TreeEntry e)
		{
			TreeEntry[] c = _contents;
			var n = new TreeEntry[c.Length + 1];

			p = -(p + 1);
			for (int k = c.Length - 1; k >= p; k--)
			{
				n[k + 1] = c[k];
			}

			n[p] = e;
			for (int k = p - 1; k >= 0; k--)
			{
				n[k] = c[k];
			}

			_contents = n;

			SetModified();
		}
Ejemplo n.º 58
0
 /// <summary>
 /// Implements the archiving of a TreeEntry in a given format.
 /// </summary>
 /// <param name="path">The path of the entry in the archive.</param>
 /// <param name="entry">The entry to archive.</param>
 /// <param name="modificationTime">The datetime the entry was last modified.</param>
 protected abstract void AddTreeEntry(string path, TreeEntry entry, DateTimeOffset modificationTime);
Ejemplo n.º 59
0
		private void ReadTree(byte[] raw)
		{
			int rawSize = raw.Length;
			int rawPtr = 0;
			int nextIndex = 0;

			while (rawPtr < rawSize)
			{
				while (rawPtr < rawSize && raw[rawPtr] != 0)
				{
					rawPtr++;
				}

				rawPtr++;
				rawPtr += Constants.OBJECT_ID_LENGTH;
				nextIndex++;
			}

			var temp = new TreeEntry[nextIndex];
			rawPtr = 0;
			nextIndex = 0;

			while (rawPtr < rawSize)
			{
				int c = raw[rawPtr++];
				if (c < '0' || c > '7')
				{
					throw new CorruptObjectException(Id, "invalid entry mode");
				}

				int mode = c - '0';

				while (true)
				{
					c = raw[rawPtr++];
					if (' ' == c) break;

					if (c < '0' || c > '7')
					{
						throw new CorruptObjectException(Id, "invalid mode");
					}

					mode <<= 3;
					mode += c - '0';
				}

				int nameLen = 0;
				while (raw[rawPtr + nameLen] != 0)
				{
					nameLen++;
				}

				var name = new byte[nameLen];
				Array.Copy(raw, rawPtr, name, 0, nameLen);
				rawPtr += nameLen + 1;

				ObjectId id = ObjectId.FromRaw(raw, rawPtr);
				rawPtr += Constants.OBJECT_ID_LENGTH;

				TreeEntry ent;
				if (FileMode.RegularFile.Equals(mode))
				{
					ent = new FileTreeEntry(this, id, name, false);
				}
				else if (FileMode.ExecutableFile.Equals(mode))
				{
					ent = new FileTreeEntry(this, id, name, true);
				}
				else if (FileMode.Tree.Equals(mode))
				{
					ent = new Tree(this, id, name);
				}
                else if (FileMode.Symlink.Equals(mode))
                {
                    ent = new SymlinkTreeEntry(this, id, name);
                }
                else if (FileMode.GitLink.Equals(mode))
                {
                    ent = new GitLinkTreeEntry(this, id, name);
                }
				else
				{
					throw new CorruptObjectException(Id, "Invalid mode: " + Convert.ToString(mode, 8));
				}

				temp[nextIndex++] = ent;
			}

			_contents = temp;
		}
Ejemplo n.º 60
0
 private static void AssertBlobContent(TreeEntry entry, string expectedContent)
 {
     entry.Type.ShouldEqual(GitObjectType.Blob);
     ((Blob)(entry.Target)).ContentAsUtf8().ShouldEqual(expectedContent);
 }