Ejemplo n.º 1
0
        public string CreateTempDirectoryFromDiff(GitDiff diff)
        {
            // checkout correct branch
            var tempDirectory = CopyTree(diff);

            return(tempDirectory);
        }
Ejemplo n.º 2
0
        private bool TryParseChunks(GitDiff result)
        {
            var rawChunkHeader = _reader.ReadLine();

            while (null != rawChunkHeader && GitDiffChunk.ChunkFirstSymbol == rawChunkHeader[0])
            {
                var chunk = new GitDiffChunk();
                var line  = _reader.ReadLine();
                while (null != line)
                {
                    if (!String.IsNullOrWhiteSpace(line))
                    {
                        if (GitDiffChunk.ChunkFirstSymbol == line[0])
                        {
                            break;
                        }

                        switch (line[0])
                        {
                        case '+': chunk.AddedLines++; break;

                        case '-': chunk.RemovedLines++; break;
                        }
                    }
                    line = _reader.ReadLine();
                }
                result.AddChunk(chunk);

                rawChunkHeader = line;
            }

            return(true);
        }
Ejemplo n.º 3
0
        internal GitDiff Parse()
        {
            Func <GitDiff, bool>[] stages = GetParsingStages();

            var result       = new GitDiff();
            var stageResults = stages.TakeWhile(s => s(result)).ToArray();

            bool isValid = stages.Length == stageResults.Length;

            return(isValid ? result : null);
        }
Ejemplo n.º 4
0
        private bool TryReadMarkers(GitDiff diff)
        {
            bool result = false;

            var leftMarkers  = GetMarkerLineParts();
            var rightMarkers = GetMarkerLineParts();

            if (null != leftMarkers && null != rightMarkers)
            {
                diff.LeftMarker  = new GitDiffMarker(leftMarkers[(int)MarkerLineParts.MarkerSymbol]);
                diff.RightMarker = new GitDiffMarker(rightMarkers[(int)MarkerLineParts.MarkerSymbol]);

                result = true;
            }

            return(result);
        }
Ejemplo n.º 5
0
        private bool TryReadMetadata(GitDiff diff)
        {
            bool result = false;

            var rawMetadata = _reader.ReadLine();

            if (!String.IsNullOrWhiteSpace(rawMetadata))
            {
                diff.Metadata = rawMetadata;
                if (!rawMetadata.StartsWith("index"))
                {
                    diff.Metadata += Environment.NewLine;
                    diff.Metadata += _reader.ReadLine();
                }
                result = true;
            }

            return(result);
        }
