コード例 #1
0
    public static void DiffLocal()
    {
        Process p      = GitCommand("diff --numstat");
        string  output = p.StandardOutput.ReadToEnd(),
                error  = p.StandardError.ReadToEnd();

        if (error.Length > 0)
        {
            UnityEngine.Debug.Log(error);
        }

        string[] lines = output.Split(new char[] { System.Environment.NewLine[0], System.Environment.NewLine[1] });
        head = new GitFile[lines.Length - 1];

        for (int i = 0; i < lines.Length - 1; i++)
        {
            head[i] = new GitFile();
            string[] a = lines[i].Split('	');
            head[i].additions = System.Convert.ToInt32(a[0]);
            head[i].deletions = System.Convert.ToInt32(a[1]);
            head[i].path      = a[2];
            head[i].GetChanges();
        }

        p.WaitForExit();
        p.Close();
    }
コード例 #2
0
        public async Task UpdatePackageSourcesTests(string testName, string[] managedFeeds)
        {
            GitFileManager gitFileManager = new GitFileManager(null, NullLogger.Instance);

            string inputNugetPath = Path.Combine(
                Environment.CurrentDirectory,
                TestInputsRootDir,
                ConfigFilesInput,
                testName,
                InputNugetConfigFile);
            string inputXmlContent = await File.ReadAllTextAsync(inputNugetPath);

            var inputNuGetConfigFile = GitFileManager.ReadXmlFile(inputXmlContent);

            XmlDocument updatedConfigFile =
                gitFileManager.UpdatePackageSources(inputNuGetConfigFile, new HashSet <string>(managedFeeds));

            var outputNugetPath = Path.Combine(
                Environment.CurrentDirectory,
                TestInputsRootDir,
                ConfigFilesInput,
                testName,
                OutputNugetConfigFile);
            string expectedOutputText = await File.ReadAllTextAsync(outputNugetPath);

            // Dump the output xml using the git file manager
            GitFile file = new GitFile(null, updatedConfigFile);

            // Normalize the \r\n newlines in the expected output to \n if they
            // exist (GitFile normalizes these before writing)
            expectedOutputText = expectedOutputText.Replace(Environment.NewLine, "\n");

            Assert.Equal(expectedOutputText, file.Content);
        }
コード例 #3
0
        public static IEnumerable <GitFile> Load(
            string filter      = null,
            string dir         = null,
            LfxFileFlags flags = LfxFileFlags.Default)
        {
            GitFileFlags gitFlags = default(GitFileFlags);

            if ((flags & LfxFileFlags.Tracked) != 0)
            {
                gitFlags |= GitFileFlags.Tracked;
            }

            if ((flags & LfxFileFlags.Untracked) != 0)
            {
                gitFlags |= GitFileFlags.Untracked;
            }

            var lfxFiles = GitFile.Load(filter, dir, gitFlags)
                           .Where(o => o.IsDefined("filter", "lfx"));

            if ((flags & LfxFileFlags.Content) != 0)
            {
                lfxFiles = lfxFiles.Where(o => !LfxPointer.CanLoad(o.Path));
            }

            if ((flags & LfxFileFlags.Pointer) != 0)
            {
                lfxFiles = lfxFiles.Where(o => LfxPointer.CanLoad(o.Path));
            }

            return(lfxFiles);
        }
コード例 #4
0
        /// <summary>
        /// Adds a file to the repo's index respecting the original file's mode.
        /// </summary>
        /// <param name="repo">Repo to add the files to</param>
        /// <param name="file">Original GitFile to add</param>
        /// <param name="fullPath">Final path for the file to be added</param>
        /// <param name="log">Logger</param>
        internal static void AddFileToIndex(Repository repo, GitFile file, string fullPath, ILogger log)
        {
            var fileMode = (Mode)Convert.ToInt32(file.Mode, 8);

            if (!Enum.IsDefined(typeof(Mode), fileMode) || fileMode == Mode.Nonexistent)
            {
                log.LogInformation($"Could not detect file mode {file.Mode} for file {file.FilePath}. Assigning non-executable mode.");
                fileMode = Mode.NonExecutableFile;
            }
            Blob fileBlob = repo.ObjectDatabase.CreateBlob(fullPath);

            repo.Index.Add(fileBlob, file.FilePath, fileMode);
        }
