コード例 #1
0
        private void diffResetSubmoduleChanges_Click(object sender, EventArgs e)
        {
            var submodules = DiffFiles.SelectedItems.Where(it => it.IsSubmodule).Select(it => it.Name).Distinct().ToList();

            // Show a form asking the user if they want to reset the changes.
            FormResetChanges.ActionEnum resetType = FormResetChanges.ShowResetDialog(this, true, true);
            if (resetType == FormResetChanges.ActionEnum.Cancel)
            {
                return;
            }

            foreach (var name in submodules)
            {
                VsrModule module = Module.GetSubmodule(name);

                // Reset all changes.
                module.Reset(ResetMode.Hard);

                // Also delete new files, if requested.
                if (resetType == FormResetChanges.ActionEnum.ResetAndDelete)
                {
                    module.Clean(CleanMode.OnlyNonIgnored, directories: true);
                }
            }

            RefreshArtificial();
        }
コード例 #2
0
        private static async Task <string> GetChangedFileTextAsync(VsrModule module, GitItemStatus file)
        {
            var changes = await module.GetCurrentChangesAsync(file.Name, file.OldName, file.Staged == StagedStatus.Index, "-U1000000")
                          .ConfigureAwait(false);

            if (changes != null)
            {
                return(changes.Text);
            }

            var content = await module.GetFileContentsAsync(file).ConfigureAwaitRunInline();

            if (content != null)
            {
                return(content);
            }

            // Try to read the contents of the file: if it cannot be read, skip the operation silently.
            try
            {
                using (var reader = File.OpenText(Path.Combine(module.WorkingDir, file.Name)))
                {
                    return(await reader.ReadToEndAsync());
                }
            }
            catch
            {
                return("");
            }
        }
コード例 #3
0
 private static ConfigFileSettings CreateLocal(VsrModule module, ConfigFileSettings lowerPriority,
                                               SettingLevel settingLevel, bool allowCache = true)
 {
     return(new ConfigFileSettings(lowerPriority,
                                   ConfigFileSettingsCache.Create(Path.Combine(module.GitCommonDirectory, "config"), true, allowCache),
                                   settingLevel));
 }
コード例 #4
0
        public static string GetSubmoduleText(VsrModule superproject, string name, string hash)
        {
            var sb = new StringBuilder();

            sb.AppendLine("Submodule " + name);
            sb.AppendLine();
            VsrModule module = superproject.GetSubmodule(name);

            // TODO File access for Git revision access
            if (module.IsValidVersionrWorkingDir())
            {
                // TEMP, will be moved in the follow up refactor
                ICommitDataManager commitDataManager = new CommitDataManager(() => module);

                CommitData data = commitDataManager.GetCommitData(hash, out _);
                if (data == null)
                {
                    sb.AppendLine("Commit hash:\t" + hash);
                    return(sb.ToString());
                }

                string header = PlainCommitDataHeaderRenderer.RenderPlain(data);
                string body   = "\n" + data.Body.Trim();
                sb.AppendLine(header);
                sb.Append(body);
            }
            else
            {
                sb.AppendLine("Commit hash:\t" + hash);
            }

            return(sb.ToString());
        }
コード例 #5
0
        /// <summary>
        /// Update the detailed status from the git status
        /// </summary>
        /// <param name="module">Current module</param>
        /// <param name="gitStatus">git status</param>
        /// <param name="cancelToken">Cancellation token</param>
        /// <returns>The task</returns>
        private async Task UpdateSubmodulesStatusAsync(VsrModule module, [CanBeNull] IReadOnlyList <GitItemStatus> gitStatus, CancellationToken cancelToken)
        {
            _previousSubmoduleUpdateTime = DateTime.Now;
            await TaskScheduler.Default;

            // TopModule is dirty if there are any changes in any module
            if (gitStatus != null &&
                gitStatus.Count > 0)
            {
                SetTopModuleAsDirty(module.GetTopModule().WorkingDir);
            }
            else if (module.GetTopModule() == module)
            {
                // status includes top module changes to files and 'dirty' can be cleared
                // (keep 'dirty' if unknown)
                _submoduleInfos[module.WorkingDir].Detailed = null;
            }

            var changedSubmodules = gitStatus.Where(i => i.IsSubmodule);

            foreach (var submoduleName in module.GetSubmodulesLocalPaths(false).Where(s => !changedSubmodules.Any(i => i.Name == s)))
            {
                SetSubmoduleEmptyDetailedStatus(module, submoduleName);
            }

            foreach (var submoduleName in changedSubmodules)
            {
                cancelToken.ThrowIfCancellationRequested();

                await GetSubmoduleDetailedStatusAsync(module, submoduleName.Name, cancelToken);
            }
        }