Ejemplo n.º 6
0
        public static GitDiff FakeDiffFor(string path, string tempDirectory)
        {
            var root = CopyFakeRepoToTempDirectory(path, tempDirectory);

            var tempDirWithoutDrive = tempDirectory.Replace(root, "\\");
            var filesInTempDir      = Directory.GetFiles(tempDirectory);
            var testFiles           = new List <string>();

            foreach (var file in filesInTempDir)
            {
                testFiles.Add(file);
            }

            var gd = new GitDiff {
                RootPath = tempDirectory
            };

            gd.AddRange(testFiles.Select(file => "/" + file.Replace(root, "").Replace(@"\", "/")));
            return(gd);
        }
Ejemplo n.º 7
0
        private bool TryReadInputSources(GitDiff diff)
        {
            bool result = false;

            var rawInputSources = _reader.ReadLine();

            if (!String.IsNullOrWhiteSpace(rawInputSources))
            {
                var parts = rawInputSources.Split(_delimeter, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == (int)InputSourcesLineParts.TotalNumberOfParts)
                {
                    diff.InputSources = rawInputSources;
                    diff.LeftInput    = parts[(int)InputSourcesLineParts.LeftFile];
                    diff.RightInput   = parts[(int)InputSourcesLineParts.RightFile];
                }

                result = true;
            }

            return(result);
        }
Ejemplo n.º 8
0
        private string CopyTree(GitDiff diff)
        {
            var windowsPaths  = diff.ToWindowsPaths();
            var tempDirectory = TempDirectory.Create("ForcePushBundler");

            foreach (var path in windowsPaths)
            {
                var filePath = Path.GetFullPath(path);

                var relativePath      = filePath.Replace(diff.RootPath, "");
                var relativeDirectory = (Path.GetDirectoryName(relativePath) ?? "").TrimStart('\\');

                Copy.CreateRelativePathInDestination(tempDirectory, relativePath);

                var fileName     = Path.GetFileName(path);
                var fullPath     = Path.Combine(tempDirectory, relativeDirectory, fileName);
                var destFileName = Path.Combine(tempDirectory, fullPath);
                File.Copy(path, destFileName);
            }

            _output.WriteLine($"Copyed modified files into staging area '{tempDirectory}'.");
            return(tempDirectory);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Log the graph in graphviz (dot) format.
        /// </summary>
        /// <param name="graph">Graph to log</param>
        /// <remarks>
        /// Example of a graphviz graph description
        ///
        /// digraph graphname {
        ///    a -> b -> c;
        ///    b -> d;
        /// }
        ///
        /// For more info see https://www.graphviz.org/
        /// </remarks>
        /// <returns>Async task</returns>
        private async Task LogGraphViz(DependencyGraph graph)
        {
            using (StreamWriter writer = UxHelpers.GetOutputFileStreamOrConsole(_options.GraphVizOutputFile))
            {
                await writer.WriteLineAsync("digraph repositoryGraph {");

                await writer.WriteLineAsync("    node [shape=record]");

                foreach (DependencyGraphNode node in graph.Nodes)
                {
                    StringBuilder nodeBuilder = new StringBuilder();

                    // First add the node name
                    nodeBuilder.Append($"    {UxHelpers.CalculateGraphVizNodeName(node)}");

                    // Then add the label.  label looks like [label="<info here>"]
                    nodeBuilder.Append("[label=\"");

                    // Append friendly repo name
                    nodeBuilder.Append(UxHelpers.GetSimpleRepoName(node.Repository));
                    nodeBuilder.Append(@"\n");

                    // Append short commit sha
                    nodeBuilder.Append(node.Commit.Substring(0, node.Commit.Length < 10 ? node.Commit.Length : 10));

                    // Append a build string (with newline) if available
                    if (node.ContributingBuilds != null && node.ContributingBuilds.Any())
                    {
                        Build newestBuild = node.ContributingBuilds.OrderByDescending(b => b.DateProduced).First();
                        nodeBuilder.Append($"\\n{newestBuild.DateProduced.ToString("g")} (UTC)");
                    }

                    // Append a diff string if the graph contains diff info.
                    GitDiff diffFrom = node.DiffFrom;
                    if (diffFrom != null)
                    {
                        if (!diffFrom.Valid)
                        {
                            nodeBuilder.Append("\\ndiff unknown");
                        }
                        else if (diffFrom.Ahead != 0 || diffFrom.Behind != 0)
                        {
                            if (node.DiffFrom.Ahead != 0)
                            {
                                nodeBuilder.Append($"\\nahead: {node.DiffFrom.Ahead} commits");
                            }
                            if (node.DiffFrom.Behind != 0)
                            {
                                nodeBuilder.Append($"\\nbehind: {node.DiffFrom.Behind} commits");
                            }
                        }
                        else
                        {
                            nodeBuilder.Append("\\nlatest");
                        }
                    }

                    // Append end of label and end of node.
                    nodeBuilder.Append("\"];");

                    // Write it out.
                    await writer.WriteLineAsync(nodeBuilder.ToString());

                    // Now write the edges
                    foreach (DependencyGraphNode childNode in node.Children)
                    {
                        await writer.WriteLineAsync($"    {UxHelpers.CalculateGraphVizNodeName(node)} -> {UxHelpers.CalculateGraphVizNodeName(childNode)}");
                    }
                }

                await writer.WriteLineAsync("}");
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        ///     Log basic node details that are common to flat/normal and coherency
        ///     path views
        /// </summary>
        /// <param name="node">Node</param>
        /// <param name="indent">Indentation</param>
        /// <example>
        ///       - Repo:     https://github.com/dotnet/wpf
        ///         Commit:   99112590688a44837276e20e9c91ef41fd54c64b
        ///         Delta:    latest
        ///         Builds:
        ///         - 20190228.4 (2/28/2019 12:57 PM)
        /// </example>
        private async Task LogBasicNodeDetails(StreamWriter writer, DependencyGraphNode node, string indent)
        {
            await writer.WriteLineAsync($"{indent}- Repo:     {node.Repository}");

            await writer.WriteLineAsync($"{indent}  Commit:   {node.Commit}");

            StringBuilder deltaString = new StringBuilder($"{indent}  Delta:    ");
            GitDiff       diffFrom    = node.DiffFrom;

            // Log the delta. Depending on user options, deltas from latest build,
            // other builds in the graph, etc. may have been calculated as part of the
            // graph build.  The delta is a diff in a node commit and another commit.
            // For the purposes of the user display for the dependency graph, we really
            // only care about the ahead/behind information.

            if (diffFrom != null)
            {
                if (diffFrom.Valid)
                {
                    if (diffFrom.Ahead != 0 || diffFrom.Behind != 0)
                    {
                        if (diffFrom.Ahead != 0)
                        {
                            deltaString.Append($"ahead {diffFrom.Ahead}");
                        }
                        if (diffFrom.Behind != 0)
                        {
                            if (diffFrom.Ahead != 0)
                            {
                                deltaString.Append(", ");
                            }
                            deltaString.Append($"behind {diffFrom.Behind}");
                        }
                        deltaString.Append($" commits vs. {diffFrom.BaseVersion}");
                    }
                    else
                    {
                        deltaString.Append("latest");
                    }
                }
                else
                {
                    deltaString.Append("unknown");
                }
                await writer.WriteLineAsync(deltaString.ToString());
            }
            if (node.ContributingBuilds != null)
            {
                if (node.ContributingBuilds.Any())
                {
                    await writer.WriteLineAsync($"{indent}  Builds:");

                    foreach (var build in node.ContributingBuilds)
                    {
                        await writer.WriteLineAsync($"{indent}  - {build.AzureDevOpsBuildNumber} ({build.DateProduced.ToLocalTime().ToString("g")})");
                    }
                }
                else
                {
                    await writer.WriteLineAsync($"{indent}  Builds: []");
                }
            }
        }
Ejemplo n.º 11
0
        void DoGit(int dirNestingLevel)
        {
            if (fOld_)
            {
                goto JustDiff;
            }
            process = new Process();
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.FileName  = "git";
            process.StartInfo.Arguments = "diff --raw";
            Console.WriteLine("Executing {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            string dirPrefix = "";

            while (dirNestingLevel > 0)
            {
                dirPrefix += "..\\";
                --dirNestingLevel;
            }

            try
            {
                process.Start();
            }
            catch (Win32Exception)
            {
                // git not installed
                Console.WriteLine("Couldn't execute '{0} {1}', is git installed and available in command line?", process.StartInfo.FileName, process.StartInfo.Arguments);
                return;
            }

            string s        = process.StandardOutput.ReadToEnd();
            var    fileList = GitDiff.ParseDiffOut(s);

            if (0 == fileList.Count)
            {
                Console.WriteLine("There are no diffs!");
                return;
            }
            PrepareTempDirs();

            for (int i = 0; i < fileList.Count; i++)
            {
                var fi         = fileList[i];
                var rev        = fi.Revision;
                var fileNameIn = fi.FileName;

                /* strip trailing "..." from the end since git show
                 * interprets them as range */
                rev = rev.Trim(".".ToCharArray());
                //Console.WriteLine("Will show {0}", rev);
                string fileNameOut  = fileNameIn.Replace(@"/", @"\");
                string pathOutAfter = System.IO.Path.Combine(tempDirAfter, fileNameOut);
                EnsureDirForFilePathExists(pathOutAfter);

                // copy working copy to tempDirAfter
                string fileNameOutToCopy = dirPrefix + fileNameOut;
                //Console.WriteLine("file: " + fileNameOutToCopy);
                if (File.Exists(fileNameOutToCopy))
                {
                    File.Copy(fileNameOutToCopy, pathOutAfter);
                }
                else
                {
                    Console.WriteLine("file: '{0}' doesn't exist", fileNameOutToCopy);
                }

                // copy revision to tempDirBefore
                string pathOutBefore = System.IO.Path.Combine(tempDirBefore, fileNameOut);
                EnsureDirForFilePathExists(pathOutBefore);

                FileStream streamOut = File.OpenWrite(pathOutBefore);

                Stream streamIn = GitDiff.GetRevisionStream(rev);
                int    bufSize  = 2048;
                byte[] buf      = new byte[bufSize];
                int    read;
                while (true)
                {
                    read = streamIn.Read(buf, 0, bufSize);
                    if (0 == read)
                    {
                        break; // end of file
                    }
                    streamOut.Write(buf, 0, read);
                }
                streamOut.Close();
            }

JustDiff:
            process = new Process();
            process.StartInfo.UseShellExecute        = true;
            process.StartInfo.RedirectStandardOutput = false;
            process.StartInfo.FileName = diffProgram_;
            // TODO: only escape tempDirBefore and tempDirAfter if necessary
            process.StartInfo.Arguments = String.Format("\"{0}\" \"{1}\"", tempDirBefore, tempDirAfter);
            Console.WriteLine("Executing {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            try
            {
                process.Start();
            }
            catch (Win32Exception)
            {
                Console.WriteLine("Couldn't execute '{0}'", diffProgram_);
            }
        }