コード例 #5
0
        public async Task UpdatePackageSourcesTests(string testName, string[] managedFeeds)
        {
            GitFileManager gitFileManager = new GitFileManager(null, NullLogger.Instance);

            string inputNugetPath = Path.Combine(
                Environment.CurrentDirectory,
                TestInputsRootDir,
                ConfigFilesInput,
                testName,
                InputNugetConfigFile);
            string inputXmlContent = await File.ReadAllTextAsync(inputNugetPath);

            var inputNuGetConfigFile = GitFileManager.ReadXmlFile(inputXmlContent);

            Dictionary <string, HashSet <string> > configFileUpdateData = new Dictionary <string, HashSet <string> >();

            configFileUpdateData.Add("testKey", new HashSet <string>(managedFeeds));
            var managedFeedsForTest = gitFileManager.FlattenLocationsAndSplitIntoGroups(configFileUpdateData);

            // 'unknown' = regex failed to match and extract repo name from feed
            managedFeedsForTest.Keys.Should().NotContain("unknown");

            XmlDocument updatedConfigFile =
                gitFileManager.UpdatePackageSources(inputNuGetConfigFile, managedFeedsForTest);

            var outputNugetPath = Path.Combine(
                Environment.CurrentDirectory,
                TestInputsRootDir,
                ConfigFilesInput,
                testName,
                OutputNugetConfigFile);
            string expectedOutputText = await File.ReadAllTextAsync(outputNugetPath);

            // Dump the output xml using the git file manager
            GitFile file = new GitFile(null, updatedConfigFile);

            // Normalize the \r\n newlines in the expected output to \n if they
            // exist (GitFile normalizes these before writing)
            expectedOutputText = expectedOutputText.Replace(Environment.NewLine, "\n");

            file.Content.Should().Be(expectedOutputText);

            // When this is performed via the Maestro service instead of the Darc CLI, it seemingly can
            // be run more than once for the same XmlDocument.  This should not impact the contents of the file;
            // Validate this expectation of idempotency by running the same update on the resultant file.
            XmlDocument doubleUpdatedConfigFile = gitFileManager.UpdatePackageSources(updatedConfigFile, managedFeedsForTest);
            GitFile     doubleUpdatedfile       = new GitFile(null, doubleUpdatedConfigFile);

            doubleUpdatedfile.Content.Should().Be(expectedOutputText, "Repeated invocation of UpdatePackageSources() caused incremental changes to nuget.config");
        }
コード例 #6
0
        private async Task <ImageArtifactDetails> GetImageInfoForSubscriptionAsync(Subscription subscription, ManifestInfo manifest)
        {
            string imageDataJson;

            using (IGitHubClient gitHubClient = _gitHubClientFactory.GetClient(Options.GitOptions.ToGitHubAuth(), Options.IsDryRun))
            {
                GitHubProject project = new GitHubProject(subscription.ImageInfo.Repo, subscription.ImageInfo.Owner);
                GitHubBranch  branch  = new GitHubBranch(subscription.ImageInfo.Branch, project);

                GitFile repo = subscription.Manifest;
                imageDataJson = await gitHubClient.GetGitHubFileContentsAsync(subscription.ImageInfo.Path, branch);
            }

            return(ImageInfoHelper.LoadFromContent(imageDataJson, manifest, skipManifestValidation: true));
        }
