Exemplo n.º 1
0
 public void MergeBranchCmd(bool allowFastForward, bool squash, bool noCommit, string strategy, bool allowUnrelatedHistories, string mergeCommitFilePath, int?log, string expected)
 {
     Assert.AreEqual(expected, GitCommandHelpers.MergeBranchCmd("branch", allowFastForward, squash, noCommit, strategy, allowUnrelatedHistories, mergeCommitFilePath, log).Arguments);
 }
Exemplo n.º 2
0
 protected override void BeforeProcessStart()
 {
     restart = false;
     Plink   = GitCommandHelpers.Plink();
     base.BeforeProcessStart();
 }
Exemplo n.º 3
0
        public static string RunGerritCommand([NotNull] IWin32Window owner, [NotNull] IGitModule aModule, [NotNull] string command, [NotNull] Uri fetchUrl, [NotNull] string remote, byte[] stdIn)
        {
            if (owner == null)
            {
                throw new ArgumentNullException("owner");
            }
            if (aModule == null)
            {
                throw new ArgumentNullException("aModule");
            }
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }
            if (fetchUrl == null)
            {
                throw new ArgumentNullException("fetchUrl");
            }
            if (remote == null)
            {
                throw new ArgumentNullException("remote");
            }

            StartAgent(owner, aModule, remote);

            var sshCmd = GitCommandHelpers.GetSsh();

            if (GitCommandHelpers.Plink())
            {
                sshCmd = Settings.Plink;
            }
            if (string.IsNullOrEmpty(sshCmd))
            {
                sshCmd = "ssh.exe";
            }

            string hostname = fetchUrl.Host;
            string username = fetchUrl.UserInfo;
            string portFlag = GitCommandHelpers.Plink() ? " -P " : " -p ";
            int    port     = fetchUrl.Port;

            if (port == -1 && fetchUrl.Scheme == "ssh")
            {
                port = 22;
            }

            var sb = new StringBuilder();

            sb.Append('"');

            if (!string.IsNullOrEmpty(username))
            {
                sb.Append(username);
                sb.Append('@');
            }

            sb.Append(hostname);
            sb.Append('"');
            sb.Append(portFlag);
            sb.Append(port);

            sb.Append(" \"");
            sb.Append(command);
            sb.Append("\"");

            return(aModule.RunCmd(
                       sshCmd,
                       sb.ToString(),
                       stdIn
                       ));
        }
Exemplo n.º 4
0
 private void ContinueBisect(GitBisectOption bisectOption)
 {
     FormProcess.ShowDialog(this, GitCommandHelpers.ContinueBisectCmd(bisectOption), false);
     Close();
 }
Exemplo n.º 5
0
        private void OkClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.Default;
                _branchListLoader.Cancel();

                // validate if destination path is supplied
                var destination = _NO_TRANSLATE_To.Text;
                if (string.IsNullOrWhiteSpace(destination))
                {
                    MessageBox.Show(this, _errorDestinationNotSupplied.Text, _errorCloneFailed.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _NO_TRANSLATE_To.Focus();
                    return;
                }

                if (!Path.IsPathRooted(destination))
                {
                    MessageBox.Show(this, _errorDestinationNotRooted.Text, _errorCloneFailed.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _NO_TRANSLATE_To.Focus();
                    return;
                }

                var dirTo = Path.Combine(destination, _NO_TRANSLATE_NewDirectory.Text);

                // this will fail if the path is anyhow invalid
                dirTo = new Uri(dirTo).LocalPath;

                if (!Directory.Exists(dirTo))
                {
                    Directory.CreateDirectory(dirTo);
                }

                // Shallow clone params
                int? depth          = null;
                bool?isSingleBranch = null;
                if (!cbDownloadFullHistory.Checked)
                {
                    depth = 1;

                    // Single branch considerations:
                    // If neither depth nor single-branch family params are specified, then it's like no-single-branch by default.
                    // If depth is specified, then single-branch is assumed.
                    // But with single-branch it's really nontrivial to switch to another branch in the GUI, and it's very hard in cmdline (obvious choices to fetch another branch lead to local repo corruption).
                    // So let's reset it to no-single-branch to (a) have the same branches behavior as with full clone, and (b) make it easier for users when switching branches.
                    isSingleBranch = false;
                }

                // Branch name param
                string branch = _NO_TRANSLATE_Branches.Text;
                if (branch == _branchDefaultRemoteHead.Text)
                {
                    branch = "";
                }
                else if (branch == _branchNone.Text)
                {
                    branch = null;
                }

                var cloneCmd = GitCommandHelpers.CloneCmd(_NO_TRANSLATE_From.Text, dirTo,
                                                          CentralRepository.Checked, cbIntializeAllSubmodules.Checked, branch, depth, isSingleBranch, cbLfs.Checked);
                using (var fromProcess = new FormRemoteProcess(Module, AppSettings.GitCommand, cloneCmd))
                {
                    fromProcess.SetUrlTryingToConnect(_NO_TRANSLATE_From.Text);
                    fromProcess.ShowDialog(this);

                    if (fromProcess.ErrorOccurred() || Module.InTheMiddleOfPatch())
                    {
                        return;
                    }
                }

                Repositories.AddMostRecentRepository(dirTo);

                if (!string.IsNullOrEmpty(_puttySshKey))
                {
                    var clonedGitModule = new GitModule(dirTo);
                    clonedGitModule.SetSetting(string.Format(SettingKeyString.RemotePuttySshKey, "origin"), _puttySshKey);
                    clonedGitModule.LocalConfigFile.Save();
                }

                if (_openedFromProtocolHandler && AskIfNewRepositoryShouldBeOpened(dirTo))
                {
                    Hide();
                    GitUICommands uiCommands = new GitUICommands(dirTo);
                    uiCommands.StartBrowseDialog();
                }
                else if (ShowInTaskbar == false && _gitModuleChanged != null &&
                         AskIfNewRepositoryShouldBeOpened(dirTo))
                {
                    _gitModuleChanged(this, new GitModuleEventArgs(new GitModule(dirTo)));
                }

                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Exception: " + ex.Message, _errorCloneFailed.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 6
0
 private void Stop_Click(object sender, EventArgs e)
 {
     FormProcess.ShowDialog(this, process: null, arguments: GitCommandHelpers.StopBisectCmd(), Module.WorkingDir, input: null, useDialogSettings: false);
     Close();
 }
Exemplo n.º 7
0
        private FixedFilterTuple BuildFilter(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(null);
            }

            //Replace windows path separator to Linux path separator.
            //This is needed to keep the file history working when started from file tree in
            //browse dialog.
            fileName = fileName.ToPosixPath();

            // we will need this later to look up proper casing for the file
            var fullFilePath = Path.Combine(Module.WorkingDir, fileName);

            //The section below contains native windows (kernel32) calls
            //and breaks on Linux. Only use it on Windows. Casing is only
            //a Windows problem anyway.
            if (EnvUtils.RunningOnWindows() && File.Exists(fullFilePath))
            {
                // grab the 8.3 file path
                var shortPath = new StringBuilder(4096);
                NativeMethods.GetShortPathName(fullFilePath, shortPath, shortPath.Capacity);

                // use 8.3 file path to get properly cased full file path
                var longPath = new StringBuilder(4096);
                NativeMethods.GetLongPathName(shortPath.ToString(), longPath, longPath.Capacity);

                // remove the working directory and now we have a properly cased file name.
                fileName = longPath.ToString().Substring(Module.WorkingDir.Length);
            }

            if (fileName.StartsWith(Module.WorkingDir, StringComparison.InvariantCultureIgnoreCase))
            {
                fileName = fileName.Substring(Module.WorkingDir.Length);
            }

            FileName = fileName;

            FixedFilterTuple res = new FixedFilterTuple();

            res.PathFilter = " \"" + fileName + "\"";
            if (AppSettings.FollowRenamesInFileHistory && !Directory.Exists(fullFilePath))
            {
                // git log --follow is not working as expected (see  http://kerneltrap.org/mailarchive/git/2009/1/30/4856404/thread)
                //
                // But we can take a more complicated path to get reasonable results:
                //  1. use git log --follow to get all previous filenames of the file we are interested in
                //  2. use git log "list of files names" to get the history graph
                //
                // note: This implementation is quite a quick hack (by someone who does not speak C# fluently).
                //

                string arg = "log --format=\"%n\" --name-only --follow " +
                             GitCommandHelpers.FindRenamesAndCopiesOpts()
                             + " -- \"" + fileName + "\"";
                Process p = Module.RunGitCmdDetached(arg, GitModule.LosslessEncoding);

                // the sequence of (quoted) file names - start with the initial filename for the search.
                var listOfFileNames = new StringBuilder("\"" + fileName + "\"");

                // keep a set of the file names already seen
                var setOfFileNames = new HashSet <string> {
                    fileName
                };

                string line;
                do
                {
                    line = p.StandardOutput.ReadLine();
                    line = GitModule.ReEncodeFileNameFromLossless(line);

                    if (!string.IsNullOrEmpty(line) && setOfFileNames.Add(line))
                    {
                        listOfFileNames.Append(" \"");
                        listOfFileNames.Append(line);
                        listOfFileNames.Append('\"');
                    }
                } while (line != null);
                // here we need --name-only to get the previous filenames in the revision graph
                res.PathFilter      = listOfFileNames.ToString();
                res.RevisionFilter += " --name-only --parents" + GitCommandHelpers.FindRenamesAndCopiesOpts();
            }
            else if (AppSettings.FollowRenamesInFileHistory)
            {
                // history of a directory
                // --parents doesn't work with --follow enabled, but needed to graph a filtered log
                res.RevisionFilter = " " + GitCommandHelpers.FindRenamesOpt() + " --follow --parents";
            }
            else
            {
                // rename following disabled
                res.RevisionFilter = " --parents";
            }

            if (AppSettings.FullHistoryInFileHistory)
            {
                res.RevisionFilter = string.Concat(" --full-history ", res.RevisionFilter);
            }


            return(res);
        }
Exemplo n.º 8
0
        private FixedFilterTuple BuildFilter(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(null);
            }

            //Replace windows path separator to Linux path separator.
            //This is needed to keep the file history working when started from file tree in
            //browse dialog.
            fileName = fileName.ToPosixPath();

            // we will need this later to look up proper casing for the file
            var fullFilePath = Path.Combine(Module.WorkingDir, fileName);

            //The section below contains native windows (kernel32) calls
            //and breaks on Linux. Only use it on Windows. Casing is only
            //a Windows problem anyway.
            if (EnvUtils.RunningOnWindows() && File.Exists(fullFilePath))
            {
                // grab the 8.3 file path
                var shortPath = new StringBuilder(4096);
                NativeMethods.GetShortPathName(fullFilePath, shortPath, shortPath.Capacity);

                // use 8.3 file path to get properly cased full file path
                var longPath = new StringBuilder(4096);
                NativeMethods.GetLongPathName(shortPath.ToString(), longPath, longPath.Capacity);

                // remove the working directory and now we have a properly cased file name.
                fileName = longPath.ToString().Substring(Module.WorkingDir.Length);
            }

            if (fileName.StartsWith(Module.WorkingDir, StringComparison.InvariantCultureIgnoreCase))
            {
                fileName = fileName.Substring(Module.WorkingDir.Length);
            }

            FileName = fileName;

            FixedFilterTuple res = new FixedFilterTuple();

            if (AppSettings.FollowRenamesInFileHistory && !Directory.Exists(fullFilePath))
            {
                // git log --follow is not working as expected (see  http://kerneltrap.org/mailarchive/git/2009/1/30/4856404/thread)
                FollowParentRewriter hrw = new FollowParentRewriter(fileName, delegate(string arg){
                    Process p = Module.RunGitCmdDetached(arg);
                    return(p.StandardOutput);
                });
                // here we need --name-only to get the previous filenames in the revision graph
                if (hrw.RewriteNecessary)
                {
                    res.Rewriter       = hrw;
                    res.RevisionFilter = " " + GitCommandHelpers.FindRenamesAndCopiesOpts() + " --name-only --follow";
                }
                else
                {
                    res.RevisionFilter = " " + GitCommandHelpers.FindRenamesAndCopiesOpts() + " --name-only --parents";
                }
            }
            else if (AppSettings.FollowRenamesInFileHistory)
            {
                // history of a directory
                // --parents doesn't work with --follow enabled, but needed to graph a filtered log
                res.RevisionFilter = " " + GitCommandHelpers.FindRenamesOpt() + " --follow --parents";
            }
            else
            {
                // rename following disabled
                res.RevisionFilter = " --parents";
            }

            if (AppSettings.FullHistoryInFileHistory)
            {
                res.RevisionFilter = string.Concat(" --full-history ", res.RevisionFilter);
            }

            res.PathFilter = " \"" + fileName + "\"";

            return(res);
        }
