PageRenderTime 47ms CodeModel.GetById 11ms 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

Large files files are truncated, but you can click here to view the full file

  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(rem

Large files files are truncated, but you can click here to view the full file