コード例 #7
0
        async Task <SaveResult> CreateOrUpdateGithubPost(string postTitle, string content, IEnumerable <FileReference> referencedFiles, BlogSetting blog)
        {
            var treeToUpload   = new GitTree();
            var imagesToUpload = referencedFiles.Where(f => !f.Saved).ToList();

            if (imagesToUpload.Count > 0)
            {
                foreach (var imageToUpload in imagesToUpload)
                {
                    var imageContent = Convert.ToBase64String(File.ReadAllBytes(imageToUpload.FullPath));
                    var item         = new GitFile
                    {
                        type    = "tree",
                        path    = imageToUpload.FullPath,
                        mode    = ((int)GitTreeMode.SubDirectory),
                        content = imageContent
                    };

                    treeToUpload.tree.Add(item);
                }
            }

            var gitFile = new GitFile
            {
                path    = postTitle,
                content = content,
                mode    = (int)GitTreeMode.File,
                type    = "blob"
            };

            treeToUpload.tree.Add(gitFile);

            var newTree = await githubApi.NewTree(blog.Token, blog.Username, blog.WebAPI, blog.BlogInfo.blogid, treeToUpload);

            var uploadedFile = newTree.Item1.tree.Single(t => t.path == gitFile.path);

            foreach (var fileReference in imagesToUpload)
            {
                fileReference.Saved = true;
            }

            return(new SaveResult
            {
                Id = uploadedFile.sha,
                NewDocumentContent = content
            });
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: UsmanMohammad/YGOPro2_MRTK
    private void DownloadGitFile(string id, GitNode file, string folderPath)
    {
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            throw new Exception("Internet error");
        }
        GitFile download = RequestFromGit <GitFile>(id, file.path);

        byte[] bytes        = Convert.FromBase64String(download.content);
        string downloadFile = Path.Combine(folderPath, file.path);
        string downloadDir  = ShaCache.ToContaingFolder(downloadFile);

        if (!Directory.Exists(downloadDir))
        {
            Directory.CreateDirectory(downloadDir);
        }
        File.WriteAllBytes(downloadFile, bytes);
        localSha.UpdateInsertCache(downloadFile, file.id);
    }
コード例 #9
0
        async Task <string> CreateOrUpdateGithubPost(string postTitle, string content,
                                                     ICollection <string> imagesToUpload, BlogSetting blog)
        {
            var treeToUpload = new GitTree();

            if (imagesToUpload.Count > 0)
            {
                foreach (var imageToUpload in imagesToUpload)
                {
                    var imageContent = Convert.ToBase64String(File.ReadAllBytes(imageToUpload));
                    var item         = new GitFile
                    {
                        type    = "tree",
                        path    = imageToUpload,
                        mode    = ((int)GitTreeMode.SubDirectory),
                        content = imageContent
                    };
                    treeToUpload.tree.Add(item);
                }
            }

            var gitFile = new GitFile
            {
                path    = postTitle,
                content = content,
                mode    = (int)GitTreeMode.File,
                type    = "blob"
            };

            treeToUpload.tree.Add(gitFile);

            var newTree = await githubApi.NewTree(blog.Token, blog.Username, blog.WebAPI, blog.BlogInfo.blogid, treeToUpload);

            var uploadedFile = newTree.Item1.tree.Single(t => t.path == gitFile.path);

            return(uploadedFile.sha);
        }
コード例 #10
0
 /// <summary>
 /// 创建处理目标
 /// </summary>
 /// <returns></returns>
 public IExcuteTarget CreateTarget()
 {
     if (Value.Contains(CommandParser.ParamterSplit))
     {
         var           p              = Value.Split(CommandParser.ParamterSplit[0]);
         string        dir            = p[0];
         string        searchConditon = p[1];
         var           files          = searchConditon.GetFiles(dir);
         IExcuteTarget targetHeader   = null;
         IExcuteTarget targetTail     = null;
         for (int index = 0, length = files.Count; index < length; index++)
         {
             if (index == 0)
             {
                 var         commandPair   = new CommandPair("-f", files[index]);
                 IKeySetting fileSearchKey = KeyFactory.Instance.CreateBy(commandPair);
                 targetHeader = ((ITarget)fileSearchKey).CreateTarget();
                 targetTail   = targetHeader;
             }
             else
             {
                 var         commandPair   = new CommandPair("-f", files[index]);
                 IKeySetting fileSearchKey = KeyFactory.Instance.CreateBy(commandPair);
                 targetTail.NextTarget = ((ITarget)fileSearchKey).CreateTarget();
                 targetTail            = targetTail.NextTarget;
             }
         }
         return(targetHeader);
     }
     //当时文件的情况
     if (File.Exists(Value))
     {
         var target = new GitFile(Value, CommandExcute);
         return(target);
     }
     return(default(IExcuteTarget));
 }
コード例 #11
0
ファイル: CommitFile.cs プロジェクト: waie123/GitMind
 public CommitFile(GitFile gitFile, GitConflictFile conflict = null)
 {
     this.gitFile = gitFile;
     Conflict     = conflict ??
                    new GitConflictFile(null, gitFile.FilePath, null, null, null, GitFileStatus.Modified);
 }