Exemplo n.º 9
0
        private void OkClick(object sender, EventArgs e)
        {
            // Ok button set as the "AcceptButton" for the form
            // if the user hits [Enter] at any point, we need to trigger BranchNameTextBox Leave event
            Ok.Focus();

            string commitGuid = commitPickerSmallControl1.SelectedCommitHash;

            if (commitGuid == null)
            {
                MessageBox.Show(this, _noRevisionSelected.Text, Text);
                DialogResult = DialogResult.None;
                return;
            }

            var branchName = BranchNameTextBox.Text.Trim();

            if (branchName.IsNullOrWhiteSpace())
            {
                MessageBox.Show(_branchNameIsEmpty.Text, Text);
                DialogResult = DialogResult.None;
                return;
            }

            if (!Module.CheckBranchFormat(branchName))
            {
                MessageBox.Show(string.Format(_branchNameIsNotValud.Text, branchName), Text);
                DialogResult = DialogResult.None;
                return;
            }

            try
            {
                var originalHash = Module.GetCurrentCheckout();

                string cmd;
                if (Orphan.Checked)
                {
                    cmd = GitCommandHelpers.CreateOrphanCmd(branchName, commitGuid);
                }
                else
                {
                    cmd = GitCommandHelpers.BranchCmd(branchName, commitGuid, chkbxCheckoutAfterCreate.Checked);
                }

                bool wasSuccessFul = FormProcess.ShowDialog(this, cmd);
                if (Orphan.Checked && wasSuccessFul && ClearOrphan.Checked)
                {// orphan AND orphan creation success AND clear
                    cmd = GitCommandHelpers.RemoveCmd();
                    FormProcess.ShowDialog(this, cmd);
                }

                if (wasSuccessFul && chkbxCheckoutAfterCreate.Checked && !string.Equals(commitGuid, originalHash, StringComparison.OrdinalIgnoreCase))
                {
                    UICommands.UpdateSubmodules(this);
                }

                DialogResult = wasSuccessFul ? DialogResult.OK : DialogResult.None;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
        }
Exemplo n.º 10
0
        private static void RunCommand(string[] args)
        {
            Dictionary <string, string> arguments = new Dictionary <string, string>();

            for (int i = 2; i < args.Length; i++)
            {
                if (args[i].StartsWith("--") && i + 1 < args.Length && !args[i + 1].StartsWith("--"))
                {
                    arguments.Add(args[i].TrimStart('-'), args[++i]);
                }
                else
                if (args[i].StartsWith("--"))
                {
                    arguments.Add(args[i].TrimStart('-'), null);
                }
            }

            if (args.Length > 1)
            {
                switch (args[1])
                {
                case "mergetool":
                case "mergeconflicts":
                    if (!arguments.ContainsKey("quiet") || GitCommandHelpers.InTheMiddleOfConflictedMerge())
                    {
                        GitUICommands.Instance.StartResolveConflictsDialog();
                    }

                    return;

                case "gitbash":
                    GitCommandHelpers.RunBash();
                    return;

                case "gitignore":
                    GitUICommands.Instance.StartEditGitIgnoreDialog();
                    return;

                case "remotes":
                    GitUICommands.Instance.StartRemotesDialog();
                    return;

                case "blame":
                    if (args.Length > 2)
                    {
                        // Remove working dir from filename. This is to prevent filenames that are too
                        // long while there is room left when the workingdir was not in the path.
                        string fileName = args[2].Replace(Settings.WorkingDir, "").Replace('\\', '/');

                        GitUICommands.Instance.StartBlameDialog(fileName);
                    }
                    else
                    {
                        MessageBox.Show("Cannot open blame, there is no file selected.", "Blame");
                    }
                    return;

                case "browse":
                    GitUICommands.Instance.StartBrowseDialog(GetParameterOrEmptyStringAsDefault(args, "-filter"));
                    return;

                case "cleanup":
                    new FormCleanupRepository().ShowDialog();
                    return;

                case "add":
                case "addfiles":
                    GitUICommands.Instance.StartAddFilesDialog();
                    return;

                case "apply":
                case "applypatch":
                    GitUICommands.Instance.StartApplyPatchDialog();
                    return;

                case "branch":
                    GitUICommands.Instance.StartCreateBranchDialog();
                    return;

                case "checkout":
                case "checkoutbranch":
                    GitUICommands.Instance.StartCheckoutBranchDialog();
                    return;

                case "checkoutrevision":
                    GitUICommands.Instance.StartCheckoutRevisionDialog();
                    return;

                case "init":
                    if (args.Length > 2)
                    {
                        GitUICommands.Instance.StartInitializeDialog(args[2]);
                    }
                    else
                    {
                        GitUICommands.Instance.StartInitializeDialog();
                    }
                    return;

                case "clone":
                    GitUICommands.Instance.StartCloneDialog();
                    return;

                case "commit":
                    Commit(arguments);
                    return;

                case "filehistory":
                    if (args.Length > 2)
                    {
                        //Remove working dir from filename. This is to prevent filenames that are too
                        //long while there is room left when the workingdir was not in the path.
                        string fileName = args[2].Replace(Settings.WorkingDir, "").Replace('\\', '/');

                        GitUICommands.Instance.StartFileHistoryDialog(fileName);
                    }
                    else
                    {
                        MessageBox.Show("Cannot open file history, there is no file selected.", "File history");
                    }
                    return;

                case "fileeditor":
                    if (args.Length > 2)
                    {
                        using (var formEditor = new FormEditor(args[2]))
                        {
                            if (formEditor.ShowDialog() == DialogResult.Cancel)
                            {
                                System.Environment.ExitCode = -1;
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Cannot open file editor, there is no file selected.", "File editor");
                    }
                    return;

                case "formatpatch":
                    GitUICommands.Instance.StartFormatPatchDialog();
                    return;

                case "pull":
                    Pull(arguments);
                    return;

                case "push":
                    Push(arguments);
                    return;

                case "settings":
                    GitUICommands.Instance.StartSettingsDialog();
                    return;

                case "viewdiff":
                    GitUICommands.Instance.StartCompareRevisionsDialog();
                    return;

                case "rebase":
                {
                    string branch = null;
                    if (arguments.ContainsKey("branch"))
                    {
                        branch = arguments["branch"];
                    }
                    GitUICommands.Instance.StartRebaseDialog(branch);
                    return;
                }

                case "merge":
                {
                    string branch = null;
                    if (arguments.ContainsKey("branch"))
                    {
                        branch = arguments["branch"];
                    }
                    GitUICommands.Instance.StartMergeBranchDialog(branch);
                    return;
                }

                case "cherry":
                    GitUICommands.Instance.StartCherryPickDialog();
                    return;

                case "revert":
                    Application.Run(new FormRevert(args[2]));
                    return;

                case "tag":
                    GitUICommands.Instance.StartCreateTagDialog();
                    return;

                case "about":
                    Application.Run(new AboutBox());
                    return;

                case "stash":
                    GitUICommands.Instance.StartStashDialog();
                    return;

                case "synchronize":
                    Commit(arguments);
                    Pull(arguments);
                    Push(arguments);
                    return;

                default:
                    Application.Run(new FormCommandlineHelp());
                    return;
                }
            }
        }
Exemplo n.º 11
0
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string[] args = Environment.GetCommandLineArgs();
            FormSplash.Show("Load settings");
            Settings.LoadSettings();
            if (Settings.RunningOnWindows())
            {
                //Quick HOME check:
                FormSplash.SetAction("Check home path");
                FormFixHome.CheckHomePath();
            }
            //Register plugins
            FormSplash.SetAction("Load plugins");
            PluginLoader.LoadAsync();

            if (string.IsNullOrEmpty(Settings.Translation))
            {
                using (var formChoose = new FormChooseTranslation())
                {
                    formChoose.ShowDialog();
                }
            }

            try
            {
                if (Application.UserAppDataRegistry == null ||
                    Application.UserAppDataRegistry.GetValue("checksettings") == null ||
                    !Application.UserAppDataRegistry.GetValue("checksettings").ToString().Equals("false", StringComparison.OrdinalIgnoreCase) ||
                    string.IsNullOrEmpty(Settings.GitCommand))
                {
                    FormSplash.SetAction("Check settings");
                    using (var settings = new FormSettings())
                    {
                        if (!settings.CheckSettings())
                        {
                            FormSettings.AutoSolveAllSettings();
                            GitUICommands.Instance.StartSettingsDialog();
                        }
                    }
                }
            }
            catch
            {
                // TODO: remove catch-all
            }

            if (args.Length >= 3)
            {
                if (Directory.Exists(args[2]))
                {
                    Settings.WorkingDir = args[2];
                }

                if (string.IsNullOrEmpty(Settings.WorkingDir))
                {
                    if (args[2].Contains(Settings.PathSeparator.ToString()))
                    {
                        Settings.WorkingDir = args[2].Substring(0, args[2].LastIndexOf(Settings.PathSeparator));
                    }
                }

                if (Settings.ValidWorkingDir())
                {
                    Repositories.RepositoryHistory.AddMostRecentRepository(Settings.WorkingDir);
                }
            }

            if (string.IsNullOrEmpty(Settings.WorkingDir))
            {
                string findWorkingDir = GitCommandHelpers.FindGitWorkingDir(Directory.GetCurrentDirectory());
                if (Settings.ValidWorkingDir(findWorkingDir))
                {
                    Settings.WorkingDir = findWorkingDir;
                }
            }

            FormSplash.Hide();

            if (args.Length <= 1)
            {
                GitUICommands.Instance.StartBrowseDialog();
            }
            else  // if we are here args.Length > 1
            {
                RunCommand(args);
            }

            Settings.SaveSettings();
        }
Exemplo n.º 12
0
        private string RunStatusCommand()
        {
            string command = GitCommandHelpers.GetAllChangedFilesCmd(true, UntrackedFilesMode.Default);

            return(Module.RunGitCmd(command));
        }
Exemplo n.º 13
0
 public void AbortMergeCmd()
 {
     Assert.AreEqual("merge --abort", GitCommandHelpers.AbortMergeCmd().Arguments);
 }
Exemplo n.º 14
0
 public void ContinueMergeCmd()
 {
     Assert.AreEqual("merge --continue", GitCommandHelpers.ContinueMergeCmd().Arguments);
 }
Exemplo n.º 15
0
        public static string GetSelectedPatch(this FileViewer diffViewer, RevisionGrid grid, GitItemStatus file)
        {
            IList <GitRevision> revisions = grid.GetSelectedRevisions();

            if (revisions.Count == 0)
            {
                return(null);
            }

            string firstRevision  = revisions[0].Guid;
            var    secondRevision = revisions.Count == 2 ? revisions[1].Guid : null;

            //to simplify if-ology
            if (GitRevision.IsArtificial(secondRevision) && firstRevision != GitRevision.UnstagedGuid)
            {
                firstRevision  = secondRevision;
                secondRevision = revisions[0].Guid;
            }

            string extraDiffArgs = null;

            if (firstRevision == GitRevision.UnstagedGuid) //working dir changes
            {
                if (secondRevision == null || secondRevision == GitRevision.IndexGuid)
                {
                    if (file.IsTracked)
                    {
                        return(ProcessDiffText(grid.Module, grid.Module.GetCurrentChanges(file.Name, file.OldName, false,
                                                                                          diffViewer.GetExtraDiffArguments(), diffViewer.Encoding), file.IsSubmodule));
                    }

                    var fullPath = Path.Combine(grid.Module.WorkingDir, file.Name);
                    if (Directory.Exists(fullPath) && GitModule.ValidWorkingDir(fullPath))
                    {
                        return(GitCommandHelpers.GetSubmoduleText(grid.Module, file.Name.TrimEnd('/'), ""));
                    }
                    return(FileReader.ReadFileContent(fullPath, diffViewer.Encoding));
                }
                else
                {
                    firstRevision  = secondRevision;
                    secondRevision = string.Empty;
                }
            }
            if (firstRevision == GitRevision.IndexGuid) //index
            {
                if (secondRevision == null)
                {
                    return(ProcessDiffText(grid.Module, grid.Module.GetCurrentChanges(file.Name, file.OldName, true,
                                                                                      diffViewer.GetExtraDiffArguments(), diffViewer.Encoding), file.IsSubmodule));
                }

                //rev1 vs index
                firstRevision  = secondRevision;
                secondRevision = string.Empty;
                extraDiffArgs  = string.Join(" ", extraDiffArgs, "--cached");
            }

            Debug.Assert(!GitRevision.IsArtificial(firstRevision), string.Join(" ", firstRevision, secondRevision));

            if (secondRevision == null)
            {
                secondRevision = firstRevision + "^";
            }

            PatchApply.Patch patch = grid.Module.GetSingleDiff(firstRevision, secondRevision, file.Name, file.OldName,
                                                               string.Join(" ", diffViewer.GetExtraDiffArguments(), extraDiffArgs), diffViewer.Encoding);

            if (patch == null)
            {
                return(string.Empty);
            }

            return(ProcessDiffText(grid.Module, patch.Text, file.IsSubmodule));
        }
        public override void StartProcess(string command, string arguments, string workdir, Dictionary <string, string> envVariables)
        {
            try
            {
                GitCommandHelpers.SetEnvironmentVariable();

                bool ssh = GitCommandHelpers.UseSsh(arguments);

                KillProcess();

                string quotedCmd = command;
                if (quotedCmd.IndexOf(' ') != -1)
                {
                    quotedCmd = quotedCmd.Quote();
                }

                DateTime executionStartTimestamp = DateTime.Now;

                // process used to execute external commands
                var process = new Process();
                ProcessStartInfo startInfo = GitCommandHelpers.CreateProcessStartInfo(command, arguments, workdir, GitModule.SystemEncoding);
                startInfo.CreateNoWindow = (!ssh && !AppSettings.ShowGitCommandLine);
                foreach (var envVariable in envVariables)
                {
                    startInfo.EnvironmentVariables.Add(envVariable.Key, envVariable.Value);
                }

                process.StartInfo = startInfo;

                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (sender, args) => FireDataReceived(new TextEventArgs((args.Data ?? "") + '\n'));
                process.ErrorDataReceived  += (sender, args) => FireDataReceived(new TextEventArgs((args.Data ?? "") + '\n'));
                process.Exited += delegate
                {
                    this.InvokeAsync(new Action(() =>
                    {
                        if (_process == null)
                        {
                            return;
                        }

                        // From GitCommandsInstance:
                        // The process is exited already, but this command waits also until all output is received.
                        // Only WaitForExit when someone is connected to the exited event. For some reason a
                        // null reference is thrown sometimes when staging/unstaging in the commit dialog when
                        // we wait for exit, probably a timing issue...
                        try
                        {
                            _process.WaitForExit();
                        }
                        catch
                        {
                            // NOP
                        }

                        _exitcode = _process.ExitCode;
                        _process  = null;
                        _timer.Stop(true);
                        FireProcessExited();
                    }));
                };

                process.Exited += (sender, args) =>
                {
                    DateTime executionEndTimestamp = DateTime.Now;
                    AppSettings.GitLog.Log(quotedCmd + " " + arguments, executionStartTimestamp, executionEndTimestamp);
                };

                process.Start();
                _process = process;
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
            }
            catch (Exception ex)
            {
                ex.Data.Add("command", command);
                ex.Data.Add("arguments", arguments);
                throw;
            }
        }
Exemplo n.º 17
0
 private void ContinueBisect(GitBisectOption bisectOption)
 {
     FormProcess.ShowDialog(this, process: null, arguments: GitCommandHelpers.ContinueBisectCmd(bisectOption), Module.WorkingDir, input: null, useDialogSettings: false);
     Close();
 }
Exemplo n.º 18
0
        private void LoadFileHistory()
        {
            FileChanges.Visible = true;

            if (string.IsNullOrEmpty(FileName))
            {
                return;
            }

            _asyncLoader.LoadAsync(
                () => BuildFilter(),
                filter =>
            {
                FileChanges.SetFilters(filter);
                FileChanges.Load();
            });

            return;

            (string revision, string path) BuildFilter()
            {
                var fileName = FileName;

                // Replace windows path separator to Linux path separator.
                // This is needed to keep the file history working when started from file tree in
                // browse dialog.
                fileName = fileName.ToPosixPath();

                // we will need this later to look up proper casing for the file
                var fullFilePath = _fullPathResolver.Resolve(fileName);

                // The section below contains native windows (kernel32) calls
                // and breaks on Linux. Only use it on Windows. Casing is only
                // a Windows problem anyway.
                if (EnvUtils.RunningOnWindows() && File.Exists(fullFilePath))
                {
                    // grab the 8.3 file path
                    var shortPath = new StringBuilder(4096);
                    NativeMethods.GetShortPathName(fullFilePath, shortPath, shortPath.Capacity);

                    // use 8.3 file path to get properly cased full file path
                    var longPath = new StringBuilder(4096);
                    NativeMethods.GetLongPathName(shortPath.ToString(), longPath, longPath.Capacity);

                    // remove the working directory and now we have a properly cased file name.
                    fileName = longPath.ToString().Substring(Module.WorkingDir.Length).ToPosixPath();
                }

                if (fileName.StartsWith(Module.WorkingDir, StringComparison.InvariantCultureIgnoreCase))
                {
                    fileName = fileName.Substring(Module.WorkingDir.Length);
                }

                FileName = fileName;

                var res = (revision : (string)null, path : $" \"{fileName}\"");

                if (AppSettings.FollowRenamesInFileHistory && !Directory.Exists(fullFilePath))
                {
                    // git log --follow is not working as expected (see  http://kerneltrap.org/mailarchive/git/2009/1/30/4856404/thread)
                    //
                    // But we can take a more complicated path to get reasonable results:
                    //  1. use git log --follow to get all previous filenames of the file we are interested in
                    //  2. use git log "list of files names" to get the history graph
                    //
                    // note: This implementation is quite a quick hack (by someone who does not speak C# fluently).
                    //

                    var args = new GitArgumentBuilder("log")
                    {
                        "--format=\"%n\"",
                        "--name-only",
                        "--format",
                        GitCommandHelpers.FindRenamesAndCopiesOpts(),
                        "--",
                        fileName.Quote()
                    };

                    var listOfFileNames = new StringBuilder(fileName.Quote());

                    // keep a set of the file names already seen
                    var setOfFileNames = new HashSet <string> {
                        fileName
                    };

                    var lines = Module.GetGitOutputLines(args, GitModule.LosslessEncoding);

                    foreach (var line in lines.Select(GitModule.ReEncodeFileNameFromLossless))
                    {
                        if (!string.IsNullOrEmpty(line) && setOfFileNames.Add(line))
                        {
                            listOfFileNames.Append(" \"");
                            listOfFileNames.Append(line);
                            listOfFileNames.Append('\"');
                        }
                    }

                    // here we need --name-only to get the previous filenames in the revision graph
                    res.path      = listOfFileNames.ToString();
                    res.revision += " --name-only --parents" + GitCommandHelpers.FindRenamesAndCopiesOpts();
                }
                else if (AppSettings.FollowRenamesInFileHistory)
                {
                    // history of a directory
                    // --parents doesn't work with --follow enabled, but needed to graph a filtered log
                    res.revision = " " + GitCommandHelpers.FindRenamesOpt() + " --follow --parents";
                }
                else
                {
                    // rename following disabled
                    res.revision = " --parents";
                }

                if (AppSettings.FullHistoryInFileHistory)
                {
                    res.revision = string.Concat(" --full-history --simplify-merges ", res.revision);
                }

                return(res);
            }
        }
Exemplo n.º 19
0
        private bool PublishChange(IWin32Window owner)
        {
            string branch = _NO_TRANSLATE_Branch.Text.Trim();

            if (string.IsNullOrEmpty(_NO_TRANSLATE_Remotes.Text))
            {
                MessageBox.Show(owner, _selectRemote.Text);
                return(false);
            }
            if (string.IsNullOrEmpty(branch))
            {
                MessageBox.Show(owner, _selectBranch.Text);
                return(false);
            }

            GerritUtil.StartAgent(owner, Module, _NO_TRANSLATE_Remotes.Text);

            string targetRef = PublishDraft.Checked ? "drafts" : "publish";

            var pushCommand = UICommands.CreateRemoteCommand();

            string targetBranch = "refs/" + targetRef + "/" + branch;
            string topic        = _NO_TRANSLATE_Topic.Text.Trim();

            if (!string.IsNullOrEmpty(topic))
            {
                targetBranch += "/" + topic;
            }

            pushCommand.CommandText = GitCommandHelpers.PushCmd(
                _NO_TRANSLATE_Remotes.Text,
                targetBranch,
                false
                );
            pushCommand.Remote = _NO_TRANSLATE_Remotes.Text;
            pushCommand.Title  = _publishCaption.Text;

            pushCommand.Execute();

            if (!pushCommand.ErrorOccurred)
            {
                bool   hadNewChanges = false;
                string change        = null;

                foreach (string line in pushCommand.CommandOutput.Split('\n'))
                {
                    if (hadNewChanges)
                    {
                        change = line;
                        const string remotePrefix = "remote:";

                        if (change.StartsWith(remotePrefix))
                        {
                            change = change.Substring(remotePrefix.Length);
                        }

                        int escapePos = change.LastIndexOf((char)27);
                        if (escapePos != -1)
                        {
                            change = change.Substring(0, escapePos);
                        }

                        change = change.Trim();

                        int spacePos = change.IndexOf(' ');
                        if (spacePos != -1)
                        {
                            change = change.Substring(0, spacePos);
                        }

                        break;
                    }
                    else if (line.Contains("New Changes"))
                    {
                        hadNewChanges = true;
                    }
                }

                if (change != null)
                {
                    FormGerritChangeSubmitted.ShowSubmitted(owner, change);
                }
            }

            return(true);
        }
Exemplo n.º 20
0
        public override bool Execute(GitUIBaseEventArgs args)
        {
            var module        = (GitModule)args.GitModule;
            var allChangesCmd = GitCommands.GitCommandHelpers.GetAllChangedFilesCmd(true, UntrackedFilesMode.All, IgnoreSubmodulesMode.All);;

            int exitCode;

            exitCode = args.GitModule.RunGitCmdResult("submodule update --init --recursive").ExitCode;

            var resultString = args.GitModule.RunGitCmdResult(allChangesCmd);
            var statusString = resultString.StdOutput;
            var changedFiles = GitCommandHelpers.GetAllChangedFilesFromString(module, statusString);

            if (changedFiles.Count != 0)
            {
                MessageBox.Show("Commit edilmeyi bekleyen dosyalarınız var. Lütfen işlemden önce bu dosyaları commit ediniz!");
                return(false);
            }

            var currentBranch = (args.GitModule.GetSelectedBranch() ?? "").ToLowerInvariant();

            // master branch inde değilsek ona geçelim
            var branch = currentBranch;

            if (branch != "master")
            {
                var switchBranchCmd = GitCommandHelpers.CheckoutCmd("master", LocalChangesAction.DontChange);
                exitCode = args.GitModule.RunGitCmdResult(switchBranchCmd).ExitCode;

                branch = args.GitModule.GetSelectedBranch().ToLowerInvariant();
                if (branch != "master")
                {
                    MessageBox.Show("Master branch'ine geçiş yapılamadı. İşleme devam edilemiyor!");
                    return(false);
                }
            }

            // master a direk commit olmadığını varsayıyoruz, dolayısıyla rebase e gerek yok, sadece pull yapalım.
            // rebase yaparsak bazı merge commitleriyle ilgili kayıp yaşanabilir
            // bu arada eğer local te bir şekilde master da commit varsa (merkezde olmayan??) branch bir önceki committen alınmış olur
            var pullCmd    = module.PullCmd("origin", "master", "master", false);
            var cmdResult  = args.GitModule.RunGitCmdResult(pullCmd);
            var pullResult = cmdResult.StdError;

            exitCode = cmdResult.ExitCode;

            if (exitCode != 0)
            {
                MessageBox.Show("Pull işlemi esnasında şu hata alındı:\n" +
                                pullResult + "\nExitCode:" + exitCode);
                return(true);
            }

            currentBranch = (args.GitModule.GetSelectedBranch() ?? "").ToLowerInvariant();
            if (currentBranch.IsNullOrEmpty() || currentBranch.ToLowerInvariant() != "master")
            {
                MessageBox.Show("Bu işlem master branch'inde yapılmalıdır!");
                return(false);
            }

            var featureMergeHash = Clipboard.GetText();

            if (Dialogs.Prompt("Canlıya gönderilecek feature branch'in TEST'e birleştirildiği commit hash'ini giriniz",
                               "Feature Branch Merge", ref featureMergeHash) != DialogResult.OK)
            {
                return(false);
            }

            var mergeInfo  = module.ShowSha1(featureMergeHash);
            var mergeLines = mergeInfo.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            if (mergeLines.Length < 3 ||
                !mergeLines[0].StartsWith("commit ", StringComparison.OrdinalIgnoreCase) ||
                !mergeLines[1].StartsWith("Merge: ", StringComparison.OrdinalIgnoreCase) ||
                !mergeLines[2].StartsWith("Author: ", StringComparison.OrdinalIgnoreCase) ||
                !mergeLines[4].Trim().StartsWith("Merge branch '", StringComparison.OrdinalIgnoreCase) ||
                mergeLines[4].IndexOf("' into", StringComparison.OrdinalIgnoreCase) < 0)
            {
                Dialogs.Alert("Merge commit'i yerine aşağıdaki sonuç bulundu:\n\n" +
                              mergeInfo);
                return(false);
            }

            var mergeTitle = mergeLines[4].Trim();

            mergeTitle = mergeTitle.Substring("Merge branch '".Length);
            var mergeIntoIdx = mergeTitle.IndexOf("' into");
            var branchName   = mergeTitle.Substring(0, mergeIntoIdx);

            var info  = module.ShowSha1(featureMergeHash + "^2");
            var lines = info.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            if (lines.Length < 3 ||
                ((!lines[0].StartsWith("commit ", StringComparison.OrdinalIgnoreCase) ||
                  !lines[1].StartsWith("Author: ", StringComparison.OrdinalIgnoreCase)) &&
                 (!lines[0].StartsWith("commit ", StringComparison.OrdinalIgnoreCase) ||
                  !lines[1].StartsWith("Merge: ", StringComparison.OrdinalIgnoreCase) ||
                  !lines[2].StartsWith("Author: ", StringComparison.OrdinalIgnoreCase) ||
                  info.Contains("' into test") ||
                  info.Contains("' into 'test"))))
            {
                Dialogs.Alert("Birleştirilen feature branch'i yerine aşağıdaki sonuç bulundu:\n\n" +
                              info);
                return(false);
            }

            var author = lines[1].Trim().Substring("Author: ".Length).Trim();
            var commit = lines[0].Trim().Substring("commit ".Length).Trim();

            var tagName   = "published-" + branchName;
            var tagResult = module.Tag(tagName, commit, false, false);

            if (!tagResult.IsNullOrWhiteSpace())
            {
                Dialogs.Alert("TAG RESULT: " + tagResult);
            }

            var pushTagCmd = GitCommandHelpers.PushTagCmd("origin", tagName, false);

            cmdResult = args.GitModule.RunGitCmdResult(pushTagCmd);
            var pushTagResult = cmdResult.StdError;

            exitCode = cmdResult.ExitCode;

            if (exitCode != 0)
            {
                MessageBox.Show("Tag push işlemi esnasında şu hata alındı:\n" + pushTagResult + "\nExitCode:" + exitCode);
                return(true);
            }

            var mergeCmd = GitCommandHelpers.MergeBranchCmd(commit, true, true, true, null);

            cmdResult = args.GitModule.RunGitCmdResult(mergeCmd);
            var mergeResult = cmdResult.StdError;

            exitCode = cmdResult.ExitCode;

            if (exitCode != 0 && exitCode != 128)
            {
                MessageBox.Show("Merge işlemi esnasında şu hata alındı:\n" + mergeResult + "\nExitCode:" + exitCode);
                return(true);
            }

            var gitDirectory = args.GitModule.GetGitDirectory();
            var msg          = File.ReadAllText(Path.Combine(gitDirectory, "SQUASH_MSG"));

            msg = "Publish Branch '" + branchName + "'\n\n" + msg;
            var msgFile = Path.Combine(gitDirectory, "SQUASH_MSG2");

            File.WriteAllText(msgFile, msg);
            try
            {
                var commitCmd = "commit --author=\"" + author + "\" --file=\"" + msgFile.Replace("\\", "/") + "\"";
                cmdResult = args.GitModule.RunGitCmdResult(commitCmd);
                var commitResult = cmdResult.StdError;
                exitCode = cmdResult.ExitCode;

                if (exitCode != 0)
                {
                    MessageBox.Show("Commit işlemi esnasında şu hata alındı:\n" + commitResult + "\nExitCode:" + exitCode);
                    return(true);
                }
            }
            finally
            {
                File.Delete(msgFile);
            }

            MessageBox.Show(String.Format("{0} feature branch'i başarıyla MASTER'a merge edildi.\n\nDeğişiklikleri inceleyip sürüm çıkabilirsiniz.", branchName));

            return(true);
        }
Exemplo n.º 21
0
 private void Stop_Click(object sender, EventArgs e)
 {
     FormProcess.ShowDialog(this, GitCommandHelpers.StopBisectCmd());
     Close();
 }
Exemplo n.º 22
0
 private void Bad_Click(object sender, EventArgs e)
 {
     new FormProcess(GitCommandHelpers.ContinueBisectCmd(false), false).ShowDialog(this);
     Close();
 }
 public void SubmoduleSyncCmd()
 {
     Assert.AreEqual("submodule sync \"foo\"", GitCommandHelpers.SubmoduleSyncCmd("foo"));
     Assert.AreEqual("submodule sync", GitCommandHelpers.SubmoduleSyncCmd(""));
     Assert.AreEqual("submodule sync", GitCommandHelpers.SubmoduleSyncCmd(null));
 }
Exemplo n.º 24
0
        private bool PushChanges(IWin32Window owner)
        {
            if (PushToUrl.Checked && string.IsNullOrEmpty(PushDestination.Text))
            {
                MessageBox.Show(owner, _selectDestinationDirectory.Text);
                return(false);
            }
            if (PushToRemote.Checked && string.IsNullOrEmpty(_NO_TRANSLATE_Remotes.Text))
            {
                MessageBox.Show(owner, _selectRemote.Text);
                return(false);
            }
            if (TabControlTagBranch.SelectedTab == TagTab && string.IsNullOrEmpty(TagComboBox.Text) &&
                !PushAllTags.Checked)
            {
                MessageBox.Show(owner, _selectTag.Text);
                return(false);
            }

            //Extra check if the branch is already known to the remote, give a warning when not.
            //This is not possible when the remote is an URL, but this is ok since most users push to
            //known remotes anyway.
            if (TabControlTagBranch.SelectedTab == BranchTab && PushToRemote.Checked)
            {
                //If the current branch is not the default push, and not known by the remote
                //(as far as we know since we are disconnected....)
                if (RemoteBranch.Text != GetDefaultPushRemote(_NO_TRANSLATE_Remotes.Text) &&
                    !Module.GetHeads(true, true).Any(x => x.Remote == _NO_TRANSLATE_Remotes.Text && x.LocalName == RemoteBranch.Text))
                {
                    //Ask if this is really what the user wants
                    if (MessageBox.Show(owner, _branchNewForRemote.Text, _pushCaption.Text, MessageBoxButtons.YesNo) ==
                        DialogResult.No)
                    {
                        return(false);
                    }
                }
            }

            if (PushToUrl.Checked)
            {
                Repositories.AddMostRecentRepository(PushDestination.Text);
            }
            Settings.PushAllTags         = PushAllTags.Checked;
            Settings.AutoPullOnRejected  = AutoPullOnRejected.Checked;
            Settings.RecursiveSubmodules = RecursiveSubmodules.SelectedIndex;

            var    remote = "";
            string destination;

            if (PushToUrl.Checked)
            {
                destination = PushDestination.Text;
            }
            else
            {
                if (GitCommandHelpers.Plink())
                {
                    if (!File.Exists(Settings.Pageant))
                    {
                        MessageBox.Show(owner, _cannotLoadPutty.Text, PuttyText);
                    }
                    else
                    {
                        Module.StartPageantForRemote(_NO_TRANSLATE_Remotes.Text);
                    }
                }

                destination = _NO_TRANSLATE_Remotes.Text;
                remote      = _NO_TRANSLATE_Remotes.Text.Trim();
            }

            string pushCmd;

            if (TabControlTagBranch.SelectedTab == BranchTab)
            {
                bool track = ReplaceTrackingReference.Checked;
                if (!track && !string.IsNullOrWhiteSpace(RemoteBranch.Text))
                {
                    GitHead selectedLocalBranch = _NO_TRANSLATE_Branch.SelectedItem as GitHead;
                    track = selectedLocalBranch != null && string.IsNullOrEmpty(selectedLocalBranch.TrackingRemote);

                    string[] remotes = _NO_TRANSLATE_Remotes.DataSource as string[];
                    if (remotes != null)
                    {
                        foreach (string remoteBranch in remotes)
                        {
                            if (!string.IsNullOrEmpty(remoteBranch) && _NO_TRANSLATE_Branch.Text.StartsWith(remoteBranch))
                            {
                                track = false;
                            }
                        }
                    }

                    if (track)
                    {
                        DialogResult result = MessageBox.Show(String.Format(_updateTrackingReference.Text, selectedLocalBranch.Name, RemoteBranch.Text), _pushCaption.Text, MessageBoxButtons.YesNoCancel);

                        if (result == DialogResult.Cancel)
                        {
                            return(false);
                        }

                        track = result == DialogResult.OK;
                    }
                }

                pushCmd = GitCommandHelpers.PushCmd(destination, _NO_TRANSLATE_Branch.Text, RemoteBranch.Text,
                                                    PushAllBranches.Checked, ForcePushBranches.Checked, track, RecursiveSubmodules.SelectedIndex);
            }
            else if (TabControlTagBranch.SelectedTab == TagTab)
            {
                pushCmd = GitCommandHelpers.PushTagCmd(destination, TagComboBox.Text, PushAllTags.Checked,
                                                       ForcePushBranches.Checked);
            }
            else
            {
                // Push Multiple Branches Tab selected
                var pushActions = new List <GitPushAction>();
                foreach (DataRow row in _branchTable.Rows)
                {
                    var push   = Convert.ToBoolean(row["Push"]);
                    var force  = Convert.ToBoolean(row["Force"]);
                    var delete = Convert.ToBoolean(row["Delete"]);

                    if (push || force)
                    {
                        pushActions.Add(new GitPushAction(row["Local"].ToString(), row["Remote"].ToString(), force));
                    }
                    else if (delete)
                    {
                        pushActions.Add(new GitPushAction(row["Remote"].ToString()));
                    }
                }
                pushCmd = GitCommandHelpers.PushMultipleCmd(destination, pushActions);
            }

            ScriptManager.RunEventScripts(Module, ScriptEvent.BeforePush);

            //controls can be accessed only from UI thread
            candidateForRebasingMergeCommit = Settings.PullMerge == Settings.PullAction.Rebase && PushToRemote.Checked && !PushAllBranches.Checked && TabControlTagBranch.SelectedTab == BranchTab;
            selectedBranch           = _NO_TRANSLATE_Branch.Text;
            selectedBranchRemote     = _NO_TRANSLATE_Remotes.Text;
            selectedRemoteBranchName = RemoteBranch.Text;

            using (var form = new FormRemoteProcess(Module, pushCmd)
            {
                Remote = remote,
                Text = string.Format(_pushToCaption.Text, destination),
                HandleOnExitCallback = HandlePushOnExit
            })
            {
                form.ShowDialog(owner);

                if (!Module.InTheMiddleOfConflictedMerge() &&
                    !Module.InTheMiddleOfRebase() && !form.ErrorOccurred())
                {
                    ScriptManager.RunEventScripts(Module, ScriptEvent.AfterPush);
                    if (_createPullRequestCB.Checked)
                    {
                        UICommands.StartCreatePullRequest(owner);
                    }
                    return(true);
                }
            }

            return(false);
        }
        private async Task <bool> DownloadChangeAsync(IWin32Window owner)
        {
            await this.SwitchToMainThreadAsync();

            string change = _NO_TRANSLATE_Change.Text.Trim();

            if (string.IsNullOrEmpty(_NO_TRANSLATE_Remotes.Text))
            {
                MessageBox.Show(owner, _selectRemote.Text);
                return(false);
            }

            if (string.IsNullOrEmpty(change))
            {
                MessageBox.Show(owner, _selectChange.Text);
                return(false);
            }

            GerritUtil.StartAgent(owner, Module, _NO_TRANSLATE_Remotes.Text);

            var reviewInfo = await LoadReviewInfoAsync();

            await this.SwitchToMainThreadAsync();

            if (reviewInfo?["id"] == null)
            {
                MessageBox.Show(owner, _cannotGetChangeDetails.Text);
                return(false);
            }

            // The user can enter both the Change-Id or the number. Here we
            // force the number to get prettier branches.

            change = (string)reviewInfo["number"];

            string topic = _NO_TRANSLATE_TopicBranch.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                var topicNode = (JValue)reviewInfo["topic"];

                topic = topicNode == null ? change : (string)topicNode.Value;
            }

            string authorValue = (string)((JValue)reviewInfo["owner"]["name"]).Value;
            string author      = Regex.Replace(authorValue.ToLowerInvariant(), "\\W+", "_");
            string branchName  = "review/" + author + "/" + topic;
            string refspec     = (string)((JValue)reviewInfo["currentPatchSet"]["ref"]).Value;

            var fetchCommand = UICommands.CreateRemoteCommand();

            fetchCommand.CommandText = FetchCommand(_NO_TRANSLATE_Remotes.Text, refspec);

            if (!RunCommand(fetchCommand, change))
            {
                return(false);
            }

            var checkoutCommand = UICommands.CreateRemoteCommand();

            checkoutCommand.CommandText = GitCommandHelpers.BranchCmd(branchName, "FETCH_HEAD", true);
            checkoutCommand.Completed  += (s, e) =>
            {
                if (e.IsError)
                {
                    if (e.Command.CommandText.Contains("already exists"))
                    {
                        // Recycle the current review branch.

                        var recycleCommand = UICommands.CreateRemoteCommand();

                        recycleCommand.CommandText = "checkout " + branchName;

                        if (!RunCommand(recycleCommand, change))
                        {
                            return;
                        }

                        var resetCommand = UICommands.CreateRemoteCommand();

                        resetCommand.CommandText = GitCommandHelpers.ResetHardCmd("FETCH_HEAD");

                        if (!RunCommand(resetCommand, change))
                        {
                            return;
                        }

                        e.IsError = false;
                    }
                }
            };

            return(RunCommand(checkoutCommand, change));
        }
Exemplo n.º 26
0
        /// <summary>
        /// silently does not save some settings if Git is not configured correctly
        /// (user notification is done elsewhere)
        /// </summary>
        public override void SaveSettings()
        {
            _gitModule.SetFilesEncoding(false, _commonLogic.ComboToEncoding(Global_FilesEncoding));

            if (_checkSettingsLogic.CanFindGitCmd())
            {
                ConfigFile globalConfig = GitCommandHelpers.GetGlobalConfig();

                if (string.IsNullOrEmpty(GlobalUserName.Text) ||
                    !GlobalUserName.Text.Equals(globalConfig.GetValue("user.name")))
                {
                    globalConfig.SetValue("user.name", GlobalUserName.Text);
                }
                if (string.IsNullOrEmpty(GlobalUserEmail.Text) ||
                    !GlobalUserEmail.Text.Equals(globalConfig.GetValue("user.email")))
                {
                    globalConfig.SetValue("user.email", GlobalUserEmail.Text);
                }
                if (string.IsNullOrEmpty(CommitTemplatePath.Text) ||
                    !CommitTemplatePath.Text.Equals(globalConfig.GetValue("commit.template")))
                {
                    globalConfig.SetValue("commit.template", CommitTemplatePath.Text);
                }
                globalConfig.SetPathValue("core.editor", GlobalEditor.Text);

                CheckSettingsLogic.SetGlobalDiffToolToConfig(globalConfig, GlobalDiffTool.Text);

                if (!string.IsNullOrEmpty(GlobalDiffTool.Text))
                {
                    globalConfig.SetPathValue(string.Format("difftool.{0}.path", GlobalDiffTool.Text), DifftoolPath.Text);
                }
                if (!string.IsNullOrEmpty(GlobalDiffTool.Text))
                {
                    globalConfig.SetPathValue(string.Format("difftool.{0}.cmd", GlobalDiffTool.Text), DifftoolCmd.Text);
                }

                globalConfig.SetValue("merge.tool", GlobalMergeTool.Text);

                if (!string.IsNullOrEmpty(GlobalMergeTool.Text))
                {
                    globalConfig.SetPathValue(string.Format("mergetool.{0}.path", GlobalMergeTool.Text), MergetoolPath.Text);
                }
                if (!string.IsNullOrEmpty(GlobalMergeTool.Text))
                {
                    globalConfig.SetPathValue(string.Format("mergetool.{0}.cmd", GlobalMergeTool.Text), MergeToolCmd.Text);
                }

                if (GlobalKeepMergeBackup.CheckState == CheckState.Checked)
                {
                    globalConfig.SetValue("mergetool.keepBackup", "true");
                }
                else if (GlobalKeepMergeBackup.CheckState == CheckState.Unchecked)
                {
                    globalConfig.SetValue("mergetool.keepBackup", "false");
                }

                if (globalAutoCrlfFalse.Checked)
                {
                    globalConfig.SetValue("core.autocrlf", "false");
                }
                if (globalAutoCrlfInput.Checked)
                {
                    globalConfig.SetValue("core.autocrlf", "input");
                }
                if (globalAutoCrlfTrue.Checked)
                {
                    globalConfig.SetValue("core.autocrlf", "true");
                }

                CommonLogic.SetEncoding(_gitModule.GetFilesEncoding(false), globalConfig, "i18n.filesEncoding");
                globalConfig.Save();
            }
        }
Exemplo n.º 27
0
        private bool PushChanges(IWin32Window owner)
        {
            ErrorOccurred = false;
            if (PushToUrl.Checked && string.IsNullOrEmpty(PushDestination.Text))
            {
                MessageBox.Show(owner, _selectDestinationDirectory.Text);
                return(false);
            }

            var selectedRemoteName = _selectedRemote.Name;

            if (PushToRemote.Checked && string.IsNullOrEmpty(selectedRemoteName))
            {
                MessageBox.Show(owner, _selectRemote.Text);
                return(false);
            }
            if (TabControlTagBranch.SelectedTab == TagTab && string.IsNullOrEmpty(TagComboBox.Text))
            {
                MessageBox.Show(owner, _selectTag.Text);
                return(false);
            }

            //Extra check if the branch is already known to the remote, give a warning when not.
            //This is not possible when the remote is an URL, but this is ok since most users push to
            //known remotes anyway.
            if (TabControlTagBranch.SelectedTab == BranchTab && PushToRemote.Checked &&
                !Module.IsBareRepository())
            {
                //If the current branch is not the default push, and not known by the remote
                //(as far as we know since we are disconnected....)
                if (_NO_TRANSLATE_Branch.Text != AllRefs &&
                    RemoteBranch.Text != _gitRemoteController.GetDefaultPushRemote(_selectedRemote, _NO_TRANSLATE_Branch.Text) &&
                    !IsBranchKnownToRemote(selectedRemoteName, RemoteBranch.Text))
                {
                    //Ask if this is really what the user wants
                    if (!AppSettings.DontConfirmPushNewBranch &&
                        DialogResult.No == MessageBox.Show(owner, _branchNewForRemote.Text, _pushCaption.Text, MessageBoxButtons.YesNo))
                    {
                        return(false);
                    }
                }
            }

            if (PushToUrl.Checked)
            {
                Repositories.AddMostRecentRepository(PushDestination.Text);
            }
            AppSettings.RecursiveSubmodules = RecursiveSubmodules.SelectedIndex;

            var    remote = "";
            string destination;

            if (PushToUrl.Checked)
            {
                destination = PushDestination.Text;
            }
            else
            {
                EnsurePageant(selectedRemoteName);

                destination = selectedRemoteName;
                remote      = selectedRemoteName.Trim();
            }

            string pushCmd;

            if (TabControlTagBranch.SelectedTab == BranchTab)
            {
                bool track = ReplaceTrackingReference.Checked;
                if (!track && !string.IsNullOrWhiteSpace(RemoteBranch.Text))
                {
                    GitRef selectedLocalBranch = _NO_TRANSLATE_Branch.SelectedItem as GitRef;
                    track = selectedLocalBranch != null && string.IsNullOrEmpty(selectedLocalBranch.TrackingRemote) &&
                            !_gitRemoteController.Remotes.Any(x => _NO_TRANSLATE_Branch.Text.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase));
                    var autoSetupMerge = Module.EffectiveConfigFile.GetValue("branch.autoSetupMerge");
                    if (autoSetupMerge.IsNotNullOrWhitespace() && autoSetupMerge.ToLowerInvariant() == "false")
                    {
                        track = false;
                    }
                    if (track && !AppSettings.DontConfirmAddTrackingRef)
                    {
                        var result = MessageBox.Show(this,
                                                     string.Format(_updateTrackingReference.Text, selectedLocalBranch.Name, RemoteBranch.Text),
                                                     _pushCaption.Text,
                                                     MessageBoxButtons.YesNoCancel);
                        if (result == DialogResult.Cancel)
                        {
                            return(false);
                        }
                        track = result == DialogResult.Yes;
                    }
                }

                if (ForcePushBranches.Checked)
                {
                    if (GitCommandHelpers.VersionInUse.SupportPushForceWithLease)
                    {
                        var choice = MessageBox.Show(this,
                                                     _useForceWithLeaseInstead.Text,
                                                     "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                                                     MessageBoxDefaultButton.Button1);
                        switch (choice)
                        {
                        case DialogResult.Yes:
                            ForcePushBranches.Checked = false;
                            ckForceWithLease.Checked  = true;
                            break;

                        case DialogResult.Cancel:
                            return(false);
                        }
                    }
                }

                if (_NO_TRANSLATE_Branch.Text == AllRefs)
                {
                    pushCmd = Module.PushAllCmd(destination, GetForcePushOption(), track, RecursiveSubmodules.SelectedIndex);
                }
                else
                {
                    pushCmd = Module.PushCmd(destination, _NO_TRANSLATE_Branch.Text, RemoteBranch.Text,
                                             GetForcePushOption(), track, RecursiveSubmodules.SelectedIndex);
                }
            }
            else if (TabControlTagBranch.SelectedTab == TagTab)
            {
                string tag         = TagComboBox.Text;
                bool   pushAllTags = false;
                if (tag == AllRefs)
                {
                    tag         = "";
                    pushAllTags = true;
                }
                pushCmd = GitCommandHelpers.PushTagCmd(destination, tag, pushAllTags, GetForcePushOption());
            }
            else
            {
                // Push Multiple Branches Tab selected
                var pushActions = new List <GitPushAction>();
                foreach (DataRow row in _branchTable.Rows)
                {
                    var push   = Convert.ToBoolean(row["Push"]);
                    var force  = Convert.ToBoolean(row["Force"]);
                    var delete = Convert.ToBoolean(row["Delete"]);

                    if (push || force)
                    {
                        pushActions.Add(new GitPushAction(row["Local"].ToString(), row["Remote"].ToString(), force));
                    }
                    else if (delete)
                    {
                        pushActions.Add(GitPushAction.DeleteRemoteBranch(row["Remote"].ToString()));
                    }
                }
                pushCmd = GitCommandHelpers.PushMultipleCmd(destination, pushActions);
            }

            ScriptManager.RunEventScripts(this, ScriptEvent.BeforePush);

            //controls can be accessed only from UI thread
            _selectedBranch = _NO_TRANSLATE_Branch.Text;
            _candidateForRebasingMergeCommit = PushToRemote.Checked && (_selectedBranch != AllRefs) && TabControlTagBranch.SelectedTab == BranchTab;
            _selectedRemoteBranchName        = RemoteBranch.Text;

            using (var form = new FormRemoteProcess(Module, pushCmd)
            {
                Remote = remote,
                Text = string.Format(_pushToCaption.Text, destination),
                HandleOnExitCallback = HandlePushOnExit
            })
            {
                form.ShowDialog(owner);
                ErrorOccurred = form.ErrorOccurred();

                if (!Module.InTheMiddleOfAction() && !form.ErrorOccurred())
                {
                    ScriptManager.RunEventScripts(this, ScriptEvent.AfterPush);
                    if (_createPullRequestCB.Checked)
                    {
                        UICommands.StartCreatePullRequest(owner);
                    }
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 28
0
        protected override void OnLoadSettings()
        {
            ConfigFile globalConfig = GitCommandHelpers.GetGlobalConfig();

            _commonLogic.EncodingToCombo(_gitModule.GetFilesEncoding(false), Global_FilesEncoding);

            GlobalUserName.Text     = globalConfig.GetValue("user.name");
            GlobalUserEmail.Text    = globalConfig.GetValue("user.email");
            GlobalEditor.Text       = globalConfig.GetPathValue("core.editor");
            GlobalMergeTool.Text    = globalConfig.GetValue("merge.tool");
            CommitTemplatePath.Text = globalConfig.GetValue("commit.template");

            if (!string.IsNullOrEmpty(GlobalMergeTool.Text))
            {
                MergetoolPath.Text = globalConfig.GetPathValue(string.Format("mergetool.{0}.path", GlobalMergeTool.Text));
            }
            if (!string.IsNullOrEmpty(GlobalMergeTool.Text))
            {
                MergeToolCmd.Text = globalConfig.GetPathValue(string.Format("mergetool.{0}.cmd", GlobalMergeTool.Text));
            }

            GlobalDiffTool.Text = CheckSettingsLogic.GetGlobalDiffToolFromConfig();

            if (!string.IsNullOrEmpty(GlobalDiffTool.Text))
            {
                DifftoolPath.Text = globalConfig.GetPathValue(string.Format("difftool.{0}.path", GlobalDiffTool.Text));
            }
            if (!string.IsNullOrEmpty(GlobalDiffTool.Text))
            {
                DifftoolCmd.Text = globalConfig.GetPathValue(string.Format("difftool.{0}.cmd", GlobalDiffTool.Text));
            }

            CommonLogic.SetCheckboxFromString(GlobalKeepMergeBackup, globalConfig.GetValue("mergetool.keepBackup"));

            string globalAutocrlf = string.Empty;

            if (globalConfig.HasValue("core.autocrlf"))
            {
                globalAutocrlf = globalConfig.GetValue("core.autocrlf").ToLower();
            }
            else if (!string.IsNullOrEmpty(Settings.GitBinDir))
            {
                try
                {
                    //the following lines only work for msysgit (i think). MSysgit has a config file
                    //in the etc directory which is checked after the local and global config. In
                    //practice this is only used to core.autocrlf. If there are more cases, we might
                    //need to consider a better solution.
                    var configFile =
                        new ConfigFile(Path.GetDirectoryName(Settings.GitBinDir).Replace("bin", "etc\\gitconfig"), false);
                    globalAutocrlf = configFile.GetValue("core.autocrlf").ToLower();
                }
                catch
                {
                }
            }

            globalAutoCrlfFalse.Checked = globalAutocrlf == "false";
            globalAutoCrlfInput.Checked = globalAutocrlf == "input";
            globalAutoCrlfTrue.Checked  = globalAutocrlf == "true";
        }
Exemplo n.º 29
0
        private bool PushChanges(IWin32Window owner)
        {
            ErrorOccurred = false;
            if (PushToUrl.Checked && string.IsNullOrEmpty(PushDestination.Text))
            {
                MessageBox.Show(owner, _selectDestinationDirectory.Text);
                return(false);
            }
            if (PushToRemote.Checked && string.IsNullOrEmpty(_NO_TRANSLATE_Remotes.Text))
            {
                MessageBox.Show(owner, _selectRemote.Text);
                return(false);
            }
            if (TabControlTagBranch.SelectedTab == TagTab && string.IsNullOrEmpty(TagComboBox.Text))
            {
                MessageBox.Show(owner, _selectTag.Text);
                return(false);
            }

            //Extra check if the branch is already known to the remote, give a warning when not.
            //This is not possible when the remote is an URL, but this is ok since most users push to
            //known remotes anyway.
            if (TabControlTagBranch.SelectedTab == BranchTab && PushToRemote.Checked &&
                !Module.IsBareRepository())
            {
                //If the current branch is not the default push, and not known by the remote
                //(as far as we know since we are disconnected....)
                if (_NO_TRANSLATE_Branch.Text != AllRefs &&
                    RemoteBranch.Text != GetDefaultPushRemote(_NO_TRANSLATE_Remotes.Text, _NO_TRANSLATE_Branch.Text) &&
                    !Module.GetRefs(false, true).Any(x => x.TrackingRemote == _NO_TRANSLATE_Remotes.Text && x.Name == RemoteBranch.Text))
                {
                    //Ask if this is really what the user wants
                    if (!AppSettings.DontConfirmPushNewBranch &&
                        MessageBox.Show(owner, _branchNewForRemote.Text, _pushCaption.Text, MessageBoxButtons.YesNo) ==
                        DialogResult.No)
                    {
                        return(false);
                    }
                }
            }

            if (PushToUrl.Checked)
            {
                Repositories.AddMostRecentRepository(PushDestination.Text);
            }
            AppSettings.RecursiveSubmodules = RecursiveSubmodules.SelectedIndex;

            var    remote = "";
            string destination;

            if (PushToUrl.Checked)
            {
                destination = PushDestination.Text;
            }
            else
            {
                if (GitCommandHelpers.Plink())
                {
                    if (!File.Exists(AppSettings.Pageant))
                    {
                        MessageBoxes.PAgentNotFound(owner);
                    }
                    else
                    {
                        Module.StartPageantForRemote(_NO_TRANSLATE_Remotes.Text);
                    }
                }

                destination = _NO_TRANSLATE_Remotes.Text;
                remote      = _NO_TRANSLATE_Remotes.Text.Trim();
            }

            string pushCmd;

            if (TabControlTagBranch.SelectedTab == BranchTab)
            {
                bool track = ReplaceTrackingReference.Checked;
                if (!track && !string.IsNullOrWhiteSpace(RemoteBranch.Text))
                {
                    GitRef selectedLocalBranch = _NO_TRANSLATE_Branch.SelectedItem as GitRef;
                    track = selectedLocalBranch != null && string.IsNullOrEmpty(selectedLocalBranch.TrackingRemote);

                    string[] remotes = _NO_TRANSLATE_Remotes.DataSource as string[];
                    if (remotes != null)
                    {
                        foreach (string remoteBranch in remotes)
                        {
                            if (!string.IsNullOrEmpty(remoteBranch) && _NO_TRANSLATE_Branch.Text.StartsWith(remoteBranch))
                            {
                                track = false;
                            }
                        }
                    }

                    if (track && !AppSettings.DontConfirmAddTrackingRef)
                    {
                        DialogResult result = MessageBox.Show(String.Format(_updateTrackingReference.Text, selectedLocalBranch.Name, RemoteBranch.Text), _pushCaption.Text, MessageBoxButtons.YesNoCancel);

                        if (result == DialogResult.Cancel)
                        {
                            return(false);
                        }

                        track = result == DialogResult.Yes;
                    }
                }

                // Try to make source rev into a fully qualified branch name. If that
                // doesn't exist, then it must be something other than a branch, so
                // fall back to using the name just as it was passed in.
                string srcRev          = "";
                bool   pushAllBranches = false;
                if (_NO_TRANSLATE_Branch.Text == AllRefs)
                {
                    pushAllBranches = true;
                }
                else
                {
                    srcRev = GitCommandHelpers.GetFullBranchName(_NO_TRANSLATE_Branch.Text);
                    if (String.IsNullOrEmpty(Module.RevParse(srcRev)))
                    {
                        srcRev = _NO_TRANSLATE_Branch.Text;
                    }
                }

                pushCmd = GitCommandHelpers.PushCmd(destination, srcRev, RemoteBranch.Text,
                                                    pushAllBranches, ForcePushBranches.Checked, track, RecursiveSubmodules.SelectedIndex);
            }
            else if (TabControlTagBranch.SelectedTab == TagTab)
            {
                string tag         = TagComboBox.Text;
                bool   pushAllTags = false;
                if (tag == AllRefs)
                {
                    tag         = "";
                    pushAllTags = true;
                }
                pushCmd = GitCommandHelpers.PushTagCmd(destination, tag, pushAllTags,
                                                       ForcePushBranches.Checked);
            }
            else
            {
                // Push Multiple Branches Tab selected
                var pushActions = new List <GitPushAction>();
                foreach (DataRow row in _branchTable.Rows)
                {
                    var push   = Convert.ToBoolean(row["Push"]);
                    var force  = Convert.ToBoolean(row["Force"]);
                    var delete = Convert.ToBoolean(row["Delete"]);

                    if (push || force)
                    {
                        pushActions.Add(new GitPushAction(row["Local"].ToString(), row["Remote"].ToString(), force));
                    }
                    else if (delete)
                    {
                        pushActions.Add(GitPushAction.DeleteRemoteBranch(row["Remote"].ToString()));
                    }
                }
                pushCmd = GitCommandHelpers.PushMultipleCmd(destination, pushActions);
            }

            ScriptManager.RunEventScripts(this, ScriptEvent.BeforePush);

            //controls can be accessed only from UI thread
            _selectedBranch = _NO_TRANSLATE_Branch.Text;
            _candidateForRebasingMergeCommit = PushToRemote.Checked && (_selectedBranch != AllRefs) && TabControlTagBranch.SelectedTab == BranchTab;
            _selectedBranchRemote            = _NO_TRANSLATE_Remotes.Text;
            _selectedRemoteBranchName        = RemoteBranch.Text;

            using (var form = new FormRemoteProcess(Module, pushCmd)
            {
                Remote = remote,
                Text = string.Format(_pushToCaption.Text, destination),
                HandleOnExitCallback = HandlePushOnExit
            })
            {
                form.ShowDialog(owner);
                ErrorOccurred = form.ErrorOccurred();

                if (!Module.InTheMiddleOfConflictedMerge() &&
                    !Module.InTheMiddleOfRebase() && !form.ErrorOccurred())
                {
                    ScriptManager.RunEventScripts(this, ScriptEvent.AfterPush);
                    if (_createPullRequestCB.Checked)
                    {
                        UICommands.StartCreatePullRequest(owner);
                    }
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 30
0
 public void ResetCmd(ResetMode mode, string commit, string file, string expected)
 {
     Assert.AreEqual(expected, GitCommandHelpers.ResetCmd(mode, commit, file).Arguments);
 }