コード例 #6
0
        /// <summary>
        /// Set empty submodule status for 'submoduleName' and below
        /// </summary>
        /// <param name="superModule">The module to compare to</param>
        /// <param name="submoduleName">Name of the submodule</param>
        private void SetSubmoduleEmptyDetailedStatus(VsrModule superModule, string submoduleName)
        {
            if (superModule == null || string.IsNullOrEmpty(submoduleName))
            {
                return;
            }

            string path = superModule.GetSubmoduleFullPath(submoduleName);

            if (!_submoduleInfos.ContainsKey(path) || _submoduleInfos[path] == null)
            {
                return;
            }

            // null is default status
            var info = _submoduleInfos[path];

            info.Detailed = null;

            var module = new VsrModule(path);

            foreach (var name in module.GetSubmodulesLocalPaths(false))
            {
                SetSubmoduleEmptyDetailedStatus(module, name);
            }
        }
コード例 #7
0
        private bool TryGetCommitLog([NotNull] string commitId, [NotNull] string format, out string error, out string data)
        {
            if (commitId.IsArtificial())
            {
                data  = null;
                error = "No log information for artificial commits";
                return(false);
            }

            var arguments = new GitArgumentBuilder("log")
            {
                "-1",
                $"--pretty=\"format:{format}\"",
                commitId
            };

            // Do not cache this command, since notes can be added
            data = GetModule().GitExecutable.GetOutput(arguments, outputEncoding: VsrModule.LosslessEncoding);

            if (VsrModule.IsGitErrorMessage(data))
            {
                error = "Cannot find commit " + commitId;
                return(false);
            }

            error = null;
            return(true);
        }