コード例 #12
0
        public async Task <int> RunAsync(CommandLineArgs args)
        {
            var index   = 1;
            var commits = _Git.GetTotalCommits().Each(x => x.Index = index++);

            Print(commits);

            int n;

            while ((n = ReadIgnore(commits.Length)) != 0)
            {
                switch (n)
                {
                case -1:
                {
                    Print(commits);
                    break;
                }

                case -2:
                {
                    Console.WriteLine("your input is not valid.");
                    break;
                }

                default:
                {
                    index   = 1;
                    commits = commits.Remove(x => x.Index == n).Each(x => x.Index = index++);
                    Print(commits);
                    break;
                }
                }
            }

            var files = new GitFile[0];

            index = 0;
            Console.Write($"\r1st phrase: {index++}/{commits.Length}");

            foreach (var commit in commits.OrderBy(x => x.Date))
            {
                var changes = _Git.GetCommitDetail(commit.Id);
                foreach (var change in changes)
                {
                    var exists = files.FirstOrDefault(x => x.Path.EqualsIgnoreCase(change.Path));

                    if (exists == null)
                    {
                        var file = new GitFile()
                        {
                            InitialCommit = commit,
                            LatestCommit  = commit,
                            InitialAction = change.Action,
                            LatestAction  = change.Action,
                            Path          = change.Path,
                        };
                        files = files.Append(file);
                    }
                    else
                    {
                        exists.LatestCommit = commit;
                        exists.LatestAction = change.Action;
                    }
                }

                Console.Write($"\r1st phrase: {index++}/{commits.Length}");
            }

            // A -> A -> A: N/A
            // A -> A -> M: N/A
            // A -> A -> D: N/A
            // A -> M -> A: Compare
            // A -> M -> M: Compare
            // A -> M -> D: Delete
            // A -> D -> A: Compare
            // A -> D -> M: Compare
            // A -> D -> D: Delete
            // M -> A -> A: N/A
            // M -> A -> M: N/A
            // M -> A -> D: N/A
            // M -> M -> A: Compare
            // M -> M -> M: Compare
            // M -> M -> D: Delete
            // M -> D -> A: Compare
            // M -> D -> M: Compare
            // M -> D -> D: Delete
            // . -> A -> A: Add
            // . -> A -> M: Add
            // . -> A -> D: Ignore

            index = 0;
            ClearCurrentLine();

            foreach (var file in files)
            {
                Console.Write($"\r2nd phrase: {index++}/{files.Length}");

                if ((file.InitialAction == "M" && file.LatestAction == "A") ||
                    (file.InitialAction == "M" && file.LatestAction == "M") ||
                    (file.InitialAction == "D" && file.LatestAction == "A") ||
                    (file.InitialAction == "D" && file.LatestAction == "M"))
                {
                    var commit = _Git.GetFileHistory(file.Path, file.InitialCommit);
                    if (commit != null)
                    {
                        file.HistoryCommit = commit;

                        var historyContent = _Git.GetFileContent(file.HistoryCommit.Id, file.Path);
                        var latestContent  = _Git.GetFileContent(file.LatestCommit.Id, file.Path);

                        if (historyContent == latestContent)
                        {
                            file.Mark = "I";
                            continue;
                        }
                    }

                    file.Mark = "M";
                    continue;
                }

                if ((file.InitialAction == "M" && file.LatestAction == "D") ||
                    (file.InitialAction == "D" && file.LatestAction == "D"))
                {
                    var commit = _Git.GetFileHistory(file.Path, file.InitialCommit);
                    if (commit != null)
                    {
                        file.HistoryCommit = commit;
                    }

                    file.Mark = "D";
                    continue;
                }

                if ((file.InitialAction == "A" && file.LatestAction == "A") ||
                    (file.InitialAction == "A" && file.LatestAction == "M"))
                {
                    file.Mark = "A";
                    continue;
                }

                if (file.InitialAction == "A" && file.LatestAction == "D")
                {
                    file.Mark = "I";
                    continue;
                }
            }

            ClearCurrentLine();

            index = 1;
            var compares = files.Where(x => x.Mark != "I").OrderBy(x => x.Mark).ThenBy(x => x.Path).ToArray().Each(x => x.Index = index++);

            // print results
            Print(compares);

            // wait input from user
            while ((n = ReadCompare(compares.Length)) != 0)
            {
                switch (n)
                {
                case -1:
                {
                    Print(compares);
                    break;
                }

                case -2:
                {
                    Console.WriteLine("your input is not valid.");
                    break;
                }

                default:
                {
                    var compare = compares.FirstOrDefault(x => x.Index == n);
                    if (compare.Mark == "M" && compare.HistoryCommit != null)
                    {
                        Console.WriteLine($"compare {compare.HistoryCommit.Id} to {compare.LatestCommit.Id}");

                        if (!"./tempfiles".IsFolder())
                        {
                            Directory.CreateDirectory("./tempfiles".FullPath());
                        }

                        var history = $"./tempfiles/{compare.HistoryCommit.Id.Substring(0, 6)}-{compare.FileName}".FullPath();
                        using (var outputStream = new FileStream(history, FileMode.Create, FileAccess.Write))
                        {
                            using (var writer = new StreamWriter(outputStream))
                            {
                                writer.Write(_Git.GetFileContent(compare.HistoryCommit.Id, compare.Path));
                            }
                        }

                        var latest = $"./tempfiles/{compare.LatestCommit.Id.Substring(0, 6)}-{compare.FileName}".FullPath();
                        using (var outputStream = new FileStream(latest, FileMode.Create, FileAccess.Write))
                        {
                            using (var writer = new StreamWriter(outputStream))
                            {
                                writer.Write(_Git.GetFileContent(compare.LatestCommit.Id, compare.Path));
                            }
                        }

                        var config = DependencyContainer.Resolve <IAppConfiguration>();

                        ProcessUtils.Execute(
                            config.CompareTool,
                            $"{config.CompareToolParams ?? string.Empty} \"{history}\" \"{latest}\"",
                            null);
                    }
                    else if (compare.Mark == "A")
                    {
                        Console.WriteLine($"{compare.Path} Added.");

                        if (!"./tempfiles".IsFolder())
                        {
                            Directory.CreateDirectory("./tempfiles".FullPath());
                        }

                        var history = "./tempfiles/empty".FullPath();
                        if (!history.IsFile())
                        {
                            using (var outputStream = new FileStream(history, FileMode.Create, FileAccess.Write)) { }
                        }

                        var latest = $"./tempfiles/{compare.LatestCommit.Id.Substring(0, 6)}-{compare.FileName}".FullPath();
                        using (var outputStream = new FileStream(latest, FileMode.Create, FileAccess.Write))
                        {
                            using (var writer = new StreamWriter(outputStream))
                            {
                                writer.Write(_Git.GetFileContent(compare.LatestCommit.Id, compare.Path));
                            }
                        }

                        var config = DependencyContainer.Resolve <IAppConfiguration>();

                        ProcessUtils.Execute(
                            config.CompareTool,
                            $"{config.CompareToolParams ?? string.Empty} \"{history}\" \"{latest}\"",
                            null);
                    }
                    else if (compare.Mark == "D" && compare.HistoryCommit != null)
                    {
                        Console.WriteLine($"{compare.Path} Deleted.");

                        if (!"./tempfiles".IsFolder())
                        {
                            Directory.CreateDirectory("./tempfiles".FullPath());
                        }

                        var history = $"./tempfiles/{compare.HistoryCommit.Id.Substring(0, 6)}-{compare.FileName}".FullPath();
                        using (var outputStream = new FileStream(history, FileMode.Create, FileAccess.Write))
                        {
                            using (var writer = new StreamWriter(outputStream))
                            {
                                writer.Write(_Git.GetFileContent(compare.HistoryCommit.Id, compare.Path));
                            }
                        }

                        var latest = "./tempfiles/empty".FullPath();
                        if (!latest.IsFile())
                        {
                            using (var outputStream = new FileStream(latest, FileMode.Create, FileAccess.Write)) { }
                        }

                        var config = DependencyContainer.Resolve <IAppConfiguration>();

                        ProcessUtils.Execute(
                            config.CompareTool,
                            $"{config.CompareToolParams ?? string.Empty} \"{history}\" \"{latest}\"",
                            null);
                    }

                    break;
                }
                }
            }

            return(await Task.FromResult(0));
        }