PageRenderTime 77ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/GitCommands/Git/GitModule.cs

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