PageRenderTime 71ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/GitCommands/Git/GitModule.cs

https://github.com/ffrancomontoya/gitextensions
C# | 2952 lines | 2349 code | 452 blank | 151 comment | 407 complexity | 1d38ab80e40c5c5ea14e33e4463ef8de MD5 | raw file
Possible License(s): GPL-3.0, GPL-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Mail;
  8. using System.Security.Permissions;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using System.Threading.Tasks;
  12. using GitCommands.Config;
  13. using GitCommands.Settings;
  14. using GitCommands.Utils;
  15. using GitUIPluginInterfaces;
  16. using JetBrains.Annotations;
  17. using PatchApply;
  18. using SmartFormat;
  19. namespace GitCommands
  20. {
  21. public delegate void GitModuleChangedEventHandler(GitModule module);
  22. public enum SubmoduleStatus
  23. {
  24. Unknown,
  25. NewSubmodule,
  26. FastForward,
  27. Rewind,
  28. NewerTime,
  29. OlderTime,
  30. SameTime
  31. }
  32. /// <summary>Provides manipulation with git module.
  33. /// <remarks>Several instances may be created for submodules.</remarks></summary>
  34. [DebuggerDisplay("GitModule ( {_workingDir} )")]
  35. public sealed class GitModule : IGitModule
  36. {
  37. private static readonly Regex DefaultHeadPattern = new Regex("refs/remotes/[^/]+/HEAD", RegexOptions.Compiled);
  38. private readonly object _lock = new object();
  39. public GitModule(string workingdir)
  40. {
  41. _superprojectInit = false;
  42. _workingDir = (workingdir ?? "").EnsureTrailingPathSeparator();
  43. }
  44. #region IGitCommands
  45. [NotNull] private readonly string _workingDir;
  46. [NotNull]
  47. public string WorkingDir
  48. {
  49. get
  50. {
  51. return _workingDir;
  52. }
  53. }
  54. /// <summary>Gets the path to the git application executable.</summary>
  55. public string GitCommand
  56. {
  57. get
  58. {
  59. return AppSettings.GitCommand;
  60. }
  61. }
  62. public Version AppVersion
  63. {
  64. get
  65. {
  66. return AppSettings.AppVersion;
  67. }
  68. }
  69. public string GravatarCacheDir
  70. {
  71. get
  72. {
  73. return AppSettings.GravatarCachePath;
  74. }
  75. }
  76. #endregion
  77. private bool _superprojectInit;
  78. private GitModule _superprojectModule;
  79. private string _submoduleName;
  80. private string _submodulePath;
  81. public string SubmoduleName
  82. {
  83. get
  84. {
  85. InitSuperproject();
  86. return _submoduleName;
  87. }
  88. }
  89. public string SubmodulePath
  90. {
  91. get
  92. {
  93. InitSuperproject();
  94. return _submodulePath;
  95. }
  96. }
  97. public GitModule SuperprojectModule
  98. {
  99. get
  100. {
  101. InitSuperproject();
  102. return _superprojectModule;
  103. }
  104. }
  105. private void InitSuperproject()
  106. {
  107. if (!_superprojectInit)
  108. {
  109. string superprojectDir = FindGitSuperprojectPath(out _submoduleName, out _submodulePath);
  110. _superprojectModule = superprojectDir == null ? null : new GitModule(superprojectDir);
  111. _superprojectInit = true;
  112. }
  113. }
  114. public GitModule FindTopProjectModule()
  115. {
  116. GitModule module = SuperprojectModule;
  117. if (module == null)
  118. return null;
  119. do
  120. {
  121. if (module.SuperprojectModule == null)
  122. return module;
  123. module = module.SuperprojectModule;
  124. } while (module != null);
  125. return module;
  126. }
  127. private RepoDistSettings _settings;
  128. public RepoDistSettings Settings
  129. {
  130. get
  131. {
  132. lock (_lock)
  133. {
  134. if (_settings == null)
  135. _settings = RepoDistSettings.CreateEffective(this);
  136. }
  137. return _settings;
  138. }
  139. }
  140. private ConfigFileSettings _effectiveConfigFile;
  141. public ConfigFileSettings EffectiveConfigFile
  142. {
  143. get
  144. {
  145. lock (_lock)
  146. {
  147. if (_effectiveConfigFile == null)
  148. _effectiveConfigFile = ConfigFileSettings.CreateEffective(this);
  149. }
  150. return _effectiveConfigFile;
  151. }
  152. }
  153. public ConfigFileSettings LocalConfigFile
  154. {
  155. get
  156. {
  157. return new ConfigFileSettings(null, EffectiveConfigFile.SettingsCache);
  158. }
  159. }
  160. //encoding for files paths
  161. private static Encoding _systemEncoding;
  162. public static Encoding SystemEncoding
  163. {
  164. get
  165. {
  166. if (_systemEncoding == null)
  167. {
  168. //check whether GitExtensions works with standard msysgit or msysgit-unicode
  169. // invoke a git command that returns an invalid argument in its response, and
  170. // check if a unicode-only character is reported back. If so assume msysgit-unicode
  171. // git config --get with a malformed key (no section) returns:
  172. // "error: key does not contain a section: <key>"
  173. const string controlStr = "ą"; // "a caudata"
  174. string arguments = string.Format("config --get {0}", controlStr);
  175. String s = new GitModule("").RunGitCmd(arguments, Encoding.UTF8);
  176. if (s != null && s.IndexOf(controlStr) != -1)
  177. _systemEncoding = new UTF8Encoding(false);
  178. else
  179. _systemEncoding = Encoding.Default;
  180. Debug.WriteLine("System encoding: " + _systemEncoding.EncodingName);
  181. }
  182. return _systemEncoding;
  183. }
  184. }
  185. //Encoding that let us read all bytes without replacing any char
  186. //It is using to read output of commands, which may consist of:
  187. //1) commit header (message, author, ...) encoded in CommitEncoding, recoded to LogOutputEncoding or not dependent of
  188. // pretty parameter (pretty=raw - recoded, pretty=format - not recoded)
  189. //2) file content encoded in its original encoding
  190. //3) file path (file name is encoded in system default encoding),
  191. // when core.quotepath is on, every non ASCII character is escaped
  192. // with \ followed by its code as a three digit octal number
  193. //4) branch, tag name, errors, warnings, hints encoded in system default encoding
  194. public static readonly Encoding LosslessEncoding = Encoding.GetEncoding("ISO-8859-1");//is any better?
  195. public Encoding FilesEncoding
  196. {
  197. get
  198. {
  199. Encoding result = EffectiveConfigFile.FilesEncoding;
  200. if (result == null)
  201. result = new UTF8Encoding(false);
  202. return result;
  203. }
  204. }
  205. public Encoding CommitEncoding
  206. {
  207. get
  208. {
  209. Encoding result = EffectiveConfigFile.CommitEncoding;
  210. if (result == null)
  211. result = new UTF8Encoding(false);
  212. return result;
  213. }
  214. }
  215. /// <summary>
  216. /// Encoding for commit header (message, notes, author, commiter, emails)
  217. /// </summary>
  218. public Encoding LogOutputEncoding
  219. {
  220. get
  221. {
  222. Encoding result = EffectiveConfigFile.LogOutputEncoding;
  223. if (result == null)
  224. result = CommitEncoding;
  225. return result;
  226. }
  227. }
  228. /// <summary>"(no branch)"</summary>
  229. public static readonly string DetachedBranch = "(no branch)";
  230. private static readonly string[] DetachedPrefixes = { "(no branch", "(detached from " };
  231. public AppSettings.PullAction LastPullAction
  232. {
  233. get { return AppSettings.GetEnum("LastPullAction_" + WorkingDir, AppSettings.PullAction.None); }
  234. set { AppSettings.SetEnum("LastPullAction_" + WorkingDir, value); }
  235. }
  236. public void LastPullActionToFormPullAction()
  237. {
  238. if (LastPullAction == AppSettings.PullAction.FetchAll)
  239. AppSettings.FormPullAction = AppSettings.PullAction.Fetch;
  240. else if (LastPullAction != AppSettings.PullAction.None)
  241. AppSettings.FormPullAction = LastPullAction;
  242. }
  243. /// <summary>Indicates whether the <see cref="WorkingDir"/> contains a git repository.</summary>
  244. public bool IsValidGitWorkingDir()
  245. {
  246. return IsValidGitWorkingDir(_workingDir);
  247. }
  248. /// <summary>Indicates whether the specified directory contains a git repository.</summary>
  249. public static bool IsValidGitWorkingDir(string dir)
  250. {
  251. if (string.IsNullOrEmpty(dir))
  252. return false;
  253. string dirPath = dir.EnsureTrailingPathSeparator();
  254. string path = dirPath + ".git";
  255. if (Directory.Exists(path) || File.Exists(path))
  256. return true;
  257. return Directory.Exists(dirPath + "info") &&
  258. Directory.Exists(dirPath + "objects") &&
  259. Directory.Exists(dirPath + "refs");
  260. }
  261. /// <summary>Gets the ".git" directory path.</summary>
  262. public string GetGitDirectory()
  263. {
  264. return GetGitDirectory(_workingDir);
  265. }
  266. public static string GetGitDirectory(string repositoryPath)
  267. {
  268. var gitpath = Path.Combine(repositoryPath, ".git");
  269. if (File.Exists(gitpath))
  270. {
  271. var lines = File.ReadLines(gitpath);
  272. foreach (string line in lines)
  273. {
  274. if (line.StartsWith("gitdir:"))
  275. {
  276. string path = line.Substring(7).Trim().Replace('/', '\\');
  277. if (Path.IsPathRooted(path))
  278. return path.EnsureTrailingPathSeparator();
  279. else
  280. return
  281. Path.GetFullPath(Path.Combine(repositoryPath,
  282. path.EnsureTrailingPathSeparator()));
  283. }
  284. }
  285. }
  286. gitpath = gitpath.EnsureTrailingPathSeparator();
  287. if (!Directory.Exists(gitpath))
  288. return repositoryPath;
  289. return gitpath;
  290. }
  291. public bool IsBareRepository()
  292. {
  293. return WorkingDir == GetGitDirectory();
  294. }
  295. public static bool IsBareRepository(string repositoryPath)
  296. {
  297. return repositoryPath == GetGitDirectory(repositoryPath);
  298. }
  299. public bool HasSubmodules()
  300. {
  301. return GetSubmodulesLocalPathes(recursive: false).Any();
  302. }
  303. /// <summary>
  304. /// This is a faster function to get the names of all submodules then the
  305. /// GetSubmodules() function. The command @git submodule is very slow.
  306. /// </summary>
  307. public IList<string> GetSubmodulesLocalPathes(bool recursive = true)
  308. {
  309. var configFile = GetSubmoduleConfigFile();
  310. var submodules = configFile.ConfigSections.Select(configSection => configSection.GetPathValue("path").Trim()).ToList();
  311. if (recursive)
  312. {
  313. for (int i = 0; i < submodules.Count; i++)
  314. {
  315. var submodule = GetSubmodule(submodules[i]);
  316. var submoduleConfigFile = submodule.GetSubmoduleConfigFile();
  317. var subsubmodules = submoduleConfigFile.ConfigSections.Select(configSection => configSection.GetPathValue("path").Trim()).ToList();
  318. for (int j = 0; j < subsubmodules.Count; j++)
  319. subsubmodules[j] = submodules[i] + '/' + subsubmodules[j];
  320. submodules.InsertRange(i + 1, subsubmodules);
  321. i += subsubmodules.Count;
  322. }
  323. }
  324. return submodules;
  325. }
  326. public static string FindGitWorkingDir(string startDir)
  327. {
  328. if (string.IsNullOrEmpty(startDir))
  329. return "";
  330. var dir = startDir.Trim();
  331. do
  332. {
  333. if (IsValidGitWorkingDir(dir))
  334. return dir.EnsureTrailingPathSeparator();
  335. dir = PathUtil.GetDirectoryName(dir);
  336. }
  337. while (!string.IsNullOrEmpty(dir));
  338. return startDir;
  339. }
  340. private static Process StartProccess(string fileName, string arguments, string workingDir, bool showConsole)
  341. {
  342. GitCommandHelpers.SetEnvironmentVariable();
  343. string quotedCmd = fileName;
  344. if (quotedCmd.IndexOf(' ') != -1)
  345. quotedCmd = quotedCmd.Quote();
  346. AppSettings.GitLog.Log(quotedCmd + " " + arguments);
  347. var startInfo = new ProcessStartInfo
  348. {
  349. FileName = fileName,
  350. Arguments = arguments,
  351. WorkingDirectory = workingDir
  352. };
  353. if (!showConsole)
  354. {
  355. startInfo.UseShellExecute = false;
  356. startInfo.CreateNoWindow = true;
  357. }
  358. return Process.Start(startInfo);
  359. }
  360. /// <summary>
  361. /// Run command, console window is visible
  362. /// </summary>
  363. public Process RunExternalCmdDetachedShowConsole(string cmd, string arguments)
  364. {
  365. try
  366. {
  367. return StartProccess(cmd, arguments, _workingDir, showConsole: true);
  368. }
  369. catch (Exception ex)
  370. {
  371. Trace.WriteLine(ex.Message);
  372. }
  373. return null;
  374. }
  375. /// <summary>
  376. /// Run command, console window is visible, wait for exit
  377. /// </summary>
  378. public void RunExternalCmdShowConsole(string cmd, string arguments)
  379. {
  380. try
  381. {
  382. using (var process = StartProccess(cmd, arguments, _workingDir, showConsole: true))
  383. process.WaitForExit();
  384. }
  385. catch (Exception ex)
  386. {
  387. Trace.WriteLine(ex.Message);
  388. }
  389. }
  390. /// <summary>
  391. /// Run command, console window is hidden
  392. /// </summary>
  393. public static Process RunExternalCmdDetached(string fileName, string arguments, string workingDir)
  394. {
  395. try
  396. {
  397. return StartProccess(fileName, arguments, workingDir, showConsole: false);
  398. }
  399. catch (Exception ex)
  400. {
  401. Trace.WriteLine(ex.Message);
  402. }
  403. return null;
  404. }
  405. /// <summary>
  406. /// Run command, console window is hidden
  407. /// </summary>
  408. public Process RunExternalCmdDetached(string cmd, string arguments)
  409. {
  410. return RunExternalCmdDetached(cmd, arguments, _workingDir);
  411. }
  412. /// <summary>
  413. /// Run git command, console window is hidden, redirect output
  414. /// </summary>
  415. public Process RunGitCmdDetached(string arguments, Encoding encoding = null)
  416. {
  417. if (encoding == null)
  418. encoding = SystemEncoding;
  419. return GitCommandHelpers.StartProcess(AppSettings.GitCommand, arguments, _workingDir, encoding);
  420. }
  421. /// <summary>
  422. /// Run command, cache results, console window is hidden, wait for exit, redirect output
  423. /// </summary>
  424. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  425. public string RunCacheableCmd(string cmd, string arguments = "", Encoding encoding = null)
  426. {
  427. if (encoding == null)
  428. encoding = SystemEncoding;
  429. byte[] cmdout, cmderr;
  430. if (GitCommandCache.TryGet(arguments, out cmdout, out cmderr))
  431. return EncodingHelper.DecodeString(cmdout, cmderr, ref encoding);
  432. GitCommandHelpers.RunCmdByte(cmd, arguments, _workingDir, null, out cmdout, out cmderr);
  433. GitCommandCache.Add(arguments, cmdout, cmderr);
  434. return EncodingHelper.DecodeString(cmdout, cmderr, ref encoding);
  435. }
  436. /// <summary>
  437. /// Run command, console window is hidden, wait for exit, redirect output
  438. /// </summary>
  439. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  440. public CmdResult RunCmdResult(string cmd, string arguments, Encoding encoding = null, byte[] stdInput = null)
  441. {
  442. byte[] output, error;
  443. int exitCode = GitCommandHelpers.RunCmdByte(cmd, arguments, _workingDir, stdInput, out output, out error);
  444. if (encoding == null)
  445. encoding = SystemEncoding;
  446. return new CmdResult
  447. {
  448. StdOutput = output == null ? string.Empty : encoding.GetString(output),
  449. StdError = error == null ? string.Empty : encoding.GetString(error),
  450. ExitCode = exitCode
  451. };
  452. }
  453. /// <summary>
  454. /// Run command, console window is hidden, wait for exit, redirect output
  455. /// </summary>
  456. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  457. public string RunCmd(string cmd, string arguments, Encoding encoding = null, byte[] stdInput = null)
  458. {
  459. return RunCmdResult(cmd, arguments, encoding, stdInput).GetString();
  460. }
  461. /// <summary>
  462. /// Run git command, console window is hidden, wait for exit, redirect output
  463. /// </summary>
  464. public string RunGitCmd(string arguments, Encoding encoding = null, byte[] stdInput = null)
  465. {
  466. return RunCmd(AppSettings.GitCommand, arguments, encoding, stdInput);
  467. }
  468. /// <summary>
  469. /// Run git command, console window is hidden, wait for exit, redirect output
  470. /// </summary>
  471. public CmdResult RunGitCmdResult(string arguments, Encoding encoding = null, byte[] stdInput = null)
  472. {
  473. return RunCmdResult(AppSettings.GitCommand, arguments, encoding, stdInput);
  474. }
  475. /// <summary>
  476. /// Run command, console window is hidden, wait for exit, redirect output
  477. /// </summary>
  478. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  479. private IEnumerable<string> ReadCmdOutputLines(string cmd, string arguments, string stdInput)
  480. {
  481. return GitCommandHelpers.ReadCmdOutputLines(cmd, arguments, _workingDir, stdInput);
  482. }
  483. /// <summary>
  484. /// Run git command, console window is hidden, wait for exit, redirect output
  485. /// </summary>
  486. public IEnumerable<string> ReadGitOutputLines(string arguments)
  487. {
  488. return ReadCmdOutputLines(AppSettings.GitCommand, arguments, null);
  489. }
  490. /// <summary>
  491. /// Run batch file, console window is hidden, wait for exit, redirect output
  492. /// </summary>
  493. public string RunBatchFile(string batchFile)
  494. {
  495. string tempFileName = Path.ChangeExtension(Path.GetTempFileName(), ".cmd");
  496. using (var writer = new StreamWriter(tempFileName))
  497. {
  498. writer.WriteLine("@prompt $G");
  499. writer.Write(batchFile);
  500. }
  501. string result = RunCmd("cmd.exe", "/C \"" + tempFileName + "\"");
  502. File.Delete(tempFileName);
  503. return result;
  504. }
  505. public void EditNotes(string revision)
  506. {
  507. string editor = GetEffectivePathSetting("core.editor").ToLower();
  508. if (editor.Contains("gitextensions") || editor.Contains("notepad") ||
  509. editor.Contains("notepad++"))
  510. {
  511. RunGitCmd("notes edit " + revision);
  512. }
  513. else
  514. {
  515. RunExternalCmdShowConsole(AppSettings.GitCommand, "notes edit " + revision);
  516. }
  517. }
  518. public bool InTheMiddleOfConflictedMerge()
  519. {
  520. return !string.IsNullOrEmpty(RunGitCmd("ls-files -z --unmerged"));
  521. }
  522. public IList<GitItem> GetConflictedFiles()
  523. {
  524. var unmergedFiles = new List<GitItem>();
  525. var fileName = "";
  526. foreach (var file in GetUnmergedFileListing())
  527. {
  528. if (file.IndexOf('\t') <= 0)
  529. continue;
  530. if (file.Substring(file.IndexOf('\t') + 1) == fileName)
  531. continue;
  532. fileName = file.Substring(file.IndexOf('\t') + 1);
  533. unmergedFiles.Add(new GitItem(this) { FileName = fileName });
  534. }
  535. return unmergedFiles;
  536. }
  537. private IEnumerable<string> GetUnmergedFileListing()
  538. {
  539. return RunGitCmd("ls-files -z --unmerged").Split(new[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  540. }
  541. public bool HandleConflictSelectSide(string fileName, string side)
  542. {
  543. Directory.SetCurrentDirectory(_workingDir);
  544. fileName = fileName.ToPosixPath();
  545. side = GetSide(side);
  546. string result = RunGitCmd(String.Format("checkout-index -f --stage={0} -- \"{1}\"", side, fileName));
  547. if (!result.IsNullOrEmpty())
  548. {
  549. return false;
  550. }
  551. result = RunGitCmd(String.Format("add -- \"{0}\"", fileName));
  552. return result.IsNullOrEmpty();
  553. }
  554. public bool HandleConflictsSaveSide(string fileName, string saveAsFileName, string side)
  555. {
  556. Directory.SetCurrentDirectory(_workingDir);
  557. fileName = fileName.ToPosixPath();
  558. side = GetSide(side);
  559. var result = RunGitCmd(String.Format("checkout-index --stage={0} --temp -- \"{1}\"", side, fileName));
  560. if (result.IsNullOrEmpty())
  561. {
  562. return false;
  563. }
  564. if (!result.StartsWith(".merge_file_"))
  565. {
  566. return false;
  567. }
  568. // Parse temporary file name from command line result
  569. var splitResult = result.Split(new[] { "\t", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
  570. if (splitResult.Length != 2)
  571. {
  572. return false;
  573. }
  574. var temporaryFileName = splitResult[0].Trim();
  575. if (!File.Exists(temporaryFileName))
  576. {
  577. return false;
  578. }
  579. var retValue = false;
  580. try
  581. {
  582. if (File.Exists(saveAsFileName))
  583. {
  584. File.Delete(saveAsFileName);
  585. }
  586. File.Move(temporaryFileName, saveAsFileName);
  587. retValue = true;
  588. }
  589. catch
  590. {
  591. }
  592. finally
  593. {
  594. if (File.Exists(temporaryFileName))
  595. {
  596. File.Delete(temporaryFileName);
  597. }
  598. }
  599. return retValue;
  600. }
  601. public void SaveBlobAs(string saveAs, string blob)
  602. {
  603. using (var ms = (MemoryStream)GetFileStream(blob)) //Ugly, has implementation info.
  604. {
  605. byte[] buf = ms.ToArray();
  606. if (EffectiveConfigFile.core.autocrlf.Value == AutoCRLFType.True)
  607. {
  608. if (!FileHelper.IsBinaryFile(this, saveAs) && !FileHelper.IsBinaryFileAccordingToContent(buf))
  609. {
  610. buf = GitConvert.ConvertCrLfToWorktree(buf);
  611. }
  612. }
  613. using (FileStream fileOut = File.Create(saveAs))
  614. {
  615. fileOut.Write(buf, 0, buf.Length);
  616. }
  617. }
  618. }
  619. private static string GetSide(string side)
  620. {
  621. if (side.Equals("REMOTE", StringComparison.CurrentCultureIgnoreCase))
  622. side = "3";
  623. if (side.Equals("LOCAL", StringComparison.CurrentCultureIgnoreCase))
  624. side = "2";
  625. if (side.Equals("BASE", StringComparison.CurrentCultureIgnoreCase))
  626. side = "1";
  627. return side;
  628. }
  629. public string[] GetConflictedFiles(string filename)
  630. {
  631. Directory.SetCurrentDirectory(_workingDir);
  632. filename = filename.ToPosixPath();
  633. string[] fileNames =
  634. {
  635. filename + ".BASE",
  636. filename + ".LOCAL",
  637. filename + ".REMOTE"
  638. };
  639. var unmerged = RunGitCmd("ls-files -z --unmerged \"" + filename + "\"").Split(new char[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  640. foreach (var file in unmerged)
  641. {
  642. string fileStage = null;
  643. int findSecondWhitespace = file.IndexOfAny(new[] { ' ', '\t' });
  644. if (findSecondWhitespace >= 0) fileStage = file.Substring(findSecondWhitespace).Trim();
  645. findSecondWhitespace = fileStage.IndexOfAny(new[] { ' ', '\t' });
  646. if (findSecondWhitespace >= 0) fileStage = fileStage.Substring(findSecondWhitespace).Trim();
  647. if (string.IsNullOrEmpty(fileStage))
  648. continue;
  649. int stage;
  650. if (!Int32.TryParse(fileStage.Trim()[0].ToString(), out stage))
  651. continue;
  652. var tempFile = RunGitCmd("checkout-index --temp --stage=" + stage + " -- " + "\"" + filename + "\"");
  653. tempFile = tempFile.Split('\t')[0];
  654. tempFile = Path.Combine(_workingDir, tempFile);
  655. var newFileName = Path.Combine(_workingDir, fileNames[stage - 1]);
  656. try
  657. {
  658. fileNames[stage - 1] = newFileName;
  659. var index = 1;
  660. while (File.Exists(fileNames[stage - 1]) && index < 50)
  661. {
  662. fileNames[stage - 1] = newFileName + index;
  663. index++;
  664. }
  665. File.Move(tempFile, fileNames[stage - 1]);
  666. }
  667. catch (Exception ex)
  668. {
  669. Trace.WriteLine(ex);
  670. }
  671. }
  672. if (!File.Exists(fileNames[0])) fileNames[0] = null;
  673. if (!File.Exists(fileNames[1])) fileNames[1] = null;
  674. if (!File.Exists(fileNames[2])) fileNames[2] = null;
  675. return fileNames;
  676. }
  677. public string[] GetConflictedFileNames(string filename)
  678. {
  679. filename = filename.ToPosixPath();
  680. var fileNames = new string[3];
  681. var unmerged = RunGitCmd("ls-files -z --unmerged \"" + filename + "\"").Split(new[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  682. foreach (var line in unmerged)
  683. {
  684. int findSecondWhitespace = line.IndexOfAny(new[] { ' ', '\t' });
  685. string fileStage = findSecondWhitespace >= 0 ? line.Substring(findSecondWhitespace).Trim() : "";
  686. findSecondWhitespace = fileStage.IndexOfAny(new[] { ' ', '\t' });
  687. fileStage = findSecondWhitespace >= 0 ? fileStage.Substring(findSecondWhitespace).Trim() : "";
  688. int stage;
  689. if (fileStage.Length > 2 && Int32.TryParse(fileStage[0].ToString(), out stage) && stage >= 1 && stage <= 3)
  690. {
  691. fileNames[stage - 1] = fileStage.Substring(2);
  692. }
  693. }
  694. return fileNames;
  695. }
  696. public string[] GetConflictedSubmoduleHashes(string filename)
  697. {
  698. filename = filename.ToPosixPath();
  699. var hashes = new string[3];
  700. var unmerged = RunGitCmd("ls-files -z --unmerged \"" + filename + "\"").Split(new[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  701. foreach (var line in unmerged)
  702. {
  703. int findSecondWhitespace = line.IndexOfAny(new[] { ' ', '\t' });
  704. string fileStage = findSecondWhitespace >= 0 ? line.Substring(findSecondWhitespace).Trim() : "";
  705. findSecondWhitespace = fileStage.IndexOfAny(new[] { ' ', '\t' });
  706. string hash = findSecondWhitespace >= 0 ? fileStage.Substring(0, findSecondWhitespace).Trim() : "";
  707. fileStage = findSecondWhitespace >= 0 ? fileStage.Substring(findSecondWhitespace).Trim() : "";
  708. int stage;
  709. if (fileStage.Length > 2 && Int32.TryParse(fileStage[0].ToString(), out stage) && stage >= 1 && stage <= 3)
  710. {
  711. hashes[stage - 1] = hash;
  712. }
  713. }
  714. return hashes;
  715. }
  716. public Dictionary<GitRef, GitItem> GetSubmoduleItemsForEachRef(string filename, Func<GitRef, bool> showRemoteRef)
  717. {
  718. string command = GetShowRefCommand();
  719. if (command == null)
  720. return new Dictionary<GitRef, GitItem>();
  721. filename = filename.ToPosixPath();
  722. var tree = RunGitCmd(command, SystemEncoding);
  723. var refs = GetTreeRefs(tree);
  724. return refs.Where(showRemoteRef).ToDictionary(r => r, r => GetSubmoduleGuid(filename, r.Name));
  725. }
  726. private string GetShowRefCommand()
  727. {
  728. if (AppSettings.ShowSuperprojectRemoteBranches)
  729. return "show-ref --dereference";
  730. if (AppSettings.ShowSuperprojectBranches || AppSettings.ShowSuperprojectTags)
  731. return "show-ref --dereference"
  732. + (AppSettings.ShowSuperprojectBranches ? " --heads" : null)
  733. + (AppSettings.ShowSuperprojectTags ? " --tags" : null);
  734. return null;
  735. }
  736. private GitItem GetSubmoduleGuid(string filename, string refName)
  737. {
  738. string str = RunGitCmd("ls-tree " + refName + " \"" + filename + "\"");
  739. return GitItem.CreateGitItemFromString(this, str);
  740. }
  741. public int? GetCommitCount(string parentHash, string childHash)
  742. {
  743. string result = RunGitCmd("rev-list " + parentHash + " ^" + childHash + " --count");
  744. int commitCount;
  745. if (int.TryParse(result, out commitCount))
  746. return commitCount;
  747. return null;
  748. }
  749. public string GetCommitCountString(string from, string to)
  750. {
  751. int? removed = GetCommitCount(from, to);
  752. int? added = GetCommitCount(to, from);
  753. if (removed == null || added == null)
  754. return "";
  755. if (removed == 0 && added == 0)
  756. return "=";
  757. return
  758. (removed > 0 ? ("-" + removed) : "") +
  759. (added > 0 ? ("+" + added) : "");
  760. }
  761. public string GetMergeMessage()
  762. {
  763. var file = GetGitDirectory() + "MERGE_MSG";
  764. return
  765. File.Exists(file)
  766. ? File.ReadAllText(file)
  767. : "";
  768. }
  769. public void RunGitK()
  770. {
  771. if (EnvUtils.RunningOnUnix())
  772. {
  773. RunExternalCmdDetachedShowConsole("gitk", "");
  774. }
  775. else
  776. {
  777. RunExternalCmdDetached("cmd.exe", "/c \"\"" + AppSettings.GitCommand.Replace("git.cmd", "gitk.cmd")
  778. .Replace("bin\\git.exe", "cmd\\gitk.cmd")
  779. .Replace("bin/git.exe", "cmd/gitk.cmd") + "\" --branches --tags --remotes\"");
  780. }
  781. }
  782. public void RunGui()
  783. {
  784. if (EnvUtils.RunningOnUnix())
  785. {
  786. RunExternalCmdDetachedShowConsole(AppSettings.GitCommand, "gui");
  787. }
  788. else
  789. {
  790. RunExternalCmdDetached("cmd.exe", "/c \"\"" + AppSettings.GitCommand + "\" gui\"");
  791. }
  792. }
  793. /// <summary>Runs a bash or shell command.</summary>
  794. public Process RunBash(string bashCommand = null)
  795. {
  796. if (EnvUtils.RunningOnUnix())
  797. {
  798. string[] termEmuCmds =
  799. {
  800. "gnome-terminal",
  801. "konsole",
  802. "Terminal",
  803. "xterm"
  804. };
  805. string args = "";
  806. string cmd = termEmuCmds.FirstOrDefault(termEmuCmd => !string.IsNullOrEmpty(RunCmd("which", termEmuCmd)));
  807. if (string.IsNullOrEmpty(cmd))
  808. {
  809. cmd = "bash";
  810. args = "--login -i";
  811. }
  812. return RunExternalCmdDetachedShowConsole(cmd, args);
  813. }
  814. else
  815. {
  816. string args;
  817. if (string.IsNullOrWhiteSpace(bashCommand))
  818. {
  819. args = "--login -i\"";
  820. }
  821. else
  822. {
  823. args = "--login -i -c \"" + bashCommand.Replace("\"", "\\\"") + "\"";
  824. }
  825. string termCmd = File.Exists(AppSettings.GitBinDir + "bash.exe") ? "bash" : "sh";
  826. return RunExternalCmdDetachedShowConsole("cmd.exe",
  827. string.Format("/c \"\"{0}{1}\" {2}", AppSettings.GitBinDir, termCmd, args));
  828. }
  829. }
  830. public string Init(bool bare, bool shared)
  831. {
  832. return RunGitCmd(Smart.Format("init{0: --bare|}{1: --shared=all|}", bare, shared));
  833. }
  834. public bool IsMerge(string commit)
  835. {
  836. string[] parents = GetParents(commit);
  837. return parents.Length > 1;
  838. }
  839. private static string ProccessDiffNotes(int startIndex, string[] lines)
  840. {
  841. int endIndex = lines.Length - 1;
  842. if (lines[endIndex] == "Notes:")
  843. endIndex--;
  844. var message = new StringBuilder();
  845. bool bNotesStart = false;
  846. for (int i = startIndex; i <= endIndex; i++)
  847. {
  848. string line = lines[i];
  849. if (bNotesStart)
  850. line = " " + line;
  851. message.AppendLine(line);
  852. if (lines[i] == "Notes:")
  853. bNotesStart = true;
  854. }
  855. return message.ToString();
  856. }
  857. public GitRevision GetRevision(string commit, bool shortFormat = false)
  858. {
  859. const string formatString =
  860. /* Hash */ "%H%n" +
  861. /* Tree */ "%T%n" +
  862. /* Parents */ "%P%n" +
  863. /* Author Name */ "%aN%n" +
  864. /* Author EMail */ "%aE%n" +
  865. /* Author Date */ "%at%n" +
  866. /* Committer Name */ "%cN%n" +
  867. /* Committer EMail*/ "%cE%n" +
  868. /* Committer Date */ "%ct%n";
  869. const string messageFormat = "%e%n%B%nNotes:%n%-N";
  870. string cmd = "log -n1 --format=format:" + formatString + (shortFormat ? "%e%n%s" : messageFormat) + " " + commit;
  871. var revInfo = RunCacheableCmd(AppSettings.GitCommand, cmd, LosslessEncoding);
  872. string[] lines = revInfo.Split('\n');
  873. var revision = new GitRevision(this, lines[0])
  874. {
  875. TreeGuid = lines[1],
  876. ParentGuids = lines[2].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries),
  877. Author = ReEncodeStringFromLossless(lines[3]),
  878. AuthorEmail = ReEncodeStringFromLossless(lines[4]),
  879. Committer = ReEncodeStringFromLossless(lines[6]),
  880. CommitterEmail = ReEncodeStringFromLossless(lines[7])
  881. };
  882. revision.AuthorDate = DateTimeUtils.ParseUnixTime(lines[5]);
  883. revision.CommitDate = DateTimeUtils.ParseUnixTime(lines[8]);
  884. revision.MessageEncoding = lines[9];
  885. if (shortFormat)
  886. {
  887. revision.Message = ReEncodeCommitMessage(lines[10], revision.MessageEncoding);
  888. }
  889. else
  890. {
  891. string message = ProccessDiffNotes(10, lines);
  892. //commit message is not reencoded by git when format is given
  893. revision.Body = ReEncodeCommitMessage(message, revision.MessageEncoding);
  894. revision.Message = revision.Body.Substring(0, revision.Body.IndexOfAny(new[] { '\r', '\n' }));
  895. }
  896. return revision;
  897. }
  898. public string[] GetParents(string commit)
  899. {
  900. string output = RunGitCmd("log -n 1 --format=format:%P \"" + commit + "\"");
  901. return output.Split(' ');
  902. }
  903. public GitRevision[] GetParentsRevisions(string commit)
  904. {
  905. string[] parents = GetParents(commit);
  906. var parentsRevisions = new GitRevision[parents.Length];
  907. for (int i = 0; i < parents.Length; i++)
  908. parentsRevisions[i] = GetRevision(parents[i], true);
  909. return parentsRevisions;
  910. }
  911. public string ShowSha1(string sha1)
  912. {
  913. return ReEncodeShowString(RunCacheableCmd(AppSettings.GitCommand, "show " + sha1, LosslessEncoding));
  914. }
  915. public string DeleteTag(string tagName)
  916. {
  917. return RunGitCmd(GitCommandHelpers.DeleteTagCmd(tagName));
  918. }
  919. public string GetCurrentCheckout()
  920. {
  921. return RunGitCmd("rev-parse HEAD").TrimEnd();
  922. }
  923. public KeyValuePair<char, string> GetSuperprojectCurrentCheckout()
  924. {
  925. if (SuperprojectModule == null)
  926. return new KeyValuePair<char, string>(' ', "");
  927. var lines = SuperprojectModule.RunGitCmd("submodule status --cached " + _submodulePath).Split('\n');
  928. if (lines.Length == 0)
  929. return new KeyValuePair<char, string>(' ', "");
  930. string submodule = lines[0];
  931. if (submodule.Length < 43)
  932. return new KeyValuePair<char, string>(' ', "");
  933. var currentCommitGuid = submodule.Substring(1, 40).Trim();
  934. return new KeyValuePair<char, string>(submodule[0], currentCommitGuid);
  935. }
  936. public bool ExistsMergeCommit(string startRev, string endRev)
  937. {
  938. if (startRev.IsNullOrEmpty() || endRev.IsNullOrEmpty())
  939. return false;
  940. string revisions = RunGitCmd("rev-list --parents --no-walk " + startRev + ".." + endRev);
  941. string[] revisionsTab = revisions.Split('\n');
  942. Func<string, bool> ex = (string parents) =>
  943. {
  944. string[] tab = parents.Split(' ');
  945. return tab.Length > 2 && tab.All(parent => GitRevision.Sha1HashRegex.IsMatch(parent));
  946. };
  947. return revisionsTab.Any(ex);
  948. }
  949. public ConfigFile GetSubmoduleConfigFile()
  950. {
  951. return new ConfigFile(_workingDir + ".gitmodules", true);
  952. }
  953. public string GetCurrentSubmoduleLocalPath()
  954. {
  955. if (SuperprojectModule == null)
  956. return null;
  957. string submodulePath = WorkingDir.Substring(SuperprojectModule.WorkingDir.Length);
  958. submodulePath = PathUtil.GetDirectoryName(submodulePath.ToPosixPath());
  959. return submodulePath;
  960. }
  961. public string GetSubmoduleNameByPath(string localPath)
  962. {
  963. var configFile = GetSubmoduleConfigFile();
  964. var submodule = configFile.ConfigSections.FirstOrDefault(configSection => configSection.GetPathValue("path").Trim() == localPath);
  965. if (submodule != null)
  966. return submodule.SubSection.Trim();
  967. return null;
  968. }
  969. public string GetSubmoduleRemotePath(string name)
  970. {
  971. var configFile = GetSubmoduleConfigFile();
  972. return configFile.GetPathValue(string.Format("submodule.{0}.url", name)).Trim();
  973. }
  974. public string GetSubmoduleFullPath(string localPath)
  975. {
  976. string dir = Path.Combine(_workingDir, localPath.EnsureTrailingPathSeparator());
  977. return Path.GetFullPath(dir); // fix slashes
  978. }
  979. public GitModule GetSubmodule(string localPath)
  980. {
  981. return new GitModule(GetSubmoduleFullPath(localPath));
  982. }
  983. IGitModule IGitModule.GetSubmodule(string submoduleName)
  984. {
  985. return GetSubmodule(submoduleName);
  986. }
  987. private GitSubmoduleInfo GetSubmoduleInfo(string submodule)
  988. {
  989. var gitSubmodule =
  990. new GitSubmoduleInfo(this)
  991. {
  992. Initialized = submodule[0] != '-',
  993. UpToDate = submodule[0] != '+',
  994. CurrentCommitGuid = submodule.Substring(1, 40).Trim()
  995. };
  996. var localPath = submodule.Substring(42).Trim();
  997. if (localPath.Contains("("))
  998. {
  999. gitSubmodule.LocalPath = localPath.Substring(0, localPath.IndexOf("(")).TrimEnd();
  1000. gitSubmodule.Branch = localPath.Substring(localPath.IndexOf("(")).Trim(new[] { '(', ')', ' ' });
  1001. }
  1002. else
  1003. gitSubmodule.LocalPath = localPath;
  1004. return gitSubmodule;
  1005. }
  1006. public IEnumerable<IGitSubmoduleInfo> GetSubmodulesInfo()
  1007. {
  1008. var submodules = ReadGitOutputLines("submodule status");
  1009. string lastLine = null;
  1010. foreach (var submodule in submodules)
  1011. {
  1012. if (submodule.Length < 43)
  1013. continue;
  1014. if (submodule.Equals(lastLine))
  1015. continue;
  1016. lastLine = submodule;
  1017. yield return GetSubmoduleInfo(submodule);
  1018. }
  1019. }
  1020. public string FindGitSuperprojectPath(out string submoduleName, out string submodulePath)
  1021. {
  1022. submoduleName = null;
  1023. submodulePath = null;
  1024. if (!IsValidGitWorkingDir())
  1025. return null;
  1026. string superprojectPath = null;
  1027. string currentPath = Path.GetDirectoryName(_workingDir); // remove last slash
  1028. if (!string.IsNullOrEmpty(currentPath))
  1029. {
  1030. string path = Path.GetDirectoryName(currentPath);
  1031. for (int i = 0; i < 5; i++)
  1032. {
  1033. if (string.IsNullOrEmpty(path))
  1034. break;
  1035. if (File.Exists(Path.Combine(path, ".gitmodules")) &&
  1036. IsValidGitWorkingDir(path))
  1037. {
  1038. superprojectPath = path.EnsureTrailingPathSeparator();
  1039. break;
  1040. }
  1041. // Check upper directory
  1042. path = Path.GetDirectoryName(path);
  1043. }
  1044. }
  1045. if (File.Exists(_workingDir + ".git") &&
  1046. superprojectPath == null)
  1047. {
  1048. var lines = File.ReadLines(_workingDir + ".git");
  1049. foreach (string line in lines)
  1050. {
  1051. if (line.StartsWith("gitdir:"))
  1052. {
  1053. string gitpath = line.Substring(7).Trim();
  1054. int pos = gitpath.IndexOf("/.git/");
  1055. if (pos != -1)
  1056. {
  1057. gitpath = gitpath.Substring(0, pos + 1).Replace('/', '\\');
  1058. gitpath = Path.GetFullPath(Path.Combine(_workingDir, gitpath));
  1059. if (File.Exists(gitpath + ".gitmodules") && IsValidGitWorkingDir(gitpath))
  1060. superprojectPath = gitpath;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. if (!string.IsNullOrEmpty(superprojectPath))
  1066. {
  1067. submodulePath = currentPath.Substring(superprojectPath.Length).ToPosixPath();
  1068. var configFile = new ConfigFile(superprojectPath + ".gitmodules", true);
  1069. foreach (ConfigSection configSection in configFile.ConfigSections)
  1070. {
  1071. if (configSection.GetPathValue("path") == submodulePath.ToPosixPath())
  1072. {
  1073. submoduleName = configSection.SubSection;
  1074. return superprojectPath;
  1075. }
  1076. }
  1077. }
  1078. return null;
  1079. }
  1080. public string GetSubmoduleSummary(string submodule)
  1081. {
  1082. var arguments = string.Format("submodule summary {0}", submodule);
  1083. return RunGitCmd(arguments);
  1084. }
  1085. public string ResetSoft(string commit)
  1086. {
  1087. return ResetSoft(commit, "");
  1088. }
  1089. public string ResetMixed(string commit)
  1090. {
  1091. return ResetMixed(commit, "");
  1092. }
  1093. public string ResetHard(string commit)
  1094. {
  1095. return ResetHard(commit, "");
  1096. }
  1097. public string ResetSoft(string commit, string file)
  1098. {
  1099. var args = "reset --soft";
  1100. if (!string.IsNullOrEmpty(commit))
  1101. args += " \"" + commit + "\"";
  1102. if (!string.IsNullOrEmpty(file))
  1103. args += " -- \"" + file + "\"";
  1104. return RunGitCmd(args);
  1105. }
  1106. public string ResetMixed(string commit, string file)
  1107. {
  1108. var args = "reset --mixed";
  1109. if (!string.IsNullOrEmpty(commit))
  1110. args += " \"" + commit + "\"";
  1111. if (!string.IsNullOrEmpty(file))
  1112. args += " -- \"" + file + "\"";
  1113. return RunGitCmd(args);
  1114. }
  1115. public string ResetHard(string commit, string file)
  1116. {
  1117. var args = "reset --hard";
  1118. if (!string.IsNullOrEmpty(commit))
  1119. args += " \"" + commit + "\"";
  1120. if (!string.IsNullOrEmpty(file))
  1121. args += " -- \"" + file + "\"";
  1122. return RunGitCmd(args);
  1123. }
  1124. public string ResetFile(string file)
  1125. {
  1126. file = file.ToPosixPath();
  1127. return RunGitCmd("checkout-index --index --force -- \"" + file + "\"");
  1128. }
  1129. public string FormatPatch(string from, string to, string output, int start)
  1130. {
  1131. output = output.ToPosixPath();
  1132. var result = RunGitCmd("format-patch -M -C -B --start-number " + start + " \"" + from + "\"..\"" + to +
  1133. "\" -o \"" + output + "\"");
  1134. return result;
  1135. }
  1136. public string FormatPatch(string from, string to, string output)
  1137. {
  1138. output = output.ToPosixPath();
  1139. var result = RunGitCmd("format-patch -M -C -B \"" + from + "\"..\"" + to + "\" -o \"" + output + "\"");
  1140. return result;
  1141. }
  1142. public string Tag(string tagName, string revision, bool annotation, bool force)
  1143. {
  1144. if (annotation)
  1145. return RunGitCmd(string.Format("tag \"{0}\" -a {1} -F \"{2}\\TAGMESSAGE\" -- \"{3}\"", tagName.Trim(), (force ? "-f" : ""), GetGitDirectory(), revision));
  1146. return RunGitCmd(string.Format("tag {0} \"{1}\" \"{2}\"", (force ? "-f" : ""), tagName.Trim(), revision));
  1147. }
  1148. public string CheckoutFiles(IEnumerable<string> fileList, string revision, bool force)
  1149. {
  1150. string files = fileList.Select(s => s.Quote()).Join(" ");
  1151. return RunGitCmd("checkout " + force.AsForce() + revision.Quote() + " -- " + files);
  1152. }
  1153. /// <summary>Tries to start Pageant for the specified remote repo (using the remote's PuTTY key file).</summary>
  1154. /// <returns>true if the remote has a PuTTY key file; otherwise, false.</returns>
  1155. public bool StartPageantForRemote(string remote)
  1156. {
  1157. var sshKeyFile = GetPuttyKeyFileForRemote(remote);
  1158. if (string.IsNullOrEmpty(sshKeyFile) || !File.Exists(sshKeyFile))
  1159. return false;
  1160. StartPageantWithKey(sshKeyFile);
  1161. return true;
  1162. }
  1163. public static void StartPageantWithKey(string sshKeyFile)
  1164. {
  1165. RunExternalCmdDetached(AppSettings.Pageant, "\"" + sshKeyFile + "\"", "");
  1166. }
  1167. public string GetPuttyKeyFileForRemote(string remote)
  1168. {
  1169. if (string.IsNullOrEmpty(remote) ||
  1170. string.IsNullOrEmpty(AppSettings.Pageant) ||
  1171. !AppSettings.AutoStartPageant ||
  1172. !GitCommandHelpers.Plink())
  1173. return "";
  1174. return GetPathSetting(string.Format("remote.{0}.puttykeyfile", remote));
  1175. }
  1176. public static bool PathIsUrl(string path)
  1177. {
  1178. return path.Contains(Path.DirectorySeparatorChar) || path.Contains(AppSettings.PosixPathSeparator.ToString());
  1179. }
  1180. public string FetchCmd(string remote, string remoteBranch, string localBranch, bool? fetchTags = false)
  1181. {
  1182. var progressOption = "";
  1183. if (GitCommandHelpers.VersionInUse.FetchCanAskForProgress)
  1184. progressOption = "--progress ";
  1185. if (string.IsNullOrEmpty(remote) && string.IsNullOrEmpty(remoteBranch) && string.IsNullOrEmpty(localBranch))
  1186. return "fetch " + progressOption;
  1187. return "fetch " + progressOption + GetFetchArgs(remote, remoteBranch, localBranch, fetchTags);
  1188. }
  1189. public string PullCmd(string remote, string remoteBranch, string localBranch, bool rebase, bool? fetchTags = false)
  1190. {
  1191. var pullArgs = "";
  1192. if (GitCommandHelpers.VersionInUse.FetchCanAskForProgress)
  1193. pullArgs = "--progress ";
  1194. if (rebase)
  1195. pullArgs = "--rebase".Combine(" ", pullArgs);
  1196. return "pull " + pullArgs + GetFetchArgs(remote, remoteBranch, localBranch, fetchTags);
  1197. }
  1198. private string GetFetchArgs(string remote, string remoteBranch, string localBranch, bool? fetchTags)
  1199. {
  1200. remote = remote.ToPosixPath();
  1201. //Remove spaces...
  1202. if (remoteBranch != null)
  1203. remoteBranch = remoteBranch.Replace(" ", "");
  1204. if (localBranch != null)
  1205. localBranch = localBranch.Replace(" ", "");
  1206. string remoteBranchArguments;
  1207. if (string.IsNullOrEmpty(remoteBranch))
  1208. remoteBranchArguments = "";
  1209. else
  1210. {
  1211. if (remoteBranch.StartsWith("+"))
  1212. remoteBranch = remoteBranch.Remove(0, 1);
  1213. remoteBranchArguments = "+" + GitCommandHelpers.GetFullBranchName(remoteBranch);
  1214. }
  1215. string localBranchArguments;
  1216. var remoteUrl = GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote));
  1217. if (PathIsUrl(remote) && !string.IsNullOrEmpty(localBranch) && string.IsNullOrEmpty(remoteUrl))
  1218. localBranchArguments = ":" + GitCommandHelpers.GetFullBranchName(localBranch);
  1219. else if (string.IsNullOrEmpty(localBranch) || PathIsUrl(remote) || string.IsNullOrEmpty(remoteUrl))
  1220. localBranchArguments = "";
  1221. else
  1222. localBranchArguments = ":" + "refs/remotes/" + remote.Trim() + "/" + localBranch + "";
  1223. string arguments = fetchTags == true ? " --tags" : fetchTags == false ? " --no-tags" : "";
  1224. return "\"" + remote.Trim() + "\" " + remoteBranchArguments + localBranchArguments + arguments;
  1225. }
  1226. public string GetRebaseDir()
  1227. {
  1228. string gitDirectory = GetGitDirectory();
  1229. if (Directory.Exists(gitDirectory + "rebase-merge" + Path.DirectorySeparatorChar))
  1230. return gitDirectory + "rebase-merge" + Path.DirectorySeparatorChar;
  1231. if (Directory.Exists(gitDirectory + "rebase-apply" + Path.DirectorySeparatorChar))
  1232. return gitDirectory + "rebase-apply" + Path.DirectorySeparatorChar;
  1233. if (Directory.Exists(gitDirectory + "rebase" + Path.DirectorySeparatorChar))
  1234. return gitDirectory + "rebase" + Path.DirectorySeparatorChar;
  1235. return "";
  1236. }
  1237. private ProcessStartInfo CreateGitStartInfo(string arguments)
  1238. {
  1239. return GitCommandHelpers.CreateProcessStartInfo(AppSettings.GitCommand, arguments, _workingDir, SystemEncoding);
  1240. }
  1241. public string ApplyPatch(string dir, string amCommand)
  1242. {
  1243. var startInfo = CreateGitStartInfo(amCommand);
  1244. using (var process = Process.Start(startInfo))
  1245. {
  1246. var files = Directory.GetFiles(dir);
  1247. if (files.Length == 0)
  1248. return "";
  1249. foreach (var file in files)
  1250. {
  1251. using (var fs = new FileStream(file, FileMode.Open))
  1252. {
  1253. fs.CopyTo(process.StandardInput.BaseStream);
  1254. }
  1255. }
  1256. process.StandardInput.Close();
  1257. process.WaitForExit();
  1258. return process.StandardOutput.ReadToEnd().Trim();
  1259. }
  1260. }
  1261. public string StageFiles(IList<GitItemStatus> files, out bool wereErrors)
  1262. {
  1263. var output = "";
  1264. wereErrors = false;
  1265. var startInfo = CreateGitStartInfo("update-index --add --stdin");
  1266. var process = new Lazy<Process>(() => Process.Start(startInfo));
  1267. foreach (var file in files.Where(file => !file.IsDeleted))
  1268. {
  1269. UpdateIndex(process, file.Name);
  1270. }
  1271. if (process.IsValueCreated)
  1272. {
  1273. process.Value.StandardInput.Close();
  1274. process.Value.WaitForExit();
  1275. wereErrors = process.Value.ExitCode != 0;
  1276. output = process.Value.StandardOutput.ReadToEnd().Trim();
  1277. }
  1278. startInfo.Arguments = "update-index --remove --stdin";
  1279. process = new Lazy<Process>(() => Process.Start(startInfo));
  1280. foreach (var file in files.Where(file => file.IsDeleted))
  1281. {
  1282. UpdateIndex(process, file.Name);
  1283. }
  1284. if (process.IsValueCreated)
  1285. {
  1286. process.Value.StandardInput.Close();
  1287. process.Value.WaitForExit();
  1288. wereErrors = wereErrors || process.Value.ExitCode != 0;
  1289. if (!string.IsNullOrEmpty(output))
  1290. output += Environment.NewLine;
  1291. output += process.Value.StandardOutput.ReadToEnd().Trim();
  1292. }
  1293. return output;
  1294. }
  1295. public string UnstageFiles(IList<GitItemStatus> files)
  1296. {
  1297. var output = "";
  1298. var startInfo = CreateGitStartInfo("update-index --info-only --index-info");
  1299. var process = new Lazy<Process>(() => Process.Start(startInfo));
  1300. foreach (var file in files.Where(file => !file.IsNew))
  1301. {
  1302. process.Value.StandardInput.WriteLine("0 0000000000000000000000000000000000000000\t\"" + file.Name.ToPosixPath() + "\"");
  1303. }
  1304. if (process.IsValueCreated)
  1305. {
  1306. process.Value.StandardInput.Close();
  1307. process.Value.WaitForExit();
  1308. output = process.Value.StandardOutput.ReadToEnd().Trim();
  1309. }
  1310. startInfo.Arguments = "update-index --force-remove --stdin";
  1311. process = new Lazy<Process>(() => Process.Start(startInfo));
  1312. foreach (var file in files.Where(file => file.IsNew))
  1313. {
  1314. UpdateIndex(process, file.Name);
  1315. }
  1316. if (process.IsValueCreated)
  1317. {
  1318. process.Value.StandardInput.Close();
  1319. process.Value.WaitForExit();
  1320. if (!string.IsNullOrEmpty(output))
  1321. output += Environment.NewLine;
  1322. output += process.Value.StandardOutput.ReadToEnd().Trim();
  1323. }
  1324. return output;
  1325. }
  1326. private static void UpdateIndex(Lazy<Process> process, string filename)
  1327. {
  1328. //process.StandardInput.WriteLine("\"" + ToPosixPath(file.Name) + "\"");
  1329. byte[] bytearr = EncodingHelper.ConvertTo(SystemEncoding,
  1330. "\"" + filename.ToPosixPath() + "\"" + process.Value.StandardInput.NewLine);
  1331. process.Value.StandardInput.BaseStream.Write(bytearr, 0, bytearr.Length);
  1332. }
  1333. public bool InTheMiddleOfBisect()
  1334. {
  1335. return File.Exists(Path.Combine(GetGitDirectory(), "BISECT_START"));
  1336. }
  1337. public bool InTheMiddleOfRebase()
  1338. {
  1339. return !File.Exists(GetRebaseDir() + "applying") &&
  1340. Directory.Exists(GetRebaseDir());
  1341. }
  1342. public bool InTheMiddleOfPatch()
  1343. {
  1344. return !File.Exists(GetRebaseDir() + "rebasing") &&
  1345. Directory.Exists(GetRebaseDir());
  1346. }
  1347. public bool InTheMiddleOfAction()
  1348. {
  1349. return InTheMiddleOfConflictedMerge() || InTheMiddleOfRebase();
  1350. }
  1351. public string GetNextRebasePatch()
  1352. {
  1353. var file = GetRebaseDir() + "next";
  1354. return File.Exists(file) ? File.ReadAllText(file).Trim() : "";
  1355. }
  1356. private static string AppendQuotedString(string str1, string str2)
  1357. {
  1358. var m1 = QuotedText.Match(str1);
  1359. var m2 = QuotedText.Match(str2);
  1360. if (!m1.Success || !m2.Success)
  1361. return str1 + str2;
  1362. Debug.Assert(m1.Groups[1].Value == m2.Groups[1].Value);
  1363. return str1.Substring(0, str1.Length - 2) + m2.Groups[2].Value + "?=";
  1364. }
  1365. private static string DecodeString(string str)
  1366. {
  1367. // decode QuotedPrintable text using .NET internal decoder
  1368. Attachment attachment = Attachment.CreateAttachmentFromString("", str);
  1369. return attachment.Name;
  1370. }
  1371. private static readonly Regex HeadersMatch = new Regex(@"^(?<header_key>[-A-Za-z0-9]+)(?::[ \t]*)(?<header_value>.*)$", RegexOptions.Compiled);
  1372. private static readonly Regex QuotedText = new Regex(@"=\?([\w-]+)\?q\?(.*)\?=$", RegexOptions.Compiled);
  1373. public bool InTheMiddleOfInteractiveRebase()
  1374. {
  1375. return File.Exists(GetRebaseDir() + "git-rebase-todo");
  1376. }
  1377. public IList<PatchFile> GetInteractiveRebasePatchFiles()
  1378. {
  1379. string todoFile = GetRebaseDir() + "git-rebase-todo";
  1380. string[] todoCommits = File.Exists(todoFile) ? File.ReadAllText(todoFile).Trim().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) : null;
  1381. IList<PatchFile> patchFiles = new List<PatchFile>();
  1382. if (todoCommits != null)
  1383. {
  1384. foreach (string todoCommit in todoCommits)
  1385. {
  1386. if (todoCommit.StartsWith("#"))
  1387. continue;
  1388. string[] parts = todoCommit.Split(' ');
  1389. if (parts.Length >= 3)
  1390. {
  1391. string error = string.Empty;
  1392. CommitData data = CommitData.GetCommitData(this, parts[1], ref error);
  1393. PatchFile nextCommitPatch = new PatchFile();
  1394. nextCommitPatch.Author = string.IsNullOrEmpty(error) ? data.Author : error;
  1395. nextCommitPatch.Subject = string.IsNullOrEmpty(error) ? data.Body : error;
  1396. nextCommitPatch.Name = parts[0];
  1397. nextCommitPatch.Date = string.IsNullOrEmpty(error) ? data.CommitDate.LocalDateTime.ToString() : error;
  1398. nextCommitPatch.IsNext = patchFiles.Count == 0;
  1399. patchFiles.Add(nextCommitPatch);
  1400. }
  1401. }
  1402. }
  1403. return patchFiles;
  1404. }
  1405. public IList<PatchFile> GetRebasePatchFiles()
  1406. {
  1407. var patchFiles = new List<PatchFile>();
  1408. var nextFile = GetNextRebasePatch();
  1409. int next;
  1410. int.TryParse(nextFile, out next);
  1411. var files = new string[0];
  1412. if (Directory.Exists(GetRebaseDir()))
  1413. files = Directory.GetFiles(GetRebaseDir());
  1414. foreach (var fullFileName in files)
  1415. {
  1416. int n;
  1417. var file = PathUtil.GetFileName(fullFileName);
  1418. if (!int.TryParse(file, out n))
  1419. continue;
  1420. var patchFile =
  1421. new PatchFile
  1422. {
  1423. Name = file,
  1424. FullName = fullFileName,
  1425. IsNext = n == next,
  1426. IsSkipped = n < next
  1427. };
  1428. if (File.Exists(GetRebaseDir() + file))
  1429. {
  1430. string key = null;
  1431. string value = "";
  1432. foreach (var line in File.ReadLines(GetRebaseDir() + file))
  1433. {
  1434. var m = HeadersMatch.Match(line);
  1435. if (key == null)
  1436. {
  1437. if (!String.IsNullOrWhiteSpace(line) && !m.Success)
  1438. continue;
  1439. }
  1440. else if (String.IsNullOrWhiteSpace(line) || m.Success)
  1441. {
  1442. value = DecodeString(value);
  1443. switch (key)
  1444. {
  1445. case "From":
  1446. if (value.IndexOf('<') > 0 && value.IndexOf('<') < value.Length)
  1447. patchFile.Author = value.Substring(0, value.IndexOf('<')).Trim();
  1448. else
  1449. patchFile.Author = value;
  1450. break;
  1451. case "Date":
  1452. if (value.IndexOf('+') > 0 && value.IndexOf('<') < value.Length)
  1453. patchFile.Date = value.Substring(0, value.IndexOf('+')).Trim();
  1454. else
  1455. patchFile.Date = value;
  1456. break;
  1457. case "Subject":
  1458. patchFile.Subject = value;
  1459. break;
  1460. }
  1461. }
  1462. if (m.Success)
  1463. {
  1464. key = m.Groups[1].Value;
  1465. value = m.Groups[2].Value;
  1466. }
  1467. else
  1468. value = AppendQuotedString(value, line.Trim());
  1469. if (string.IsNullOrEmpty(line) ||
  1470. !string.IsNullOrEmpty(patchFile.Author) &&
  1471. !string.IsNullOrEmpty(patchFile.Date) &&
  1472. !string.IsNullOrEmpty(patchFile.Subject))
  1473. break;
  1474. }
  1475. }
  1476. patchFiles.Add(patchFile);
  1477. }
  1478. return patchFiles;
  1479. }
  1480. public string CommitCmd(bool amend, bool signOff = false, string author = "", bool useExplicitCommitMessage = true)
  1481. {
  1482. string command = "commit";
  1483. if (amend)
  1484. command += " --amend";
  1485. if (signOff)
  1486. command += " --signoff";
  1487. if (!string.IsNullOrEmpty(author))
  1488. command += " --author=\"" + author + "\"";
  1489. if (useExplicitCommitMessage)
  1490. {
  1491. var path = Path.Combine(GetGitDirectory(), "COMMITMESSAGE");
  1492. command += " -F \"" + path + "\"";
  1493. }
  1494. return command;
  1495. }
  1496. public string RemoveRemote(string name)
  1497. {
  1498. return RunGitCmd("remote rm \"" + name + "\"");
  1499. }
  1500. public string RenameRemote(string name, string newName)
  1501. {
  1502. return RunGitCmd("remote rename \"" + name + "\" \"" + newName + "\"");
  1503. }
  1504. public string RenameBranch(string name, string newName)
  1505. {
  1506. return RunGitCmd("branch -m \"" + name + "\" \"" + newName + "\"");
  1507. }
  1508. public string AddRemote(string name, string path)
  1509. {
  1510. var location = path.ToPosixPath();
  1511. if (string.IsNullOrEmpty(name))
  1512. return "Please enter a name.";
  1513. return
  1514. string.IsNullOrEmpty(location)
  1515. ? RunGitCmd(string.Format("remote add \"{0}\" \"\"", name))
  1516. : RunGitCmd(string.Format("remote add \"{0}\" \"{1}\"", name, location));
  1517. }
  1518. public string[] GetRemotes(bool allowEmpty = true)
  1519. {
  1520. string remotes = RunGitCmd("remote show");
  1521. return allowEmpty ? remotes.Split('\n') : remotes.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  1522. }
  1523. public IEnumerable<string> GetSettings(string setting)
  1524. {
  1525. return LocalConfigFile.GetValues(setting);
  1526. }
  1527. public string GetSetting(string setting)
  1528. {
  1529. return LocalConfigFile.GetValue(setting);
  1530. }
  1531. public string GetPathSetting(string setting)
  1532. {
  1533. return GetSetting(setting);
  1534. }
  1535. public string GetEffectiveSetting(string setting)
  1536. {
  1537. return EffectiveConfigFile.GetValue(setting);
  1538. }
  1539. public string GetEffectivePathSetting(string setting)
  1540. {
  1541. return GetEffectiveSetting(setting);
  1542. }
  1543. public void UnsetSetting(string setting)
  1544. {
  1545. SetSetting(setting, null);
  1546. }
  1547. public void SetSetting(string setting, string value)
  1548. {
  1549. LocalConfigFile.SetValue(setting, value);
  1550. }
  1551. public void SetPathSetting(string setting, string value)
  1552. {
  1553. LocalConfigFile.SetPathValue(setting, value);
  1554. }
  1555. public IList<GitStash> GetStashes()
  1556. {
  1557. var list = RunGitCmd("stash list").Split('\n');
  1558. var stashes = new List<GitStash>();
  1559. for (int i = 0; i < list.Length; i++)
  1560. {
  1561. string stashString = list[i];
  1562. if (stashString.IndexOf(':') > 0)
  1563. {
  1564. stashes.Add(new GitStash(stashString, i));
  1565. }
  1566. }
  1567. return stashes;
  1568. }
  1569. public Patch GetSingleDiff(string @from, string to, string fileName, string oldFileName, string extraDiffArguments, Encoding encoding, bool cacheResult)
  1570. {
  1571. string fileA = null;
  1572. string fileB = null;
  1573. if (!string.IsNullOrEmpty(fileName))
  1574. {
  1575. fileB = fileName;
  1576. fileName = string.Concat("\"", fileName.ToPosixPath(), "\"");
  1577. }
  1578. if (!string.IsNullOrEmpty(oldFileName))
  1579. {
  1580. fileA = oldFileName;
  1581. oldFileName = string.Concat("\"", oldFileName.ToPosixPath(), "\"");
  1582. }
  1583. if (fileA.IsNullOrEmpty())
  1584. fileA = fileB;
  1585. else if (fileB.IsNullOrEmpty())
  1586. fileB = fileA;
  1587. from = from.ToPosixPath();
  1588. to = to.ToPosixPath();
  1589. string commitRange = string.Empty;
  1590. if (!to.IsNullOrEmpty())
  1591. commitRange = "\"" + to + "\"";
  1592. if (!from.IsNullOrEmpty())
  1593. commitRange = string.Join(" ", commitRange, "\"" + from + "\"");
  1594. if (AppSettings.UsePatienceDiffAlgorithm)
  1595. extraDiffArguments = string.Concat(extraDiffArguments, " --patience");
  1596. var patchManager = new PatchManager();
  1597. var arguments = String.Format("diff {0} -M -C {1} -- {2} {3}", extraDiffArguments, commitRange, fileName, oldFileName);
  1598. string patch;
  1599. if (cacheResult)
  1600. patch = RunCacheableCmd(AppSettings.GitCommand, arguments, LosslessEncoding);
  1601. else
  1602. patch = RunCmd(AppSettings.GitCommand, arguments, LosslessEncoding);
  1603. patchManager.LoadPatch(patch, false, encoding);
  1604. foreach (Patch p in patchManager.Patches)
  1605. if (p.FileNameA.Equals(fileA) && p.FileNameB.Equals(fileB) ||
  1606. p.FileNameA.Equals(fileB) && p.FileNameB.Equals(fileA))
  1607. return p;
  1608. return patchManager.Patches.Count > 0 ? patchManager.Patches[patchManager.Patches.Count - 1] : null;
  1609. }
  1610. public string GetStatusText(bool untracked)
  1611. {
  1612. string cmd = "status -s";
  1613. if (untracked)
  1614. cmd = cmd + " -u";
  1615. return RunGitCmd(cmd);
  1616. }
  1617. public string GetDiffFilesText(string from, string to)
  1618. {
  1619. return GetDiffFilesText(from, to, false);
  1620. }
  1621. public string GetDiffFilesText(string from, string to, bool noCache)
  1622. {
  1623. string cmd = "diff -M -C --name-status \"" + to + "\" \"" + from + "\"";
  1624. return noCache ? RunGitCmd(cmd) : this.RunCacheableCmd(AppSettings.GitCommand, cmd, SystemEncoding);
  1625. }
  1626. public List<GitItemStatus> GetDiffFilesWithSubmodulesStatus(string from, string to)
  1627. {
  1628. var status = GetDiffFiles(from, to);
  1629. GetSubmoduleStatus(status, from, to);
  1630. return status;
  1631. }
  1632. public List<GitItemStatus> GetDiffFiles(string from, string to, bool noCache = false)
  1633. {
  1634. string cmd = "diff -M -C -z --name-status \"" + to + "\" \"" + from + "\"";
  1635. string result = noCache ? RunGitCmd(cmd) : this.RunCacheableCmd(AppSettings.GitCommand, cmd, SystemEncoding);
  1636. return GitCommandHelpers.GetAllChangedFilesFromString(this, result, true);
  1637. }
  1638. public IList<GitItemStatus> GetStashDiffFiles(string stashName)
  1639. {
  1640. var resultCollection = GetDiffFiles(stashName, stashName + "^", true);
  1641. // shows untracked files
  1642. string untrackedTreeHash = RunGitCmd("log " + stashName + "^3 --pretty=format:\"%T\" --max-count=1");
  1643. if (GitRevision.Sha1HashRegex.IsMatch(untrackedTreeHash))
  1644. {
  1645. var files = GetTreeFiles(untrackedTreeHash, true);
  1646. resultCollection.AddRange(files);
  1647. }
  1648. return resultCollection;
  1649. }
  1650. public IList<GitItemStatus> GetTreeFiles(string treeGuid, bool full)
  1651. {
  1652. var tree = GetTree(treeGuid, full);
  1653. var list = tree
  1654. .Select(file => new GitItemStatus
  1655. {
  1656. IsNew = true,
  1657. IsChanged = false,
  1658. IsDeleted = false,
  1659. IsStaged = false,
  1660. Name = file.Name,
  1661. TreeGuid = file.Guid
  1662. }).ToList();
  1663. // Doesn't work with removed submodules
  1664. var submodulesList = GetSubmodulesLocalPathes();
  1665. foreach (var item in list)
  1666. {
  1667. if (submodulesList.Contains(item.Name))
  1668. item.IsSubmodule = true;
  1669. }
  1670. return list;
  1671. }
  1672. public IList<GitItemStatus> GetAllChangedFiles(bool excludeIgnoredFiles = true, UntrackedFilesMode untrackedFiles = UntrackedFilesMode.Default)
  1673. {
  1674. var status = RunGitCmd(GitCommandHelpers.GetAllChangedFilesCmd(excludeIgnoredFiles, untrackedFiles));
  1675. return GitCommandHelpers.GetAllChangedFilesFromString(this, status);
  1676. }
  1677. public IList<GitItemStatus> GetAllChangedFilesWithSubmodulesStatus(bool excludeIgnoredFiles = true, UntrackedFilesMode untrackedFiles = UntrackedFilesMode.Default)
  1678. {
  1679. var status = GetAllChangedFiles(excludeIgnoredFiles, untrackedFiles);
  1680. GetCurrentSubmoduleStatus(status);
  1681. return status;
  1682. }
  1683. private void GetCurrentSubmoduleStatus(IList<GitItemStatus> status)
  1684. {
  1685. foreach (var item in status)
  1686. if (item.IsSubmodule)
  1687. {
  1688. var localItem = item;
  1689. localItem.SubmoduleStatus = Task.Factory.StartNew(() =>
  1690. {
  1691. var submoduleStatus = GitCommandHelpers.GetCurrentSubmoduleChanges(this, localItem.Name, localItem.OldName, localItem.IsStaged);
  1692. if (submoduleStatus != null && submoduleStatus.Commit != submoduleStatus.OldCommit)
  1693. {
  1694. var submodule = submoduleStatus.GetSubmodule(this);
  1695. submoduleStatus.CheckSubmoduleStatus(submodule);
  1696. }
  1697. return submoduleStatus;
  1698. });
  1699. }
  1700. }
  1701. private void GetSubmoduleStatus(IList<GitItemStatus> status, string from, string to)
  1702. {
  1703. status.ForEach(item =>
  1704. {
  1705. if (item.IsSubmodule)
  1706. {
  1707. item.SubmoduleStatus = Task.Factory.StartNew(() =>
  1708. {
  1709. Patch patch = GetSingleDiff(from, to, item.Name, item.OldName, "", SystemEncoding, true);
  1710. string text = patch != null ? patch.Text : "";
  1711. var submoduleStatus = GitCommandHelpers.GetSubmoduleStatus(text, this, item.Name);
  1712. if (submoduleStatus.Commit != submoduleStatus.OldCommit)
  1713. {
  1714. var submodule = submoduleStatus.GetSubmodule(this);
  1715. submoduleStatus.CheckSubmoduleStatus(submodule);
  1716. }
  1717. return submoduleStatus;
  1718. });
  1719. }
  1720. });
  1721. }
  1722. public IList<GitItemStatus> GetStagedFiles()
  1723. {
  1724. string status = RunGitCmd("diff -M -C -z --cached --name-status", SystemEncoding);
  1725. if (status.Length < 50 && status.Contains("fatal: No HEAD commit to compare"))
  1726. {
  1727. //This command is a little more expensive because it will return both staged and unstaged files
  1728. string command = GitCommandHelpers.GetAllChangedFilesCmd(true, UntrackedFilesMode.No);
  1729. status = RunGitCmd(command, SystemEncoding);
  1730. IList<GitItemStatus> stagedFiles = GitCommandHelpers.GetAllChangedFilesFromString(this, status, false);
  1731. return stagedFiles.Where(f => f.IsStaged).ToList();
  1732. }
  1733. return GitCommandHelpers.GetAllChangedFilesFromString(this, status, true);
  1734. }
  1735. public IList<GitItemStatus> GetStagedFilesWithSubmodulesStatus()
  1736. {
  1737. var status = GetStagedFiles();
  1738. GetCurrentSubmoduleStatus(status);
  1739. return status;
  1740. }
  1741. public IList<GitItemStatus> GetUnstagedFiles()
  1742. {
  1743. return GetAllChangedFiles().Where(x => !x.IsStaged).ToArray();
  1744. }
  1745. public IList<GitItemStatus> GetUnstagedFilesWithSubmodulesStatus()
  1746. {
  1747. return GetAllChangedFilesWithSubmodulesStatus().Where(x => !x.IsStaged).ToArray();
  1748. }
  1749. public IList<GitItemStatus> GitStatus(UntrackedFilesMode untrackedFilesMode, IgnoreSubmodulesMode ignoreSubmodulesMode = 0)
  1750. {
  1751. string command = GitCommandHelpers.GetAllChangedFilesCmd(true, untrackedFilesMode, ignoreSubmodulesMode);
  1752. string status = RunGitCmd(command);
  1753. return GitCommandHelpers.GetAllChangedFilesFromString(this, status);
  1754. }
  1755. /// <summary>Indicates whether there are any changes to the repository,
  1756. /// including any untracked files or directories; excluding submodules.</summary>
  1757. public bool IsDirtyDir()
  1758. {
  1759. return GitStatus(UntrackedFilesMode.All, IgnoreSubmodulesMode.Default).Count > 0;
  1760. }
  1761. public Patch GetCurrentChanges(string fileName, string oldFileName, bool staged, string extraDiffArguments, Encoding encoding)
  1762. {
  1763. fileName = string.Concat("\"", fileName.ToPosixPath(), "\"");
  1764. if (!string.IsNullOrEmpty(oldFileName))
  1765. oldFileName = string.Concat("\"", oldFileName.ToPosixPath(), "\"");
  1766. if (AppSettings.UsePatienceDiffAlgorithm)
  1767. extraDiffArguments = string.Concat(extraDiffArguments, " --patience");
  1768. var args = string.Concat("diff ", extraDiffArguments, " -- ", fileName);
  1769. if (staged)
  1770. args = string.Concat("diff -M -C --cached", extraDiffArguments, " -- ", fileName, " ", oldFileName);
  1771. String result = RunGitCmd(args, LosslessEncoding);
  1772. var patchManager = new PatchManager();
  1773. patchManager.LoadPatch(result, false, encoding);
  1774. return patchManager.Patches.Count > 0 ? patchManager.Patches[patchManager.Patches.Count - 1] : null;
  1775. }
  1776. public string StageFile(string file)
  1777. {
  1778. return RunGitCmd("update-index --add" + " \"" + file.ToPosixPath() + "\"");
  1779. }
  1780. public string StageFileToRemove(string file)
  1781. {
  1782. return RunGitCmd("update-index --remove" + " \"" + file.ToPosixPath() + "\"");
  1783. }
  1784. public string UnstageFile(string file)
  1785. {
  1786. return RunGitCmd("rm --cached \"" + file.ToPosixPath() + "\"");
  1787. }
  1788. public string UnstageFileToRemove(string file)
  1789. {
  1790. return RunGitCmd("reset HEAD -- \"" + file.ToPosixPath() + "\"");
  1791. }
  1792. /// <summary>Dirty but fast. This sometimes fails.</summary>
  1793. public static string GetSelectedBranchFast(string repositoryPath)
  1794. {
  1795. if (string.IsNullOrEmpty(repositoryPath))
  1796. return string.Empty;
  1797. string head;
  1798. string headFileName = Path.Combine(GetGitDirectory(repositoryPath), "HEAD");
  1799. if (File.Exists(headFileName))
  1800. {
  1801. head = File.ReadAllText(headFileName, SystemEncoding);
  1802. if (!head.Contains("ref:"))
  1803. return DetachedBranch;
  1804. }
  1805. else
  1806. {
  1807. return string.Empty;
  1808. }
  1809. if (!string.IsNullOrEmpty(head))
  1810. {
  1811. return head.Replace("ref:", "").Replace("refs/heads/", string.Empty).Trim();
  1812. }
  1813. return string.Empty;
  1814. }
  1815. /// <summary>Gets the current branch; or "(no branch)" if HEAD is detached.</summary>
  1816. public string GetSelectedBranch(string repositoryPath)
  1817. {
  1818. string head = GetSelectedBranchFast(repositoryPath);
  1819. if (string.IsNullOrEmpty(head))
  1820. {
  1821. var result = RunGitCmdResult("symbolic-ref HEAD");
  1822. if (result.ExitCode == 1)
  1823. return DetachedBranch;
  1824. return result.StdOutput;
  1825. }
  1826. return head;
  1827. }
  1828. /// <summary>Gets the current branch; or "(no branch)" if HEAD is detached.</summary>
  1829. public string GetSelectedBranch()
  1830. {
  1831. return GetSelectedBranch(_workingDir);
  1832. }
  1833. /// <summary>Indicates whether HEAD is not pointing to a branch.</summary>
  1834. public bool IsDetachedHead()
  1835. {
  1836. return IsDetachedHead(GetSelectedBranch());
  1837. }
  1838. public static bool IsDetachedHead(string branch)
  1839. {
  1840. return DetachedPrefixes.Any(a => branch.StartsWith(a, StringComparison.Ordinal));
  1841. }
  1842. /// <summary>Gets the remote of the current branch; or "origin" if no remote is configured.</summary>
  1843. public string GetCurrentRemote()
  1844. {
  1845. string remote = GetSetting(string.Format("branch.{0}.remote", GetSelectedBranch()));
  1846. return remote;
  1847. }
  1848. /// <summary>Gets the remote branch of the specified local branch; or "" if none is configured.</summary>
  1849. public string GetRemoteBranch(string branch)
  1850. {
  1851. string remote = GetSetting(string.Format("branch.{0}.remote", branch));
  1852. string merge = GetSetting(string.Format("branch.{0}.merge", branch));
  1853. if (String.IsNullOrEmpty(remote) || String.IsNullOrEmpty(merge))
  1854. return "";
  1855. return remote + "/" + (merge.StartsWith("refs/heads/") ? merge.Substring(11) : merge);
  1856. }
  1857. public RemoteActionResult<IList<GitRef>> GetRemoteRefs(string remote, bool tags, bool branches)
  1858. {
  1859. RemoteActionResult<IList<GitRef>> result = new RemoteActionResult<IList<GitRef>>()
  1860. {
  1861. AuthenticationFail = false,
  1862. HostKeyFail = false,
  1863. Result = null
  1864. };
  1865. remote = remote.ToPosixPath();
  1866. var tree = GetTreeFromRemoteRefs(remote, tags, branches);
  1867. // If the authentication failed because of a missing key, ask the user to supply one.
  1868. if (tree.Contains("FATAL ERROR") && tree.Contains("authentication"))
  1869. {
  1870. result.AuthenticationFail = true;
  1871. }
  1872. else if (tree.ToLower().Contains("the server's host key is not cached in the registry"))
  1873. {
  1874. result.HostKeyFail = true;
  1875. }
  1876. else
  1877. {
  1878. result.Result = GetTreeRefs(tree);
  1879. }
  1880. return result;
  1881. }
  1882. private string GetTreeFromRemoteRefs(string remote, bool tags, bool branches)
  1883. {
  1884. if (tags && branches)
  1885. return RunGitCmd("ls-remote --heads --tags \"" + remote + "\"");
  1886. if (tags)
  1887. return RunGitCmd("ls-remote --tags \"" + remote + "\"");
  1888. if (branches)
  1889. return RunGitCmd("ls-remote --heads \"" + remote + "\"");
  1890. return "";
  1891. }
  1892. public IList<GitRef> GetRefs(bool tags = true, bool branches = true)
  1893. {
  1894. var tree = GetTree(tags, branches);
  1895. return GetTreeRefs(tree);
  1896. }
  1897. /// <summary>
  1898. ///
  1899. /// </summary>
  1900. /// <param name="option">Ordery by date is slower.</param>
  1901. /// <returns></returns>
  1902. public IList<GitRef> GetTagRefs(GetTagRefsSortOrder option)
  1903. {
  1904. var list = GetRefs(true, false);
  1905. var sortedList = new List<GitRef>();
  1906. if (option == GetTagRefsSortOrder.ByCommitDateAscending)
  1907. {
  1908. sortedList = list.OrderBy(head =>
  1909. {
  1910. var r = new GitRevision(this, head.Guid);
  1911. return r.CommitDate;
  1912. }).ToList();
  1913. }
  1914. else if (option == GetTagRefsSortOrder.ByCommitDateDescending)
  1915. {
  1916. sortedList = list.OrderByDescending(head =>
  1917. {
  1918. var r = new GitRevision(this, head.Guid);
  1919. return r.CommitDate;
  1920. }).ToList();
  1921. }
  1922. else
  1923. sortedList = new List<GitRef>(list);
  1924. return sortedList;
  1925. }
  1926. public enum GetTagRefsSortOrder
  1927. {
  1928. /// <summary>
  1929. /// default
  1930. /// </summary>
  1931. ByName,
  1932. /// <summary>
  1933. /// slower than ByName
  1934. /// </summary>
  1935. ByCommitDateAscending,
  1936. /// <summary>
  1937. /// slower than ByName
  1938. /// </summary>
  1939. ByCommitDateDescending
  1940. }
  1941. public ICollection<string> GetMergedBranches()
  1942. {
  1943. return RunGitCmd(GitCommandHelpers.MergedBranches()).Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  1944. }
  1945. private string GetTree(bool tags, bool branches)
  1946. {
  1947. if (tags && branches)
  1948. return RunGitCmd("show-ref --dereference", SystemEncoding);
  1949. if (tags)
  1950. return RunGitCmd("show-ref --tags", SystemEncoding);
  1951. if (branches)
  1952. return RunGitCmd("show-ref --dereference --heads", SystemEncoding);
  1953. return "";
  1954. }
  1955. private IList<GitRef> GetTreeRefs(string tree)
  1956. {
  1957. var itemsStrings = tree.Split('\n');
  1958. var gitRefs = new List<GitRef>();
  1959. var defaultHeads = new Dictionary<string, GitRef>(); // remote -> HEAD
  1960. var remotes = GetRemotes(false);
  1961. foreach (var itemsString in itemsStrings)
  1962. {
  1963. if (itemsString == null || itemsString.Length <= 42)
  1964. continue;
  1965. var completeName = itemsString.Substring(41).Trim();
  1966. var guid = itemsString.Substring(0, 40);
  1967. var remoteName = GitCommandHelpers.GetRemoteName(completeName, remotes);
  1968. var head = new GitRef(this, guid, completeName, remoteName);
  1969. if (DefaultHeadPattern.IsMatch(completeName))
  1970. defaultHeads[remoteName] = head;
  1971. else
  1972. gitRefs.Add(head);
  1973. }
  1974. // do not show default head if remote has a branch on the same commit
  1975. GitRef defaultHead;
  1976. foreach (var gitRef in gitRefs.Where(head => defaultHeads.TryGetValue(head.Remote, out defaultHead) && head.Guid == defaultHead.Guid))
  1977. {
  1978. defaultHeads.Remove(gitRef.Remote);
  1979. }
  1980. gitRefs.AddRange(defaultHeads.Values);
  1981. return gitRefs;
  1982. }
  1983. /// <summary>
  1984. /// Gets branches which contain the given commit.
  1985. /// If both local and remote branches are requested, remote branches are prefixed with "remotes/"
  1986. /// (as returned by git branch -a)
  1987. /// </summary>
  1988. /// <param name="sha1">The sha1.</param>
  1989. /// <param name="getLocal">Pass true to include local branches</param>
  1990. /// <param name="getRemote">Pass true to include remote branches</param>
  1991. /// <returns></returns>
  1992. public IEnumerable<string> GetAllBranchesWhichContainGivenCommit(string sha1, bool getLocal, bool getRemote)
  1993. {
  1994. string args = "--contains " + sha1;
  1995. if (getRemote && getLocal)
  1996. args = "-a " + args;
  1997. else if (getRemote)
  1998. args = "-r " + args;
  1999. else if (!getLocal)
  2000. return new string[] { };
  2001. string info = RunGitCmd("branch " + args);
  2002. if (info.Trim().StartsWith("fatal") || info.Trim().StartsWith("error:"))
  2003. return new List<string>();
  2004. string[] result = info.Split(new[] { '\r', '\n', '*' }, StringSplitOptions.RemoveEmptyEntries);
  2005. // Remove symlink targets as in "origin/HEAD -> origin/master"
  2006. for (int i = 0; i < result.Length; i++)
  2007. {
  2008. string item = result[i].Trim();
  2009. int idx;
  2010. if (getRemote && ((idx = item.IndexOf(" ->")) >= 0))
  2011. {
  2012. item = item.Substring(0, idx);
  2013. }
  2014. result[i] = item;
  2015. }
  2016. return result;
  2017. }
  2018. /// <summary>
  2019. /// Gets all tags which contain the given commit.
  2020. /// </summary>
  2021. /// <param name="sha1">The sha1.</param>
  2022. /// <returns></returns>
  2023. public IEnumerable<string> GetAllTagsWhichContainGivenCommit(string sha1)
  2024. {
  2025. string info = RunGitCmd("tag --contains " + sha1, SystemEncoding);
  2026. if (info.Trim().StartsWith("fatal") || info.Trim().StartsWith("error:"))
  2027. return new List<string>();
  2028. return info.Split(new[] { '\r', '\n', '*', ' ' }, StringSplitOptions.RemoveEmptyEntries);
  2029. }
  2030. /// <summary>
  2031. /// Returns list of filenames which would be ignored
  2032. /// </summary>
  2033. /// <param name="ignorePatterns">Patterns to ignore (.gitignore syntax)</param>
  2034. /// <returns></returns>
  2035. public IList<string> GetIgnoredFiles(IEnumerable<string> ignorePatterns)
  2036. {
  2037. var notEmptyPatterns = ignorePatterns
  2038. .Where(pattern => !pattern.IsNullOrWhiteSpace());
  2039. if (notEmptyPatterns.Count() != 0)
  2040. {
  2041. var excludeParams =
  2042. notEmptyPatterns
  2043. .Select(pattern => "-x " + pattern.Quote())
  2044. .Join(" ");
  2045. // filter duplicates out of the result because options -c and -m may return
  2046. // same files at times
  2047. return RunGitCmd("ls-files -z -o -m -c -i " + excludeParams)
  2048. .Split(new[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries)
  2049. .Distinct()
  2050. .ToList();
  2051. }
  2052. else
  2053. {
  2054. return new string[] { };
  2055. }
  2056. }
  2057. public string[] GetFullTree(string id)
  2058. {
  2059. string tree = this.RunCacheableCmd(AppSettings.GitCommand, String.Format("ls-tree -z -r --name-only {0}", id), SystemEncoding);
  2060. return tree.Split(new char[] { '\0', '\n' });
  2061. }
  2062. public IList<IGitItem> GetTree(string id, bool full)
  2063. {
  2064. string args = "-z";
  2065. if (full)
  2066. args += " -r";
  2067. var tree = this.RunCacheableCmd(AppSettings.GitCommand, "ls-tree " + args + " \"" + id + "\"", SystemEncoding);
  2068. return GitItem.CreateIGitItemsFromString(this, tree);
  2069. }
  2070. public GitBlame Blame(string filename, string from, Encoding encoding)
  2071. {
  2072. return Blame(filename, from, null, encoding);
  2073. }
  2074. public GitBlame Blame(string filename, string from, string lines, Encoding encoding)
  2075. {
  2076. from = from.ToPosixPath();
  2077. filename = filename.ToPosixPath();
  2078. string blameCommand = string.Format("blame --porcelain -M -w -l{0} \"{1}\" -- \"{2}\"", lines != null ? " -L " + lines : "", from, filename);
  2079. var itemsStrings =
  2080. RunCacheableCmd(
  2081. AppSettings.GitCommand,
  2082. blameCommand,
  2083. LosslessEncoding
  2084. )
  2085. .Split('\n');
  2086. GitBlame blame = new GitBlame();
  2087. GitBlameHeader blameHeader = null;
  2088. GitBlameLine blameLine = null;
  2089. for (int i = 0; i < itemsStrings.GetLength(0); i++)
  2090. {
  2091. try
  2092. {
  2093. string line = itemsStrings[i];
  2094. //The contents of the actual line is output after the above header, prefixed by a TAB. This is to allow adding more header elements later.
  2095. if (line.StartsWith("\t"))
  2096. {
  2097. blameLine.LineText = line.Substring(1) //trim ONLY first tab
  2098. .Trim(new char[] { '\r' }); //trim \r, this is a workaround for a \r\n bug
  2099. blameLine.LineText = ReEncodeStringFromLossless(blameLine.LineText, encoding);
  2100. }
  2101. else if (line.StartsWith("author-mail"))
  2102. blameHeader.AuthorMail = ReEncodeStringFromLossless(line.Substring("author-mail".Length).Trim());
  2103. else if (line.StartsWith("author-time"))
  2104. blameHeader.AuthorTime = DateTimeUtils.ParseUnixTime(line.Substring("author-time".Length).Trim());
  2105. else if (line.StartsWith("author-tz"))
  2106. blameHeader.AuthorTimeZone = line.Substring("author-tz".Length).Trim();
  2107. else if (line.StartsWith("author"))
  2108. {
  2109. blameHeader = new GitBlameHeader();
  2110. blameHeader.CommitGuid = blameLine.CommitGuid;
  2111. blameHeader.Author = ReEncodeStringFromLossless(line.Substring("author".Length).Trim());
  2112. blame.Headers.Add(blameHeader);
  2113. }
  2114. else if (line.StartsWith("committer-mail"))
  2115. blameHeader.CommitterMail = line.Substring("committer-mail".Length).Trim();
  2116. else if (line.StartsWith("committer-time"))
  2117. blameHeader.CommitterTime = DateTimeUtils.ParseUnixTime(line.Substring("committer-time".Length).Trim());
  2118. else if (line.StartsWith("committer-tz"))
  2119. blameHeader.CommitterTimeZone = line.Substring("committer-tz".Length).Trim();
  2120. else if (line.StartsWith("committer"))
  2121. blameHeader.Committer = ReEncodeStringFromLossless(line.Substring("committer".Length).Trim());
  2122. else if (line.StartsWith("summary"))
  2123. blameHeader.Summary = ReEncodeStringFromLossless(line.Substring("summary".Length).Trim());
  2124. else if (line.StartsWith("filename"))
  2125. blameHeader.FileName = ReEncodeFileNameFromLossless(line.Substring("filename".Length).Trim());
  2126. else if (line.IndexOf(' ') == 40) //SHA1, create new line!
  2127. {
  2128. blameLine = new GitBlameLine();
  2129. var headerParams = line.Split(' ');
  2130. blameLine.CommitGuid = headerParams[0];
  2131. if (headerParams.Length >= 3)
  2132. {
  2133. blameLine.OriginLineNumber = int.Parse(headerParams[1]);
  2134. blameLine.FinalLineNumber = int.Parse(headerParams[2]);
  2135. }
  2136. blame.Lines.Add(blameLine);
  2137. }
  2138. }
  2139. catch
  2140. {
  2141. //Catch all parser errors, and ignore them all!
  2142. //We should never get here...
  2143. AppSettings.GitLog.Log("Error parsing output from command: " + blameCommand + "\n\nPlease report a bug!");
  2144. }
  2145. }
  2146. return blame;
  2147. }
  2148. public string GetFileText(string id, Encoding encoding)
  2149. {
  2150. return RunCacheableCmd(AppSettings.GitCommand, "cat-file blob \"" + id + "\"", encoding);
  2151. }
  2152. public string GetFileBlobHash(string fileName, string revision)
  2153. {
  2154. if (revision == GitRevision.UnstagedGuid) //working directory changes
  2155. {
  2156. return null;
  2157. }
  2158. if (revision == GitRevision.IndexGuid) //index
  2159. {
  2160. string blob = RunGitCmd(string.Format("ls-files -s \"{0}\"", fileName));
  2161. string[] s = blob.Split(new char[] { ' ', '\t' });
  2162. if (s.Length >= 2)
  2163. return s[1];
  2164. }
  2165. else
  2166. {
  2167. string blob = RunGitCmd(string.Format("ls-tree -r {0} \"{1}\"", revision, fileName));
  2168. string[] s = blob.Split(new char[] { ' ', '\t' });
  2169. if (s.Length >= 3)
  2170. return s[2];
  2171. }
  2172. return string.Empty;
  2173. }
  2174. public static void StreamCopy(Stream input, Stream output)
  2175. {
  2176. int read;
  2177. var buffer = new byte[2048];
  2178. do
  2179. {
  2180. read = input.Read(buffer, 0, buffer.Length);
  2181. output.Write(buffer, 0, read);
  2182. } while (read > 0);
  2183. }
  2184. public Stream GetFileStream(string blob)
  2185. {
  2186. try
  2187. {
  2188. var newStream = new MemoryStream();
  2189. using (var process = RunGitCmdDetached("cat-file blob " + blob))
  2190. {
  2191. StreamCopy(process.StandardOutput.BaseStream, newStream);
  2192. newStream.Position = 0;
  2193. process.WaitForExit();
  2194. return newStream;
  2195. }
  2196. }
  2197. catch (Win32Exception ex)
  2198. {
  2199. Trace.WriteLine(ex);
  2200. }
  2201. return null;
  2202. }
  2203. public IEnumerable<string> GetPreviousCommitMessages(int count)
  2204. {
  2205. return GetPreviousCommitMessages("HEAD", count);
  2206. }
  2207. public IEnumerable<string> GetPreviousCommitMessages(string revision, int count)
  2208. {
  2209. string sep = "d3fb081b9000598e658da93657bf822cc87b2bf6";
  2210. string output = RunGitCmd("log -n " + count + " " + revision + " --pretty=format:" + sep + "%e%n%s%n%n%b", LosslessEncoding);
  2211. string[] messages = output.Split(new string[] { sep }, StringSplitOptions.RemoveEmptyEntries);
  2212. if (messages.Length == 0)
  2213. return new string[] { string.Empty };
  2214. return messages.Select(cm =>
  2215. {
  2216. int idx = cm.IndexOf("\n");
  2217. string encodingName = cm.Substring(0, idx);
  2218. cm = cm.Substring(idx + 1, cm.Length - idx - 1);
  2219. cm = ReEncodeCommitMessage(cm, encodingName);
  2220. return cm;
  2221. });
  2222. }
  2223. public string OpenWithDifftool(string filename, string oldFileName = "", string revision1 = null, string revision2 = null, string extraDiffArguments = "")
  2224. {
  2225. var output = "";
  2226. if (!filename.IsNullOrEmpty())
  2227. filename = filename.Quote();
  2228. if (!oldFileName.IsNullOrEmpty())
  2229. oldFileName = oldFileName.Quote();
  2230. string args = string.Join(" ", extraDiffArguments, revision2.QuoteNE(), revision1.QuoteNE(), "--", filename, oldFileName);
  2231. RunGitCmdDetached("difftool --gui --no-prompt " + args);
  2232. return output;
  2233. }
  2234. public string RevParse(string revisionExpression)
  2235. {
  2236. string revparseCommand = string.Format("rev-parse \"{0}~0\"", revisionExpression);
  2237. var result = RunGitCmdResult(revparseCommand);
  2238. return result.ExitCode == 0? result.StdOutput.Split('\n')[0] : "";
  2239. }
  2240. public string GetMergeBase(string a, string b)
  2241. {
  2242. return RunGitCmd("merge-base " + a + " " + b).TrimEnd();
  2243. }
  2244. public SubmoduleStatus CheckSubmoduleStatus(string commit, string oldCommit, CommitData data, CommitData olddata, bool loaddata = false)
  2245. {
  2246. if (!IsValidGitWorkingDir() || oldCommit == null)
  2247. return SubmoduleStatus.NewSubmodule;
  2248. if (commit == null || commit == oldCommit)
  2249. return SubmoduleStatus.Unknown;
  2250. string baseCommit = GetMergeBase(commit, oldCommit);
  2251. if (baseCommit == oldCommit)
  2252. return SubmoduleStatus.FastForward;
  2253. else if (baseCommit == commit)
  2254. return SubmoduleStatus.Rewind;
  2255. string error = "";
  2256. if (loaddata)
  2257. olddata = CommitData.GetCommitData(this, oldCommit, ref error);
  2258. if (olddata == null)
  2259. return SubmoduleStatus.NewSubmodule;
  2260. if (loaddata)
  2261. data = CommitData.GetCommitData(this, commit, ref error);
  2262. if (data == null)
  2263. return SubmoduleStatus.Unknown;
  2264. if (data.CommitDate > olddata.CommitDate)
  2265. return SubmoduleStatus.NewerTime;
  2266. else if (data.CommitDate < olddata.CommitDate)
  2267. return SubmoduleStatus.OlderTime;
  2268. else if (data.CommitDate == olddata.CommitDate)
  2269. return SubmoduleStatus.SameTime;
  2270. return SubmoduleStatus.Unknown;
  2271. }
  2272. public SubmoduleStatus CheckSubmoduleStatus(string commit, string oldCommit)
  2273. {
  2274. return CheckSubmoduleStatus(commit, oldCommit, null, null, true);
  2275. }
  2276. /// <summary>
  2277. /// Uses check-ref-format to ensure that a branch name is well formed.
  2278. /// </summary>
  2279. /// <param name="branchName">Branch name to test.</param>
  2280. /// <returns>true if <see cref="branchName"/> is valid reference name, otherwise false.</returns>
  2281. public bool CheckBranchFormat([NotNull] string branchName)
  2282. {
  2283. if (branchName == null)
  2284. throw new ArgumentNullException("branchName");
  2285. if (branchName.IsNullOrWhiteSpace())
  2286. return false;
  2287. branchName = branchName.Replace("\"", "\\\"");
  2288. var result = RunGitCmdResult(string.Format("check-ref-format --branch \"{0}\"", branchName));
  2289. return result.ExitCode == 0;
  2290. }
  2291. public bool IsLockedIndex()
  2292. {
  2293. return IsLockedIndex(_workingDir);
  2294. }
  2295. public static bool IsLockedIndex(string repositoryPath)
  2296. {
  2297. var gitDir = GetGitDirectory(repositoryPath);
  2298. var indexLockFile = Path.Combine(gitDir, "index.lock");
  2299. return File.Exists(indexLockFile);
  2300. }
  2301. public bool IsRunningGitProcess()
  2302. {
  2303. if (IsLockedIndex())
  2304. {
  2305. return true;
  2306. }
  2307. if (EnvUtils.RunningOnWindows())
  2308. {
  2309. return Process.GetProcessesByName("git").Length > 0;
  2310. }
  2311. // Get processes by "ps" command.
  2312. var cmd = Path.Combine(AppSettings.GitBinDir, "ps");
  2313. var arguments = "x";
  2314. var output = RunCmd(cmd, arguments);
  2315. var lines = output.Split('\n');
  2316. if (lines.Count() >= 2)
  2317. return false;
  2318. var headers = lines[0].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  2319. var commandIndex = Array.IndexOf(headers, "COMMAND");
  2320. for (int i = 1; i < lines.Count(); i++)
  2321. {
  2322. var columns = lines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  2323. if (commandIndex < columns.Count())
  2324. {
  2325. var command = columns[commandIndex];
  2326. if (command.EndsWith("/git"))
  2327. {
  2328. return true;
  2329. }
  2330. }
  2331. }
  2332. return false;
  2333. }
  2334. public static string UnquoteFileName(string fileName)
  2335. {
  2336. char[] chars = fileName.ToCharArray();
  2337. IList<byte> blist = new List<byte>();
  2338. int i = 0;
  2339. StringBuilder sb = new StringBuilder();
  2340. while (i < chars.Length)
  2341. {
  2342. char c = chars[i];
  2343. if (c == '\\')
  2344. {
  2345. //there should be 3 digits
  2346. if (chars.Length >= i + 3)
  2347. {
  2348. string octNumber = "" + chars[i + 1] + chars[i + 2] + chars[i + 3];
  2349. try
  2350. {
  2351. int code = Convert.ToInt32(octNumber, 8);
  2352. blist.Add((byte)code);
  2353. i += 4;
  2354. }
  2355. catch (Exception)
  2356. {
  2357. }
  2358. }
  2359. }
  2360. else
  2361. {
  2362. if (blist.Count > 0)
  2363. {
  2364. sb.Append(SystemEncoding.GetString(blist.ToArray()));
  2365. blist.Clear();
  2366. }
  2367. sb.Append(c);
  2368. i++;
  2369. }
  2370. }
  2371. if (blist.Count > 0)
  2372. {
  2373. sb.Append(SystemEncoding.GetString(blist.ToArray()));
  2374. blist.Clear();
  2375. }
  2376. return sb.ToString();
  2377. }
  2378. public static string ReEncodeFileNameFromLossless(string fileName)
  2379. {
  2380. fileName = ReEncodeStringFromLossless(fileName, SystemEncoding);
  2381. return UnquoteFileName(fileName);
  2382. }
  2383. public static string ReEncodeString(string s, Encoding fromEncoding, Encoding toEncoding)
  2384. {
  2385. if (s == null || fromEncoding.HeaderName.Equals(toEncoding.HeaderName))
  2386. return s;
  2387. else
  2388. {
  2389. byte[] bytes = fromEncoding.GetBytes(s);
  2390. s = toEncoding.GetString(bytes);
  2391. return s;
  2392. }
  2393. }
  2394. /// <summary>
  2395. /// reencodes string from GitCommandHelpers.LosslessEncoding to toEncoding
  2396. /// </summary>
  2397. /// <param name="s"></param>
  2398. /// <returns></returns>
  2399. public static string ReEncodeStringFromLossless(string s, Encoding toEncoding)
  2400. {
  2401. if (toEncoding == null)
  2402. return s;
  2403. return ReEncodeString(s, LosslessEncoding, toEncoding);
  2404. }
  2405. public string ReEncodeStringFromLossless(string s)
  2406. {
  2407. return ReEncodeStringFromLossless(s, LogOutputEncoding);
  2408. }
  2409. //there is a bug: git does not recode commit message when format is given
  2410. //Lossless encoding is used, because LogOutputEncoding might not be lossless and not recoded
  2411. //characters could be replaced by replacement character while reencoding to LogOutputEncoding
  2412. public string ReEncodeCommitMessage(string s, string toEncodingName)
  2413. {
  2414. bool isABug = true;
  2415. Encoding encoding;
  2416. try
  2417. {
  2418. if (isABug)
  2419. {
  2420. if (toEncodingName.IsNullOrEmpty())
  2421. encoding = Encoding.UTF8;
  2422. else if (toEncodingName.Equals(LosslessEncoding.HeaderName, StringComparison.InvariantCultureIgnoreCase))
  2423. encoding = null; //no recoding is needed
  2424. else
  2425. encoding = Encoding.GetEncoding(toEncodingName);
  2426. }
  2427. else//if bug will be fixed, git should recode commit message to LogOutputEncoding
  2428. encoding = LogOutputEncoding;
  2429. }
  2430. catch (Exception)
  2431. {
  2432. return "! Unsupported commit message encoding: " + toEncodingName + " !\n\n" + s;
  2433. }
  2434. return ReEncodeStringFromLossless(s, encoding);
  2435. }
  2436. /// <summary>
  2437. /// header part of show result is encoded in logoutputencoding (including reencoded commit message)
  2438. /// diff part is raw data in file's original encoding
  2439. /// s should be encoded in LosslessEncoding
  2440. /// </summary>
  2441. /// <param name="s"></param>
  2442. /// <returns></returns>
  2443. public string ReEncodeShowString(string s)
  2444. {
  2445. if (s.IsNullOrEmpty())
  2446. return s;
  2447. int p = s.IndexOf("diff --git");
  2448. string header;
  2449. string diffHeader;
  2450. string diffContent;
  2451. string diff;
  2452. if (p > 0)
  2453. {
  2454. header = s.Substring(0, p);
  2455. diff = s.Substring(p);
  2456. }
  2457. else
  2458. {
  2459. header = string.Empty;
  2460. diff = s;
  2461. }
  2462. p = diff.IndexOf("@@");
  2463. if (p > 0)
  2464. {
  2465. diffHeader = diff.Substring(0, p);
  2466. diffContent = diff.Substring(p);
  2467. }
  2468. else
  2469. {
  2470. diffHeader = string.Empty;
  2471. diffContent = diff;
  2472. }
  2473. header = ReEncodeString(header, LosslessEncoding, LogOutputEncoding);
  2474. diffHeader = ReEncodeFileNameFromLossless(diffHeader);
  2475. diffContent = ReEncodeString(diffContent, LosslessEncoding, FilesEncoding);
  2476. return header + diffHeader + diffContent;
  2477. }
  2478. public override bool Equals(object obj)
  2479. {
  2480. if (obj == null) { return false; }
  2481. if (obj == this) { return true; }
  2482. GitModule other = obj as GitModule;
  2483. return (other != null) && Equals(other);
  2484. }
  2485. bool Equals(GitModule other)
  2486. {
  2487. return
  2488. string.Equals(_workingDir, other._workingDir) &&
  2489. Equals(_superprojectModule, other._superprojectModule);
  2490. }
  2491. public override int GetHashCode()
  2492. {
  2493. return _workingDir.GetHashCode();
  2494. }
  2495. public override string ToString()
  2496. {
  2497. return WorkingDir;
  2498. }
  2499. }
  2500. }