コード例 #8
0
        private void InitClick(object sender, EventArgs e)
        {
            var directoryPath = _NO_TRANSLATE_Directory.Text;

            if (!IsRootedDirectoryPath(directoryPath))
            {
                MessageBox.Show(this, _chooseDirectory.Text, _chooseDirectoryCaption.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (File.Exists(directoryPath))
            {
                MessageBox.Show(this, _chooseDirectoryNotFile.Text, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var module = new VsrModule(directoryPath);

            if (!System.IO.Directory.Exists(module.WorkingDir))
            {
                System.IO.Directory.CreateDirectory(module.WorkingDir);
            }

            MessageBox.Show(this, module.Init(Central.Checked, Central.Checked), _initMsgBoxCaption.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

            _gitModuleChanged?.Invoke(this, new VsrModuleEventArgs(module));

            ThreadHelper.JoinableTaskFactory.Run(() => RepositoryHistoryManager.Locals.AddAsMostRecentAsync(directoryPath));
            Close();
        }
コード例 #9
0
        public void UnescapeOctalCodePoints_returns_same_string_if_nothing_to_escape()
        {
            // If nothing was escaped in the original string, the same string instance is returned.
            const string s = "Hello, World!";

            Assert.AreSame(s, VsrModule.UnescapeOctalCodePoints(s));
        }
コード例 #10
0
        public CommonLogic([CanBeNull] VsrModule module)
        {
            Module = module;

            if (module != null)
            {
                var repoDistGlobalSettings    = RepoDistSettings.CreateGlobal(false);
                var repoDistPulledSettings    = RepoDistSettings.CreateDistributed(Module, false);
                var repoDistLocalSettings     = RepoDistSettings.CreateLocal(Module, false);
                var repoDistEffectiveSettings = new RepoDistSettings(
                    new RepoDistSettings(repoDistGlobalSettings, repoDistPulledSettings.SettingsCache, SettingLevel.Distributed),
                    repoDistLocalSettings.SettingsCache,
                    SettingLevel.Effective);

                var configFileGlobalSettings    = ConfigFileSettings.CreateGlobal(false);
                var configFileLocalSettings     = ConfigFileSettings.CreateLocal(Module, false);
                var configFileEffectiveSettings = new ConfigFileSettings(
                    configFileGlobalSettings, configFileLocalSettings.SettingsCache, SettingLevel.Effective);

                RepoDistSettingsSet = new RepoDistSettingsSet(
                    repoDistEffectiveSettings,
                    repoDistLocalSettings,
                    repoDistPulledSettings,
                    repoDistGlobalSettings);

                ConfigFileSettingsSet = new ConfigFileSettingsSet(
                    configFileEffectiveSettings,
                    configFileLocalSettings,
                    configFileGlobalSettings);
            }
        }
コード例 #11
0
        private static string GetModuleBranch(string path, string noBranchText)
        {
            var branch = VsrModule.GetSelectedBranchFast(path);
            var text   = DetachedHeadParser.IsDetachedHead(branch) ? noBranchText : branch;

            return($"({text})");
        }
コード例 #12
0
        private void SetSubmoduleData(VsrModule currentModule, SubmoduleInfoResult result, string noBranchText, IVsrModule topProject)
        {
            var submodules = topProject.GetSubmodulesLocalPaths().OrderBy(submoduleName => submoduleName).ToArray();

            if (submodules.Any())
            {
                string localPath = result.Module.WorkingDir.Substring(topProject.WorkingDir.Length);
                localPath = Path.GetDirectoryName(localPath).ToPosixPath();

                foreach (var submodule in submodules)
                {
                    string path = topProject.GetSubmoduleFullPath(submodule);
                    string name = submodule + GetBranchNameSuffix(path, noBranchText);

                    bool bold = false;
                    if (submodule == localPath)
                    {
                        result.CurrentSubmoduleName = currentModule.GetCurrentSubmoduleLocalPath();
                        bold = true;
                    }

                    var smi = new SubmoduleInfo {
                        Text = name, Path = path, Bold = bold
                    };
                    result.SuperSubmodules.Add(smi);
                }
            }
        }
コード例 #13
0
        /// <inheritdoc />
        public void UpdateSubmodulesStatus(string workingDirectory, [CanBeNull] IReadOnlyList <GitItemStatus> gitStatus, bool forceUpdate)
        {
            if (_submoduleInfoResult == null)
            {
                _gitStatusWhileUpdatingStructure = gitStatus;
                return;
            }

            // Throttle updates triggered from status updates
            TimeSpan elapsed = DateTime.Now - _previousSubmoduleUpdateTime;

            if (gitStatus == null || (!forceUpdate && elapsed.TotalSeconds <= 15))
            {
                Console.WriteLine($"{MethodBase.GetCurrentMethod().Name} called too early again - aborting");
                return;
            }

            var cancelToken = _submodulesStatusSequence.Next();

            _gitStatusWhileUpdatingStructure = null;
            ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await TaskScheduler.Default;

                var currentModule = new VsrModule(workingDirectory);
                await UpdateSubmodulesStatusAsync(currentModule, gitStatus, cancelToken);

                OnStatusUpdated(_submoduleInfoResult, cancelToken);
            }).FileAndForget();
        }
コード例 #14
0
 public static new bool ShowDialog(IWin32Window owner, VsrModule module, ArgumentString arguments)
 {
     using (var formRemoteProcess = new FormRemoteProcess(module, arguments))
     {
         formRemoteProcess.ShowDialog(owner);
         return(!formRemoteProcess.ErrorOccurred());
     }
 }
コード例 #15
0
 private static RepoDistSettings CreateLocal(VsrModule module, RepoDistSettings lowerPriority,
                                             SettingLevel settingLevel, bool allowCache = true)
 {
     ////if (module.IsBareRepository()
     return(new RepoDistSettings(lowerPriority,
                                 GitExtSettingsCache.Create(Path.Combine(module.GitCommonDirectory, AppSettings.SettingsFileName), allowCache),
                                 settingLevel));
 }
コード例 #16
0
        public static bool AskForCacheHostkey(IWin32Window owner, VsrModule module, string remoteUrl)
        {
            if (!string.IsNullOrEmpty(remoteUrl) && MessageBoxes.CacheHostkey(owner))
            {
                return(new Plink().Connect(remoteUrl));
            }

            return(false);
        }
コード例 #17
0
ファイル: Dashboard.cs プロジェクト: craw85/vsrextensions
        private void openItem_Click(object sender, EventArgs e)
        {
            VsrModule module = FormOpenDirectory.OpenModule(this, currentModule: null);

            if (module != null)
            {
                OnModuleChanged(this, new VsrModuleEventArgs(module));
            }
        }
コード例 #18
0
        public static IRepositoryHostPlugin TryGetGitHosterForModule(VsrModule module)
        {
            if (!module.IsValidVersionrWorkingDir())
            {
                return(null);
            }

            return(GitHosters.FirstOrDefault(gitHoster => gitHoster.GitModuleIsRelevantToMe()));
        }
コード例 #19
0
        private void LoadPuttyKey()
        {
            if (!GitCommandHelpers.Plink())
            {
                return;
            }

            if (File.Exists(AppSettings.Pageant))
            {
                var files = new HashSet <string>(new PathEqualityComparer());
                foreach (var remote in GetSelectedRemotes())
                {
                    var sshKeyFile = Module.GetPuttyKeyFileForRemote(remote);
                    if (!string.IsNullOrEmpty(sshKeyFile))
                    {
                        files.Add(sshKeyFile);
                    }
                }

                foreach (var sshKeyFile in files)
                {
                    if (File.Exists(sshKeyFile))
                    {
                        VsrModule.StartPageantWithKey(sshKeyFile);
                    }
                }
            }
            else
            {
                MessageBoxes.PAgentNotFound(this);
            }

            return;

            IEnumerable <string> GetSelectedRemotes()
            {
                if (PullFromUrl.Checked)
                {
                    yield break;
                }

                if (IsPullAll())
                {
                    foreach (var remote in (IEnumerable <ConfigFileRemote>)_NO_TRANSLATE_Remotes.DataSource)
                    {
                        if (!string.IsNullOrWhiteSpace(remote.Name) && remote.Name != AllRemotes)
                        {
                            yield return(remote.Name);
                        }
                    }
                }
                else if (!string.IsNullOrWhiteSpace(_NO_TRANSLATE_Remotes.Text))
                {
                    yield return(_NO_TRANSLATE_Remotes.Text);
                }
            }
        }
コード例 #20
0
        private string GetBranchNameSuffix(string repositoryPath, string noBranchText)
        {
            if (AppSettings.ShowRepoCurrentBranch && !VsrModule.IsBareRepository(repositoryPath))
            {
                return(" " + GetModuleBranch(repositoryPath, noBranchText));
            }

            return(string.Empty);
        }
コード例 #21
0
        /// <summary>
        /// Get the detailed submodule status submodules below 'module' (but not this module)
        /// </summary>
        /// <param name="module">Module to compare to</param>
        /// <param name="cancelToken">Cancelation token</param>
        /// <returns>The task</returns>
        private async Task GetSubmoduleDetailedStatusAsync(VsrModule module, CancellationToken cancelToken)
        {
            foreach (var name in module.GetSubmodulesLocalPaths(false))
            {
                cancelToken.ThrowIfCancellationRequested();

                await GetSubmoduleDetailedStatusAsync(module, name, cancelToken);
            }
        }
コード例 #22
0
        public FormFileHistory(GitUICommands commands, string fileName, GitRevision revision = null, bool filterByRevision = false)
            : this(commands)
        {
            FileChanges.InitialObjectId     = revision?.ObjectId;
            FileChanges.ShowBuildServerInfo = true;

            FileName = fileName;
            SetTitle();

            Diff.ExtraDiffArgumentsChanged += (sender, e) => UpdateSelectedFileViewers();

            var isSubmodule = VsrModule.IsValidVersionrWorkingDir(_fullPathResolver.Resolve(FileName));

            if (isSubmodule)
            {
                tabControl1.RemoveIfExists(BlameTab);
            }

            FileChanges.SelectionChanged += FileChangesSelectionChanged;
            FileChanges.DisableContextMenu();

            bool blameTabExists = tabControl1.Contains(BlameTab);

            UpdateFollowHistoryMenuItems();

            fullHistoryToolStripMenuItem.Checked     = AppSettings.FullHistoryInFileHistory;
            showFullHistoryToolStripMenuItem.Checked = AppSettings.FullHistoryInFileHistory;
            simplifyMergesToolStripMenuItem.Checked  = AppSettings.SimplifyMergesInFileHistory;
            simplifyMergesToolStripMenuItem.Enabled  = AppSettings.FullHistoryInFileHistory;
            simplifyMergesContextMenuItem.Checked    = AppSettings.SimplifyMergesInFileHistory;
            simplifyMergesContextMenuItem.Enabled    = AppSettings.FullHistoryInFileHistory;

            loadHistoryOnShowToolStripMenuItem.Checked = AppSettings.LoadFileHistoryOnShow;
            loadBlameOnShowToolStripMenuItem.Checked   = AppSettings.LoadBlameOnShow && blameTabExists;
            saveAsToolStripMenuItem.Visible            = !isSubmodule;

            toolStripBlameOptions.Visible = blameTabExists;
            if (blameTabExists)
            {
                ignoreWhitespaceToolStripMenuItem.Checked            = AppSettings.IgnoreWhitespaceOnBlame;
                detectMoveAndCopyInAllFilesToolStripMenuItem.Checked = AppSettings.DetectCopyInAllOnBlame;
                detectMoveAndCopyInThisFileToolStripMenuItem.Checked = AppSettings.DetectCopyInFileOnBlame;
                displayAuthorFirstToolStripMenuItem.Checked          = AppSettings.BlameDisplayAuthorFirst;
                showAuthorAvatarToolStripMenuItem.Checked            = AppSettings.BlameShowAuthorAvatar;
                showAuthorToolStripMenuItem.Checked           = AppSettings.BlameShowAuthor;
                showAuthorDateToolStripMenuItem.Checked       = AppSettings.BlameShowAuthorDate;
                showAuthorTimeToolStripMenuItem.Checked       = AppSettings.BlameShowAuthorTime;
                showLineNumbersToolStripMenuItem.Checked      = AppSettings.BlameShowLineNumbers;
                showOriginalFilePathToolStripMenuItem.Checked = AppSettings.BlameShowOriginalFilePath;
            }

            if (filterByRevision && revision?.ObjectId != null)
            {
                _filterBranchHelper.SetBranchFilter(revision.Guid, false);
            }
        }
コード例 #23
0
        public void CheckSubmoduleStatus(VsrModule submodule)
        {
            if (submodule == null)
            {
                Status = SubmoduleStatus.NewSubmodule;
                return;
            }

            Status = submodule.CheckSubmoduleStatus(Commit, OldCommit);
        }
コード例 #24
0
 private void LoadSshKeyClick(object sender, EventArgs e)
 {
     if (string.IsNullOrEmpty(PuttySshKey.Text))
     {
         MessageBox.Show(this, _errorNoKeyEntered.Text, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else
     {
         VsrModule.StartPageantWithKey(PuttySshKey.Text);
     }
 }
コード例 #25
0
        /// <summary>
        /// Tries to load the given key. Returns whether successful.
        /// </summary>
        public static bool LoadKey(IWin32Window parent, string path)
        {
            if (!File.Exists(AppSettings.Pageant))
            {
                MessageBoxes.PAgentNotFound(parent);
                return(false);
            }

            VsrModule.StartPageantWithKey(path);
            return(true);
        }
コード例 #26
0
        public static bool CanBeGitURL(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return(false);
            }

            return(IsUrl(url) ||
                   url.EndsWith(".git", StringComparison.CurrentCultureIgnoreCase) ||
                   VsrModule.IsValidVersionrWorkingDir(url));
        }
コード例 #27
0
        private void ChangeWorkingDir(string path, Action <object, VsrModuleEventArgs> setGitModule)
        {
            var module = new VsrModule(path);

            if (module.IsValidVersionrWorkingDir())
            {
                setGitModule(this, new VsrModuleEventArgs(module));
                return;
            }

            _invalidRepositoryRemover.ShowDeleteInvalidRepositoryDialog(path);
        }
コード例 #28
0
        public void TestGetDiffChangedFilesFromString(string testName, StagedStatus stagedStatus, string statusString)
        {
            // TODO produce a valid working directory
            var module = new VsrModule(Path.GetTempPath());

            using (ApprovalResults.ForScenario(testName.Replace(' ', '_')))
            {
                // git diff -M -C -z --name-status
                var statuses = GitCommandHelpers.GetDiffChangedFilesFromString(module, statusString, stagedStatus);
                Approvals.VerifyJson(JsonConvert.SerializeObject(statuses));
            }
        }
コード例 #29
0
        public static string ProcessSubmodulePatch(VsrModule module, string fileName, Patch patch)
        {
            string text   = patch?.Text;
            var    status = GitCommandHelpers.ParseSubmoduleStatus(text, module, fileName);

            if (status == null)
            {
                return("");
            }

            return(ProcessSubmoduleStatus(module, status));
        }
コード例 #30
0
        public void TestGetStatusChangedFilesFromString(string testName, string statusString)
        {
            // TODO produce a valid working directory
            var module = new VsrModule(Path.GetTempPath());

            using (ApprovalResults.ForScenario(testName.Replace(' ', '_')))
            {
                // git status --porcelain=2 --untracked-files=no -z
                var statuses = GitCommandHelpers.GetStatusChangedFilesFromString(module, statusString);
                Approvals.VerifyJson(JsonConvert.SerializeObject(statuses));
            }
        }