/// <summary> /// Requires absolute path /// </summary> /// <param name="fileName"></param> public void UnStageFile(string fileName) { if (!this.HasGitRepository) { return; } var fileNameRel = GetRelativeFileName(fileName); if (GitBash.Exists) { if (head == null) { GitBash.Run(string.Format("rm --cached -- \"{0}\"", fileNameRel), this.GitWorkingDirectory); } else { GitBash.Run(string.Format("reset -- \"{0}\"", fileNameRel), this.GitWorkingDirectory); } } else { ResetCommand resetCommand = new Git(repository).Reset(); resetCommand.AddPath(GetRelativeFileNameForGit(fileName)); resetCommand.SetRef(Constants.HEAD); resetCommand.Call(); } this.cache.Remove(GetCacheKey(fileName)); this.changedFiles = null; }
public string DiffFile(string fileName) { var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".diff"); try { var status = GetFileStatus(fileName); if (status == GitFileStatus.NotControlled || status == GitFileStatus.New || status == GitFileStatus.Added) { tmpFileName = Path.ChangeExtension(tmpFileName, Path.GetExtension(fileName)); File.Copy(Path.Combine(WorkingDirectory, fileName), tmpFileName); if (IsBinaryFile(tmpFileName)) { File.Delete(tmpFileName); File.WriteAllText(tmpFileName, "Binary file: " + fileName); } return(tmpFileName); } GitBash.RunCmd(string.Format("diff HEAD -- \"{0}\" > \"{1}\"", fileName, tmpFileName), WorkingDirectory); } catch (Exception ex) { File.WriteAllText(tmpFileName, ex.Message); } return(tmpFileName); }
public void CheckOutBranch(string branch, bool createNew = false) { if (!this.HasGitRepository) { return; } if (GitBash.Exists) { try { GitBash.Run(string.Format("checkout {0} {1}", (createNew ? "-b" : ""), branch), this.GitWorkingDirectory); } catch (Exception ex) { if (!ex.Message.StartsWith("Switched to a new branch")) { throw; } } } else { Git git = new Git(this.repository); git.Checkout().SetName(branch) .SetCreateBranch(createNew) .Call(); } }
public string AmendCommit(string message) { if (!HasGitRepository) { return(null); } if (string.IsNullOrEmpty(message)) { throw new ArgumentException("Commit message must not be null or empty!", "message"); } string msg = ""; if (GitBash.Exists) { var msgFile = Path.Combine(this.repository.Directory, "COMMITMESSAGE"); File.WriteAllText(msgFile, message); msg = GitBash.Run(string.Format("commit --amend -F \"{0}\"", msgFile), this.GitWorkingDirectory); if (msg.IndexOf('\n') > 0) { msg = msg.Split('\n')[0]; } File.Delete(msgFile); } else { var git = new Git(this.repository); var rev = git.Commit().SetAmend(true).SetMessage(message).Call(); msg = rev.Name; } Refresh(); return(msg); }
public void EditIngoreFile() { var ignoreFile = Path.Combine(WorkingDirectory, ".gitignore"); var ret = GitBash.Run("config core.editor", WorkingDirectory); if (!ret.HasError && ret.Output.Trim() != "") { var editor = ret.Output.Trim(); if (editor.Length == 0) { editor = "notepad.exe"; } var cmd = string.Format("{0} \"{1}\"", editor, ignoreFile); cmd = cmd.Replace("/", "\\"); var pinfo = new ProcessStartInfo("cmd.exe") { Arguments = "/C \"" + cmd + "\"", UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = this.WorkingDirectory, }; Process.Start(pinfo); } }
internal IList <GitFile> GetChangedFiles() { if (!HasGitRepository) { return(new List <GitFile>()); } if (GitBash.Exists) { var output = GitBash.Run("status --porcelain -z --untracked-files", this.GitWorkingDirectory); return(ParseGitStatus(output)); } else { var list = new List <GitFile>(); var treeWalk = new TreeWalk(this.repository); treeWalk.Recursive = true; treeWalk.Filter = TreeFilter.ANY_DIFF; var id = repository.Resolve(Constants.HEAD); if (id != null) { treeWalk.AddTree(new RevWalk(repository).ParseTree(id)); } else { treeWalk.AddTree(new EmptyTreeIterator()); } treeWalk.AddTree(new DirCacheIterator(this.repository.ReadDirCache())); treeWalk.AddTree(new FileTreeIterator(this.repository)); var filters = new TreeFilter[] { new SkipWorkTreeFilter(INDEX), new IndexDiffFilter(INDEX, WORKDIR) }; treeWalk.Filter = AndTreeFilter.Create(filters); while (treeWalk.Next()) { WorkingTreeIterator workingTreeIterator = treeWalk.GetTree <WorkingTreeIterator>(WORKDIR); if (workingTreeIterator != null && workingTreeIterator.IsEntryIgnored()) { continue; } var fileName = GetFullPath(treeWalk.PathString); if (Directory.Exists(fileName)) { continue; // this excludes sub modules } var status = GetFileStatus(treeWalk); list.Add(new GitFile { FileName = GetRelativeFileName(fileName), Status = status }); this.cache[GetCacheKey(fileName)] = status; } return(list); } }
public string DiffFile(string fileName, string commitId1, string commitId2) { try { if (!this.HasGitRepository) { return(""); } var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".diff"); var fileNameRel = GetRelativeFileName(fileName); if (GitBash.Exists) { GitBash.RunCmd(string.Format("diff {2} {3} -- \"{0}\" > \"{1}\"", fileNameRel, tmpFileName, commitId1, commitId2), this.GitWorkingDirectory); } else { HistogramDiff hd = new HistogramDiff(); hd.SetFallbackAlgorithm(null); RawText a = string.IsNullOrWhiteSpace(commitId1) ? new RawText(new byte[0]) : new RawText(this.RepositoryGraph.GetFileContent(commitId1, fileNameRel) ?? new byte[0]); RawText b = string.IsNullOrWhiteSpace(commitId2) ? new RawText(new byte[0]) : new RawText(this.RepositoryGraph.GetFileContent(commitId2, fileNameRel) ?? new byte[0]); var list = hd.Diff(RawTextComparator.DEFAULT, a, b); using (Stream stream = new FileStream(tmpFileName, System.IO.FileMode.CreateNew)) { DiffFormatter df = new DiffFormatter(stream); df.Format(list, a, b); df.Flush(); } //using (Stream mstream = new MemoryStream(), // stream = new BufferedStream(mstream)) //{ // DiffFormatter df = new DiffFormatter(stream); // df.Format(list, a, b); // df.Flush(); // stream.Seek(0, SeekOrigin.Begin); // var ret = new StreamReader(stream).ReadToEnd(); // ret = ret.Replace("\r", "").Replace("\n", "\r\n"); // File.WriteAllText(tmpFileName, ret); //} } return(tmpFileName); } catch (Exception ex) { Log.WriteLine("Refresh: {0}\r\n{1}", this.initFolder, ex.ToString()); return(""); } }
internal string GetBranchId(string name) { string id = null; var result = GitBash.Run("rev-parse " + name, this.WorkingDirectory); if (!result.HasError && !result.Output.StartsWith("fatal:")) { id = result.Output.Trim(); } return(id); }
public bool CurrentCommitHasRefs() { if (this.head == null) { return(false); } var result = GitBash.Run("show-ref --head --dereference", this.GitWorkingDirectory); var refs = result.Output.Split('\n') .Where(t => t.IndexOf(this.head.Name) >= 0); return(refs.Count() > 2); }
public string DiffFile(string fileName, string commitId1, string commitId2) { if (!this.IsGit) { return(""); } var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".diff"); var fileNameRel = fileName; GitBash.RunCmd(string.Format("diff {2} {3} -- \"{0}\" > \"{1}\"", fileNameRel, tmpFileName, commitId1, commitId2), WorkingDirectory); return(tmpFileName); }
public string Blame(string fileName) { if (!this.IsGit) { return(""); } var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".blame"); var fileNameRel = fileName; GitBash.RunCmd(string.Format("blame -M -w -- \"{0}\" > \"{1}\"", fileNameRel, tmpFileName), WorkingDirectory); return(tmpFileName); }
public void SaveFileFromLastCommit(string fileName, string tempFile) { if (!this.isGit) { return; } var head = GetBranchId("HEAD"); if (head != null) { GitBash.RunCmd(string.Format("show \"HEAD:{0}\" > \"{1}\"", fileName, tempFile), this.WorkingDirectory); } }
public string DiffFile(string fileName) { var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".diff"); try { GitBash.RunCmd(string.Format("diff HEAD -- \"{0}\" > \"{1}\"", fileName, tmpFileName), WorkingDirectory); } catch (Exception ex) { File.WriteAllText(tmpFileName, ex.Message); } return(tmpFileName); }
public GitRepository(string directory) { this.workingDirectory = directory; Refresh(); this.isGit = false; var result = GitBash.Run("rev-parse --show-toplevel", WorkingDirectory); if (!result.HasError && !result.Output.StartsWith("fatal:")) { this.workingDirectory = result.Output.Trim(); result = GitBash.Run("rev-parse --is-inside-work-tree", WorkingDirectory); isGit = string.Compare("true", result.Output.Trim(), true) == 0; } }
public static void Init(string folderName) { if (GitBash.Exists) { GitBash.Run("init", folderName); } else { var gitFolder = Path.Combine(folderName, Constants.DOT_GIT); var repo = new FileRepository(gitFolder); repo.Create(); var dir = Directory.CreateDirectory(gitFolder); dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden; } }
public IEnumerable <string> GetCommitsForFile(string fileName) { if (!this.HasGitRepository || !GitBash.Exists) { return(new string[0]); } var fileNameRel = GetRelativeFileName(fileName); var result = GitBash.Run(string.Format("log -z --ignore-space-change --pretty=format:%H -- \"{0}\"", fileNameRel), this.GitWorkingDirectory); if (!result.HasError) { return(result.Output.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries)); } return(new string[0]); }
public bool DiffTool(params string[] fileNames) { var quotedFileNames = from f in fileNames select string.Format("\"{0}\"", f); var fileList = string.Join(" ", quotedFileNames); if (fileList == "") { return(false); } var cmd = string.Format("difftool --no-prompt {0}", fileList); var t = GitBash.RunAsync(cmd, WorkingDirectory); return(true); }
public string Blame(string fileName) { if (!this.HasGitRepository) { return(""); } var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".blame"); if (GitBash.Exists) { var fileNameRel = GetRelativeFileName(fileName); GitBash.RunCmd(string.Format("blame -M -w -- \"{0}\" > \"{1}\"", fileNameRel, tmpFileName), this.GitWorkingDirectory); } return(tmpFileName); }
public void Apply(string[] diffLines, int startLine, int endLine, bool cached, bool reverse) { var difftool = new DiffTool(); var hunks = difftool.GetHunks(diffLines, startLine, endLine, reverse); if (hunks.Count() <= 0) { throw new Exception("No change selected"); } var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".diff"); using (var file = new StreamWriter(tmpFileName, false, Encoding.UTF8)) { for (int i = 0; i < 4; i++) { // Skip the line: index xxxx..xxxx if (i != 1) { var line = diffLines[i]; file.Write(FixEOL(line)); } } foreach (var hunk in hunks) { var heading = $"@@ -{hunk.OldBlock[0]},{hunk.OldBlock[1]} +{hunk.NewBlock[0]},{hunk.NewBlock[1]} @@{hunk.Heading}"; file.Write(FixEOL(heading)); foreach (var line in hunk.Lines) { file.Write(FixEOL(line)); } } } var cmd = "apply --ignore-whitespace"; if (cached) { cmd += " --cached"; } var result = GitBash.Run($"{cmd} \"{tmpFileName}\"", WorkingDirectory); File.Delete(tmpFileName); if (result.HasError) { throw new GitException(result.Error); } }
public bool CurrentCommitHasRefs() { var head = GetBranchId("HEAD"); if (head == null) { return(false); } var result = GitBash.Run("show-ref --head --dereference", WorkingDirectory); if (!result.HasError && !result.Output.StartsWith("fatal:")) { var refs = result.Output.Split('\n') .Where(t => t.IndexOf(head) >= 0); return(refs.Count() > 2); } return(false); }
private string GitRun(string cmd) { if (!this.IsGit) { return(null); } var result = GitBash.Run(cmd, this.WorkingDirectory); if (result.HasError) { throw new GitException(result.Error); } if (result.Output.StartsWith("fatal:")) { throw new GitException(result.Output); } return(result.Output); }
public void Refresh() { this.repositoryGraph = null; this.changedFiles = null; this.isGit = false; this.branch = null; this.remotes = null; this.configs = null; var result = GitBash.Run("rev-parse --show-toplevel", WorkingDirectory); if (!result.HasError && !result.Output.StartsWith("fatal:")) { this.workingDirectory = result.Output.Trim(); result = GitBash.Run("rev-parse --is-inside-work-tree", WorkingDirectory); isGit = string.Compare("true", result.Output.Trim(), true) == 0; } }
/// <summary> /// Requires absolute path /// </summary> /// <param name="fileName"></param> public void UnStageFile(string fileName) { if (!this.HasGitRepository) { return; } var fileNameRel = GetRelativeFileName(fileName); if (GitBash.Exists) { if (head == null) { GitBash.Run(string.Format("rm --cached -- \"{0}\"", fileNameRel), this.GitWorkingDirectory); } else { GitBash.Run(string.Format("reset -- \"{0}\"", fileNameRel), this.GitWorkingDirectory); } } else { TreeEntry treeEntry = null; if (commitTree != null) { treeEntry = commitTree.FindBlobMember(fileNameRel); } //var index = repository.GetIndex(); //index.RereadIfNecessary(); index.Remove(repository.WorkTree, fileName); if (treeEntry != null) { index.AddEntry(treeEntry); } index.Write(); } this.cache.Remove(GetCacheKey(fileName)); this.changedFiles = null; }
private void VerifyGit() { var isValid = false; if (GitBash.Exists) { var name = GitBash.Run("config --global user.name", "").Output; var email = GitBash.Run("config --global user.email", "").Output; isValid = !string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(email); } if (!isValid) { Settings.Show(); } else { Settings.Hide(); } }
public void SaveFileFromRepository(string fileName, string tempFile) { if (!this.HasGitRepository || this.head == null) { return; } if (GitBash.Exists) { string fileNameRel = GetRelativeFileNameForGit(fileName); GitBash.RunCmd(string.Format("show \"HEAD:{0}\" > \"{1}\"", fileNameRel, tempFile), this.GitWorkingDirectory); } else { var data = GetFileContent(fileName); using (var binWriter = new BinaryWriter(File.Open(tempFile, System.IO.FileMode.Create))) { binWriter.Write(data ?? new byte[] { }); } } }
public string DiffFileAdv(string fileName, bool diffIndex = false) { var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), diffIndex ? ".cached.diff" : ".diff"); try { if (diffIndex) { GitBash.RunCmd(string.Format("diff --cached -- \"{0}\" > \"{1}\"", fileName, tmpFileName), WorkingDirectory); } else { GitBash.RunCmd(string.Format("diff -- \"{0}\" > \"{1}\"", fileName, tmpFileName), WorkingDirectory); } } catch (Exception ex) { File.WriteAllText(tmpFileName, ex.Message); } return(tmpFileName); }
/// <summary> /// Requires absolute path /// </summary> /// <param name="fileName"></param> public void StageFile(string fileName) { if (!this.HasGitRepository) { return; } //var index = repository.GetIndex(); //index.RereadIfNecessary(); if (GitBash.Exists) { if (File.Exists(fileName)) { GitBash.Run(string.Format("add \"{0}\"", GetRelativeFileName(fileName)), this.GitWorkingDirectory); } else { GitBash.Run(string.Format("rm --cached -- \"{0}\"", GetRelativeFileName(fileName)), this.GitWorkingDirectory); } } else { index.Remove(repository.WorkTree, fileName); if (File.Exists(fileName)) { var content = File.ReadAllBytes(fileName); index.Add(repository.WorkTree, fileName, content); } else { //stage deleted index.Remove(repository.WorkTree, fileName); } index.Write(); } this.cache.Remove(GetCacheKey(fileName)); this.changedFiles = null; }
/// <summary> /// Requires absolute path /// </summary> /// <param name="fileName"></param> public void StageFile(string fileName) { if (!this.HasGitRepository) { return; } //var index = repository.GetIndex(); //index.RereadIfNecessary(); if (GitBash.Exists) { if (File.Exists(fileName)) { GitBash.Run(string.Format("add \"{0}\"", GetRelativeFileName(fileName)), this.GitWorkingDirectory); } else { GitBash.Run(string.Format("rm --cached -- \"{0}\"", GetRelativeFileName(fileName)), this.GitWorkingDirectory); } } else { if (File.Exists(fileName)) { AddCommand addCommand = new Git(repository).Add(); addCommand.AddFilepattern(GetRelativeFileNameForGit(fileName)); addCommand.Call(); } else { RmCommand rmCommand = new Git(repository).Rm(); rmCommand.AddFilepattern(GetRelativeFileNameForGit(fileName)); rmCommand.Call(); } } this.cache.Remove(GetCacheKey(fileName)); this.changedFiles = null; }
public void CheckOutFile(string fileName) { if (!this.HasGitRepository || this.head == null) { return; } string fileNameRel = GetRelativeFileName(fileName); if (GitBash.Exists) { GitBash.Run(string.Format("checkout -- \"{0}\"", fileNameRel), this.GitWorkingDirectory); } else { GitFileStatus status = GetFileStatus(fileName); SaveFileFromRepository(fileName, fileName); if (status == GitFileStatus.Staged || status == GitFileStatus.Removed) { UnStageFile(fileName); } } }
/// <summary> /// Diff working file with last commit /// </summary> /// <param name="fileName">Expect relative path</param> /// <returns>diff file in temp folder</returns> public string DiffFile(string fileName) { try { if (!this.HasGitRepository) { return(""); } var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".diff"); var status = GetFileStatus(fileName); if (head == null || status == GitFileStatus.New || status == GitFileStatus.Added) { tmpFileName = Path.ChangeExtension(tmpFileName, Path.GetExtension(fileName)); File.Copy(GetFullPath(fileName), tmpFileName); return(tmpFileName); } if (GitBash.Exists) { var fileNameRel = GetRelativeFileName(fileName); GitBash.RunCmd(string.Format("diff HEAD -- \"{0}\" > \"{1}\"", fileNameRel, tmpFileName), this.GitWorkingDirectory); } else { HistogramDiff hd = new HistogramDiff(); hd.SetFallbackAlgorithm(null); var fullName = GetFullPath(fileName); RawText b = new RawText(File.Exists(GetFullPath(fileName)) ? File.ReadAllBytes(fullName) : new byte[0]); RawText a = new RawText(GetFileContent(fileName) ?? new byte[0]); var list = hd.Diff(RawTextComparator.DEFAULT, a, b); using (Stream stream = File.Create(tmpFileName)) { DiffFormatter df = new DiffFormatter(stream); df.Format(list, a, b); df.Flush(); } //using (Stream mstream = new MemoryStream(), // stream = new BufferedStream(mstream)) //{ // DiffFormatter df = new DiffFormatter(stream); // df.Format(list, a, b); // df.Flush(); // stream.Seek(0, SeekOrigin.Begin); // var ret = new StreamReader(stream).ReadToEnd(); // File.WriteAllText(tmpFileName, ret); //} } return(tmpFileName); } catch (Exception ex) { Log.WriteLine("Refresh: {0}\r\n{1}", this.initFolder, ex.ToString()); return(""); } }