PageRenderTime 51ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/GitCommands/Git/GitModule.cs

https://github.com/ffrancomontoya/gitextensions
C# | 2952 lines | 2349 code | 452 blank | 151 comment | 407 complexity | 1d38ab80e40c5c5ea14e33e4463ef8de MD5 | raw file
Possible License(s): GPL-3.0, GPL-2.0

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. String s = new GitModule("").RunGitCmd(arguments, Encoding.UTF8);
  176. if (s != null && s.IndexOf(controlStr) != -1)
  177. _systemEncoding = new UTF8Encoding(false);
  178. else
  179. _systemEncoding = Encoding.Default;
  180. Debug.WriteLine("System encoding: " + _systemEncoding.EncodingName);
  181. }
  182. return _systemEncoding;
  183. }
  184. }
  185. //Encoding that let us read all bytes without replacing any char
  186. //It is using to read output of commands, which may consist of:
  187. //1) commit header (message, author, ...) encoded in CommitEncoding, recoded to LogOutputEncoding or not dependent of
  188. // pretty parameter (pretty=raw - recoded, pretty=format - not recoded)
  189. //2) file content encoded in its original encoding
  190. //3) file path (file name is encoded in system default encoding),
  191. // when core.quotepath is on, every non ASCII character is escaped
  192. // with \ followed by its code as a three digit octal number
  193. //4) branch, tag name, errors, warnings, hints encoded in system default encoding
  194. public static readonly Encoding LosslessEncoding = Encoding.GetEncoding("ISO-8859-1");//is any better?
  195. public Encoding FilesEncoding
  196. {
  197. get
  198. {
  199. Encoding result = EffectiveConfigFile.FilesEncoding;
  200. if (result == null)
  201. result = new UTF8Encoding(false);
  202. return result;
  203. }
  204. }
  205. public Encoding CommitEncoding
  206. {
  207. get
  208. {
  209. Encoding result = EffectiveConfigFile.CommitEncoding;
  210. if (result == null)
  211. result = new UTF8Encoding(false);
  212. return result;
  213. }
  214. }
  215. /// <summary>
  216. /// Encoding for commit header (message, notes, author, commiter, emails)
  217. /// </summary>
  218. public Encoding LogOutputEncoding
  219. {
  220. get
  221. {
  222. Encoding result = EffectiveConfigFile.LogOutputEncoding;
  223. if (result == null)
  224. result = CommitEncoding;
  225. return result;
  226. }
  227. }
  228. /// <summary>"(no branch)"</summary>
  229. public static readonly string DetachedBranch = "(no branch)";
  230. private static readonly string[] DetachedPrefixes = { "(no branch", "(detached from " };
  231. public AppSettings.PullAction LastPullAction
  232. {
  233. get { return AppSettings.GetEnum("LastPullAction_" + WorkingDir, AppSettings.PullAction.None); }
  234. set { AppSettings.SetEnum("LastPullAction_" + WorkingDir, value); }
  235. }
  236. public void LastPullActionToFormPullAction()
  237. {
  238. if (LastPullAction == AppSettings.PullAction.FetchAll)
  239. AppSettings.FormPullAction = AppSettings.PullAction.Fetch;
  240. else if (LastPullAction != AppSettings.PullAction.None)
  241. AppSettings.FormPullAction = LastPullAction;
  242. }
  243. /// <summary>Indicates whether the <see cref="WorkingDir"/> contains a git repository.</summary>
  244. public bool IsValidGitWorkingDir()
  245. {
  246. return IsValidGitWorkingDir(_workingDir);
  247. }
  248. /// <summary>Indicates whether the specified directory contains a git repository.</summary>
  249. public static bool IsValidGitWorkingDir(string dir)
  250. {
  251. if (string.IsNullOrEmpty(dir))
  252. return false;
  253. string dirPath = dir.EnsureTrailingPathSeparator();
  254. string path = dirPath + ".git";
  255. if (Directory.Exists(path) || File.Exists(path))
  256. return true;
  257. return Directory.Exists(dirPath + "info") &&
  258. Directory.Exists(dirPath + "objects") &&
  259. Directory.Exists(dirPath + "refs");
  260. }
  261. /// <summary>Gets the ".git" directory path.</summary>
  262. public string GetGitDirectory()
  263. {
  264. return GetGitDirectory(_workingDir);
  265. }
  266. public static string GetGitDirectory(string repositoryPath)
  267. {
  268. var gitpath = Path.Combine(repositoryPath, ".git");
  269. if (File.Exists(gitpath))
  270. {
  271. var lines = File.ReadLines(gitpath);
  272. foreach (string line in lines)
  273. {
  274. if (line.StartsWith("gitdir:"))
  275. {
  276. string path = line.Substring(7).Trim().Replace('/', '\\');
  277. if (Path.IsPathRooted(path))
  278. return path.EnsureTrailingPathSeparator();
  279. else
  280. return
  281. Path.GetFullPath(Path.Combine(repositoryPath,
  282. path.EnsureTrailingPathSeparator()));
  283. }
  284. }
  285. }
  286. gitpath = gitpath.EnsureTrailingPathSeparator();
  287. if (!Directory.Exists(gitpath))
  288. return repositoryPath;
  289. return gitpath;
  290. }
  291. public bool IsBareRepository()
  292. {
  293. return WorkingDir == GetGitDirectory();
  294. }
  295. public static bool IsBareRepository(string repositoryPath)
  296. {
  297. return repositoryPath == GetGitDirectory(repositoryPath);
  298. }
  299. public bool HasSubmodules()
  300. {
  301. return GetSubmodulesLocalPathes(recursive: false).Any();
  302. }
  303. /// <summary>
  304. /// This is a faster function to get the names of all submodules then the
  305. /// GetSubmodules() function. The command @git submodule is very slow.
  306. /// </summary>
  307. public IList<string> GetSubmodulesLocalPathes(bool recursive = true)
  308. {
  309. var configFile = GetSubmoduleConfigFile();
  310. var submodules = configFile.ConfigSections.Select(configSection => configSection.GetPathValue("path").Trim()).ToList();
  311. if (recursive)
  312. {
  313. for (int i = 0; i < submodules.Count; i++)
  314. {
  315. var submodule = GetSubmodule(submodules[i]);
  316. var submoduleConfigFile = submodule.GetSubmoduleConfigFile();
  317. var subsubmodules = submoduleConfigFile.ConfigSections.Select(configSection => configSection.GetPathValue("path").Trim()).ToList();
  318. for (int j = 0; j < subsubmodules.Count; j++)
  319. subsubmodules[j] = submodules[i] + '/' + subsubmodules[j];
  320. submodules.InsertRange(i + 1, subsubmodules);
  321. i += subsubmodules.Count;
  322. }
  323. }
  324. return submodules;
  325. }
  326. public static string FindGitWorkingDir(string startDir)
  327. {
  328. if (string.IsNullOrEmpty(startDir))
  329. return "";
  330. var dir = startDir.Trim();
  331. do
  332. {
  333. if (IsValidGitWorkingDir(dir))
  334. return dir.EnsureTrailingPathSeparator();
  335. dir = PathUtil.GetDirectoryName(dir);
  336. }
  337. while (!string.IsNullOrEmpty(dir));
  338. return startDir;
  339. }
  340. private static Process StartProccess(string fileName, string arguments, string workingDir, bool showConsole)
  341. {
  342. GitCommandHelpers.SetEnvironmentVariable();
  343. string quotedCmd = fileName;
  344. if (quotedCmd.IndexOf(' ') != -1)
  345. quotedCmd = quotedCmd.Quote();
  346. AppSettings.GitLog.Log(quotedCmd + " " + arguments);
  347. var startInfo = new ProcessStartInfo
  348. {
  349. FileName = fileName,
  350. Arguments = arguments,
  351. WorkingDirectory = workingDir
  352. };
  353. if (!showConsole)
  354. {
  355. startInfo.UseShellExecute = false;
  356. startInfo.CreateNoWindow = true;
  357. }
  358. return Process.Start(startInfo);
  359. }
  360. /// <summary>
  361. /// Run command, console window is visible
  362. /// </summary>
  363. public Process RunExternalCmdDetachedShowConsole(string cmd, string arguments)
  364. {
  365. try
  366. {
  367. return StartProccess(cmd, arguments, _workingDir, showConsole: true);
  368. }
  369. catch (Exception ex)
  370. {
  371. Trace.WriteLine(ex.Message);
  372. }
  373. return null;
  374. }
  375. /// <summary>
  376. /// Run command, console window is visible, wait for exit
  377. /// </summary>
  378. public void RunExternalCmdShowConsole(string cmd, string arguments)
  379. {
  380. try
  381. {
  382. using (var process = StartProccess(cmd, arguments, _workingDir, showConsole: true))
  383. process.WaitForExit();
  384. }
  385. catch (Exception ex)
  386. {
  387. Trace.WriteLine(ex.Message);
  388. }
  389. }
  390. /// <summary>
  391. /// Run command, console window is hidden
  392. /// </summary>
  393. public static Process RunExternalCmdDetached(string fileName, string arguments, string workingDir)
  394. {
  395. try
  396. {
  397. return StartProccess(fileName, arguments, workingDir, showConsole: false);
  398. }
  399. catch (Exception ex)
  400. {
  401. Trace.WriteLine(ex.Message);
  402. }
  403. return null;
  404. }
  405. /// <summary>
  406. /// Run command, console window is hidden
  407. /// </summary>
  408. public Process RunExternalCmdDetached(string cmd, string arguments)
  409. {
  410. return RunExternalCmdDetached(cmd, arguments, _workingDir);
  411. }
  412. /// <summary>
  413. /// Run git command, console window is hidden, redirect output
  414. /// </summary>
  415. public Process RunGitCmdDetached(string arguments, Encoding encoding = null)
  416. {
  417. if (encoding == null)
  418. encoding = SystemEncoding;
  419. return GitCommandHelpers.StartProcess(AppSettings.GitCommand, arguments, _workingDir, encoding);
  420. }
  421. /// <summary>
  422. /// Run command, cache results, console window is hidden, wait for exit, redirect output
  423. /// </summary>
  424. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  425. public string RunCacheableCmd(string cmd, string arguments = "", Encoding encoding = null)
  426. {
  427. if (encoding == null)
  428. encoding = SystemEncoding;
  429. byte[] cmdout, cmderr;
  430. if (GitCommandCache.TryGet(arguments, out cmdout, out cmderr))
  431. return EncodingHelper.DecodeString(cmdout, cmderr, ref encoding);
  432. GitCommandHelpers.RunCmdByte(cmd, arguments, _workingDir, null, out cmdout, out cmderr);
  433. GitCommandCache.Add(arguments, cmdout, cmderr);
  434. return EncodingHelper.DecodeString(cmdout, cmderr, ref encoding);
  435. }
  436. /// <summary>
  437. /// Run command, console window is hidden, wait for exit, redirect output
  438. /// </summary>
  439. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  440. public CmdResult RunCmdResult(string cmd, string arguments, Encoding encoding = null, byte[] stdInput = null)
  441. {
  442. byte[] output, error;
  443. int exitCode = GitCommandHelpers.RunCmdByte(cmd, arguments, _workingDir, stdInput, out output, out error);
  444. if (encoding == null)
  445. encoding = SystemEncoding;
  446. return new CmdResult
  447. {
  448. StdOutput = output == null ? string.Empty : encoding.GetString(output),
  449. StdError = error == null ? string.Empty : encoding.GetString(error),
  450. ExitCode = exitCode
  451. };
  452. }
  453. /// <summary>
  454. /// Run command, console window is hidden, wait for exit, redirect output
  455. /// </summary>
  456. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  457. public string RunCmd(string cmd, string arguments, Encoding encoding = null, byte[] stdInput = null)
  458. {
  459. return RunCmdResult(cmd, arguments, encoding, stdInput).GetString();
  460. }
  461. /// <summary>
  462. /// Run git command, console window is hidden, wait for exit, redirect output
  463. /// </summary>
  464. public string RunGitCmd(string arguments, Encoding encoding = null, byte[] stdInput = null)
  465. {
  466. return RunCmd(AppSettings.GitCommand, arguments, encoding, stdInput);
  467. }
  468. /// <summary>
  469. /// Run git command, console window is hidden, wait for exit, redirect output
  470. /// </summary>
  471. public CmdResult RunGitCmdResult(string arguments, Encoding encoding = null, byte[] stdInput = null)
  472. {
  473. return RunCmdResult(AppSettings.GitCommand, arguments, encoding, stdInput);
  474. }
  475. /// <summary>
  476. /// Run command, console window is hidden, wait for exit, redirect output
  477. /// </summary>
  478. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  479. private IEnumerable<string> ReadCmdOutputLines(string cmd, string arguments, string stdInput)
  480. {
  481. return GitCommandHelpers.ReadCmdOutputLines(cmd, arguments, _workingDir, stdInput);
  482. }
  483. /// <summary>
  484. /// Run git command, console window is hidden, wait for exit, redirect output
  485. /// </summary>
  486. public IEnumerable<string> ReadGitOutputLines(string arguments)
  487. {
  488. return ReadCmdOutputLines(AppSettings.GitCommand, arguments, null);
  489. }
  490. /// <summary>
  491. /// Run batch file, console window is hidden, wait for exit, redirect output
  492. /// </summary>
  493. public string RunBatchFile(string batchFile)
  494. {
  495. string tempFileName = Path.ChangeExtension(Path.GetTempFileName(), ".cmd");
  496. using (var writer = new StreamWriter(tempFileName))
  497. {
  498. writer.WriteLine("@prompt $G");
  499. writer.Write(batchFile);
  500. }
  501. string result = RunCmd("cmd.exe", "/C \"" + tempFileName + "\"");
  502. File.Delete(tempFileName);
  503. return result;
  504. }
  505. public void EditNotes(string revision)
  506. {
  507. string editor = GetEffectivePathSetting("core.editor").ToLower();
  508. if (editor.Contains("gitextensions") || editor.Contains("notepad") ||
  509. editor.Contains("notepad++"))
  510. {
  511. RunGitCmd("notes edit " + revision);
  512. }
  513. else
  514. {
  515. RunExternalCmdShowConsole(AppSettings.GitCommand, "notes edit " + revision);
  516. }
  517. }
  518. public bool InTheMiddleOfConflictedMerge()
  519. {
  520. return !string.IsNullOrEmpty(RunGitCmd("ls-files -z --unmerged"));
  521. }
  522. public IList<GitItem> GetConflictedFiles()
  523. {
  524. var unmergedFiles = new List<GitItem>();
  525. var fileName = "";
  526. foreach (var file in GetUnmergedFileListing())
  527. {
  528. if (file.IndexOf('\t') <= 0)
  529. continue;
  530. if (file.Substring(file.IndexOf('\t') + 1) == fileName)
  531. continue;
  532. fileName = file.Substring(file.IndexOf('\t') + 1);
  533. unmergedFiles.Add(new GitItem(this) { FileName = fileName });
  534. }
  535. return unmergedFiles;
  536. }
  537. private IEnumerable<string> GetUnmergedFileListing()
  538. {
  539. return RunGitCmd("ls-files -z --unmerged").Split(new[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  540. }
  541. public bool HandleConflictSelectSide(string fileName, string side)
  542. {
  543. Directory.SetCurrentDirectory(_workingDir);
  544. fileName = fileName.ToPosixPath();
  545. side = GetSide(side);
  546. string result = RunGitCmd(String.Format("checkout-index -f --stage={0} -- \"{1}\"", side, fileName));
  547. if (!result.IsNullOrEmpty())
  548. {
  549. return false;
  550. }
  551. result = RunGitCmd(String.Format("add -- \"{0}\"", fileName));
  552. return result.IsNullOrEmpty();
  553. }
  554. public bool HandleConflictsSaveSide(string fileName, string saveAsFileName, string side)
  555. {
  556. Directory.SetCurrentDirectory(_workingDir);
  557. fileName = fileName.ToPosixPath();
  558. side = GetSide(side);
  559. var result = RunGitCmd(String.Format("checkout-index --stage={0} --temp -- \"{1}\"", side, fileName));
  560. if (result.IsNullOrEmpty())
  561. {
  562. return false;
  563. }
  564. if (!result.StartsWith(".merge_file_"))
  565. {
  566. return false;
  567. }
  568. // Parse temporary file name from command line result
  569. var splitResult = result.Split(new[] { "\t", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
  570. if (splitResult.Length != 2)
  571. {
  572. return false;
  573. }
  574. var temporaryFileName = splitResult[0].Trim();
  575. if (!File.Exists(temporaryFileName))
  576. {
  577. return false;
  578. }
  579. var retValue = false;
  580. try
  581. {
  582. if (File.Exists(saveAsFileName))
  583. {
  584. File.Delete(saveAsFileName);
  585. }
  586. File.Move(temporaryFileName, saveAsFileName);
  587. retValue = true;
  588. }
  589. catch
  590. {
  591. }
  592. finally
  593. {
  594. if (File.Exists(temporaryFileName))
  595. {
  596. File.Delete(temporaryFileName);
  597. }
  598. }
  599. return retValue;
  600. }
  601. public void SaveBlobAs(string saveAs, string blob)
  602. {
  603. using (var ms = (MemoryStream)GetFileStream(blob)) //Ugly, has implementation info.
  604. {
  605. byte[] buf = ms.ToArray();
  606. if (EffectiveConfigFile.core.autocrlf.Value == AutoCRLFType.True)
  607. {
  608. if (!FileHelper.IsBinaryFile(this, saveAs) && !FileHelper.IsBinaryFileAccordingToContent(buf))
  609. {
  610. buf = GitConvert.ConvertCrLfToWorktree(buf);
  611. }
  612. }
  613. using (FileStream fileOut = File.Create(saveAs))
  614. {
  615. fileOut.Write(buf, 0, buf.Length);
  616. }
  617. }
  618. }
  619. private static string GetSide(string side)
  620. {
  621. if (side.Equals("REMOTE", StringComparison.CurrentCultureIgnoreCase))
  622. side = "3";
  623. if (side.Equals("LOCAL", StringComparison.CurrentCultureIgnoreCase))
  624. side = "2";
  625. if (side.Equals("BASE", StringComparison.CurrentCultureIgnoreCase))
  626. side = "1";
  627. return side;
  628. }
  629. public string[] GetConflictedFiles(string filename)
  630. {
  631. Directory.SetCurrentDirectory(_workingDir);
  632. filename = filename.ToPosixPath();
  633. string[] fileNames =
  634. {
  635. filename + ".BASE",
  636. filename + ".LOCAL",
  637. filename + ".REMOTE"
  638. };
  639. var unmerged = RunGitCmd("ls-files -z --unmerged \"" + filename + "\"").Split(new char[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  640. foreach (var file in unmerged)
  641. {
  642. string fileStage = null;
  643. int findSecondWhitespace = file.IndexOfAny(new[] { ' ', '\t' });
  644. if (findSecondWhitespace >= 0) fileStage = file.Substring(findSecondWhitespace).Trim();
  645. findSecondWhitespace = fileStage.IndexOfAny(new[] { ' ', '\t' });
  646. if (findSecondWhitespace >= 0) fileStage = fileStage.Substring(findSecondWhitespace).Trim();
  647. if (string.IsNullOrEmpty(fileStage))
  648. continue;
  649. int stage;
  650. if (!Int32.TryParse(fileStage.Trim()[0].ToString(), out stage))
  651. continue;
  652. var tempFile = RunGitCmd("checkout-index --temp --stage=" + stage + " -- " + "\"" + filename + "\"");
  653. tempFile = tempFile.Split('\t')[0];
  654. tempFile = Path.Combine(_workingDir, tempFile);
  655. var newFileName = Path.Combine(_workingDir, fileNames[stage - 1]);
  656. try
  657. {
  658. fileNames[stage - 1] = newFileName;
  659. var index = 1;
  660. while (File.Exists(fileNames[stage - 1]) && index < 50)
  661. {
  662. fileNames[stage - 1] = newFileName + index;
  663. index++;
  664. }
  665. File.Move(tempFile, fileNames[stage - 1]);
  666. }
  667. catch (Exception ex)
  668. {
  669. Trace.WriteLine(ex);
  670. }
  671. }
  672. if (!File.Exists(fileNames[0])) fileNames[0] = null;
  673. if (!File.Exists(fileNames[1])) fileNames[1] = null;
  674. if (!File.Exists(fileNames[2])) fileNames[2] = null;
  675. return fileNames;
  676. }
  677. public string[] GetConflictedFileNames(string filename)
  678. {
  679. filename = filename.ToPosixPath();
  680. var fileNames = new string[3];
  681. var unmerged = RunGitCmd("ls-files -z --unmerged \"" + filename + "\"").Split(new[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  682. foreach (var line in unmerged)
  683. {
  684. int findSecondWhitespace = line.IndexOfAny(new[] { ' ', '\t' });
  685. string fileStage = findSecondWhitespace >= 0 ? line.Substring(findSecondWhitespace).Trim() : "";
  686. findSecondWhitespace = fileStage.IndexOfAny(new[] { ' ', '\t' });
  687. fileStage = findSecondWhitespace >= 0 ? fileStage.Substring(findSecondWhitespace).Trim() : "";
  688. int stage;
  689. if (fileStage.Length > 2 && Int32.TryParse(fileStage[0].ToString(), out stage) && stage >= 1 && stage <= 3)
  690. {
  691. fileNames[stage - 1] = fileStage.Substring(2);
  692. }
  693. }
  694. return fileNames;
  695. }
  696. public string[] GetConflictedSubmoduleHashes(string filename)
  697. {
  698. filename = filename.ToPosixPath();
  699. var hashes = new string[3];
  700. var unmerged = RunGitCmd("ls-files -z --unmerged \"" + filename + "\"").Split(new[] { '\0', '\n' }, StringSplitOptions.RemoveEmptyEntries);
  701. foreach (var line in unmerged)
  702. {
  703. int findSecondWhitespace = line.IndexOfAny(new[] { ' ', '\t' });
  704. string fileStage = findSecondWhitespace >= 0 ? line.Substring(findSecondWhitespace).Trim() : "";
  705. findSecondWhitespace = fileStage.IndexOfAny(new[] { ' ', '\t' });
  706. string hash = findSecondWhitespace >= 0 ? fileStage.Substring(0, findSecondWhitespace).Trim() : "";
  707. fileStage = findSecondWhitespace >= 0 ? fileStage.Substring(findSecondWhitespace).Trim() : "";
  708. int stage;
  709. if (fileStage.Length > 2 && Int32.TryParse(fileStage[0].ToString(), out stage) && stage >= 1 && stage <= 3)
  710. {
  711. hashes[stage - 1] = hash;
  712. }
  713. }
  714. return hashes;
  715. }
  716. public Dictionary<GitRef, GitItem> GetSubmoduleItemsForEachRef(string filename, Func<GitRef, bool> showRemoteRef)
  717. {
  718. string command = GetShowRefCommand();
  719. if (command == null)
  720. return new Dictionary<GitRef, GitItem>();
  721. filename = filename.ToPosixPath();
  722. var tree = RunGitCmd(command, SystemEncoding);
  723. var refs = GetTreeRefs(tree);
  724. return refs.Where(showRemoteRef).ToDictionary(r => r, r => GetSubmoduleGuid(filename, r.Name));
  725. }
  726. private string GetShowRefCommand()
  727. {
  728. if (AppSettings.ShowSuperprojectRemoteBranches)
  729. return "show-ref --dereference";
  730. if (AppSettings.ShowSuperprojectBranches || AppSettings.ShowSuperprojectTags)
  731. return "show-ref --dereference"
  732. + (AppSettings.ShowSuperprojectBranches ? " --heads" : null)
  733. + (AppSettings.ShowSuperprojectTags ? " --tags" : null);
  734. return null;
  735. }
  736. private GitItem GetSubmoduleGuid(string filename, string refName)
  737. {
  738. string str = RunGitCmd("ls-tree " + refName + " \"" + filename + "\"");
  739. return GitItem.CreateGitItemFromString(this, str);
  740. }
  741. public int? GetCommitCount(string parentHash, string childHash)
  742. {
  743. string result = RunGitCmd("rev-list " + parentHash + " ^" + childHash + " --count");
  744. int commitCount;
  745. if (int.TryParse(result, out commitCount))
  746. return commitCount;
  747. return null;
  748. }
  749. public string GetCommitCountString(string from, string to)
  750. {
  751. int? removed = GetCommitCount(from, to);
  752. int? added = GetCommitCount(to, from);
  753. if (removed == null || added == null)
  754. return "";
  755. if (removed == 0 && added == 0)
  756. return "=";
  757. return
  758. (removed > 0 ? ("-" + removed) : "") +
  759. (added > 0 ? ("+" + added) : "");
  760. }
  761. public string GetMergeMessage()
  762. {
  763. var file = GetGitDirectory() + "MERGE_MSG";
  764. return
  765. File.Exists(file)
  766. ? File.ReadAllText(file)
  767. : "";
  768. }
  769. public void RunGitK()
  770. {
  771. if (EnvUtils.RunningOnUnix())
  772. {
  773. RunExternalCmdDetachedShowConsole("gitk", "");
  774. }
  775. else
  776. {
  777. RunExternalCmdDetached("cmd.exe", "/c \"\"" + AppSettings.GitCommand.Replace("git.cmd", "gitk.cmd")
  778. .Replace("bin\\git.exe", "cmd\\gitk.cmd")
  779. .Replace("bin/git.exe", "cmd/gitk.cmd") + "\" --branches --tags --remotes\"");
  780. }
  781. }
  782. public void RunGui()
  783. {
  784. if (EnvUtils.RunningOnUnix())
  785. {
  786. RunExternalCmdDetachedShowConsole(AppSettings.GitCommand, "gui");
  787. }
  788. else
  789. {
  790. RunExternalCmdDetached("cmd.exe", "/c \"\"" + AppSettings.GitCommand + "\" gui\"");
  791. }
  792. }
  793. /// <summary>Runs a bash or shell command.</summary>
  794. public Process RunBash(string bashCommand = null)
  795. {
  796. if (EnvUtils.RunningOnUnix())
  797. {
  798. string[] termEmuCmds =
  799. {
  800. "gnome-terminal",
  801. "konsole",
  802. "Terminal",
  803. "xterm"
  804. };
  805. string args = "";
  806. string cmd = termEmuCmds.FirstOrDefault(termEmuCmd => !string.IsNullOrEmpty(RunCmd("which", termEmuCmd)));
  807. if (string.IsNullOrEmpty(cmd))
  808. {
  809. cmd = "bash";
  810. args = "--login -i";
  811. }
  812. return RunExternalCmdDetachedShowConsole(cmd, args);
  813. }
  814. else
  815. {
  816. string args;
  817. if (string.IsNullOrWhiteSpace(bashCommand))
  818. {
  819. args = "--login -i\"";
  820. }
  821. else
  822. {
  823. args = "--login -i -c \"" + bashCommand.Replace("\"", "\\\"") + "\"";
  824. }
  825. string termCmd = File.Exists(AppSettings.GitBinDir + "bash.exe") ? "bash" : "sh";
  826. return RunExternalCmdDetachedShowConsole("cmd.exe",
  827. string.Format("/c \"\"{0}{1}\" {2}", AppSettings.GitBinDir, termCmd, args));
  828. }
  829. }
  830. public string Init(bool bare, bool shared)
  831. {
  832. return RunGitCmd(Smart.Format("init{0: --bare|}{1: --shared=all|}", bare, shared));
  833. }
  834. public bool IsMerge(string commit)
  835. {
  836. string[] parents = GetParents(commit);
  837. return parents.Length > 1;
  838. }
  839. private static string ProccessDiffNotes(int startIndex, string[] lines)
  840. {
  841. int endIndex = lines.Length - 1;
  842. if (lines[endIndex] == "Notes:")
  843. endIndex--;
  844. var message = new StringBuilder();
  845. bool bNotesStart = false;
  846. for (int i = startIndex; i <= endIndex; i++)
  847. {
  848. string line = lines[i];
  849. if (bNotesStart)
  850. line = " " + line;
  851. message.AppendLine(line);
  852. if (lines[i] == "Notes:")
  853. bNotesStart = true;
  854. }
  855. return message.ToString();
  856. }
  857. public GitRevision GetRevision(string commit, bool shortFormat = false)
  858. {
  859. const string formatString =
  860. /* Hash */ "%H%n" +
  861. /* Tree */ "%T%n" +
  862. /* Parents */ "%P%n" +
  863. /* Author Name */ "%aN%n" +
  864. /* Author EMail */ "%aE%n" +
  865. /* Author Date */ "%at%n" +
  866. /* Committer Name */ "%cN%n" +
  867. /* Committer EMail*/ "%cE%n" +
  868. /* Committer Date */ "%ct%n";
  869. const string messageFormat = "%e%n%B%nNotes:%n%-N";
  870. string cmd = "log -n1 --format=format:" + formatString + (shortFormat ? "%e%n%s" : messageFormat) + " " + commit;
  871. var revInfo = RunCacheableCmd(AppSettings.GitCommand, cmd, LosslessEncoding);
  872. string[] lines = revInfo.Split('\n');
  873. var revision = new GitRevision(this, lines[0])
  874. {
  875. TreeGuid = lines[1],
  876. ParentGuids = lines[2].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries),
  877. Author = ReEncodeStringFromLossless(lines[3]),
  878. AuthorEmail = ReEncodeStringFromLossless(lines[4]),
  879. Committer = ReEncodeStringFromLossless(lines[6]),
  880. CommitterEmail = ReEncodeStringFromLossless(lines[7])
  881. };
  882. revision.AuthorDate = DateTimeUtils.ParseUnixTime(lines[5]);
  883. revision.CommitDate = DateTimeUtils.ParseUnixTime(lines[8]);
  884. revision.MessageEncoding = lines[9];
  885. if (shortFormat)
  886. {
  887. revision.Message = ReEncodeCommitMessage(lines[10], revision.MessageEncoding);
  888. }
  889. else
  890. {
  891. string message = ProccessDiffNotes(10, lines);
  892. //commit message is not reencoded by git when format is given
  893. revision.Body = ReEncodeCommitMessage(message, revision.MessageEncoding);
  894. revision.Message = revision.Body.Substring(0, revision.Body.IndexOfAny(new[] { '\r', '\n' }));
  895. }
  896. return revision;
  897. }
  898. public string[] GetParents(string commit)
  899. {
  900. string output = RunGitCmd("log -n 1 --format=format:%P \"" + commit + "\"");
  901. return output.Split(' ');
  902. }
  903. public GitRevision[] GetParentsRevisions(string commit)
  904. {
  905. string[] parents = GetParents(commit);
  906. var parentsRevisions = new GitRevision[parents.Length];
  907. for (int i = 0; i < parents.Length; i++)
  908. parentsRevisions[i] = GetRevision(parents[i], true);
  909. return parentsRevisions;
  910. }
  911. public string ShowSha1(string sha1)
  912. {
  913. return ReEncodeShowString(RunCacheableCmd(AppSettings.GitCommand, "show " + sha1, LosslessEncoding));
  914. }
  915. public string DeleteTag(string tagName)
  916. {
  917. return RunGitCmd(GitCommandHelpers.DeleteTagCmd(tagName));
  918. }
  919. public string GetCurrentCheckout()
  920. {
  921. return RunGitCmd("rev-parse HEAD").TrimEnd();
  922. }
  923. public KeyValuePair<char, string> GetSuperprojectCurrentCheckout()
  924. {
  925. if (SuperprojectModule == null)
  926. return new KeyValuePair<char, string>(' ', "");
  927. var lines = SuperprojectModule.RunGitCmd("submodule status --cached " + _submodulePath).Split('\n');
  928. if (lines.Length == 0)
  929. return new KeyValuePair<char, string>(' ', "");
  930. string submodule = lines[0];
  931. if (submodule.Length < 43)
  932. return new KeyValuePair<char, string>(' ', "");
  933. var currentCommitGuid = submodule.Substring(1, 40).Trim();
  934. return new KeyValuePair<char, string>(submodule[0], currentCommitGuid);
  935. }
  936. public bool ExistsMergeCommit(string startRev, string endRev)
  937. {
  938. if (startRev.IsNullOrEmpty() || endRev.IsNullOrEmpty())
  939. return false;
  940. string revisions = RunGitCmd("rev-list --parents --no-walk " + startRev + ".." + endRev);
  941. string[] revisionsTab = revisions.Split('\n');
  942. Func<string, bool> ex = (string parents) =>
  943. {
  944. string[] tab = parents.Split(' ');
  945. return tab.Length > 2 && tab.All(parent => GitRevision.Sha1HashRegex.IsMatch(parent));
  946. };
  947. return revisionsTab.Any(ex);
  948. }
  949. public ConfigFile GetSubmoduleConfigFile()
  950. {
  951. return new ConfigFile(_workingDir + ".gitmodules", true);
  952. }
  953. public string GetCurrentSubmoduleLocalPath()
  954. {
  955. if (SuperprojectModule == null)
  956. return null;
  957. string submodulePath = WorkingDir.Substring(SuperprojectModule.WorkingDir.Length);
  958. submodulePath = PathUtil.GetDirectoryName(submodulePath.ToPosixPath());
  959. return submodulePath;
  960. }
  961. public string GetSubmoduleNameByPath(string localPath)
  962. {
  963. var configFile = GetSubmoduleConfigFile();
  964. var submodule = configFile.ConfigSections.FirstOrDefault(configSection => configSection.GetPathValue("path").Trim() == localPath);
  965. if (submodule != null)
  966. return submodule.SubSection.Trim();
  967. return null;
  968. }
  969. public string GetSubmoduleRemotePath(string name)
  970. {
  971. var configFile = GetSubmoduleConfigFile();
  972. return configFile.GetPathValue(string.Format("submodule.{0}.url", name)).Trim();
  973. }
  974. public string GetSubmoduleFullPath(string localPath)
  975. {
  976. string dir = Path.Combine(_workingDir, localPath.EnsureTrailingPathSeparator());
  977. return Path.GetFullPath(dir); // fix slashes
  978. }
  979. public GitModule GetSubmodule(string localPath)
  980. {
  981. return new GitModule(GetSubmoduleFullPath(localPath));
  982. }
  983. IGitModule IGitModule.GetSubmodule(string submoduleName)
  984. {
  985. return GetSubmodule(submoduleName);
  986. }
  987. private GitSubmoduleInfo GetSubmoduleInfo(string submodule)
  988. {
  989. var gitSubmodule =
  990. new GitSubmoduleInfo(this)
  991. {
  992. Initialized = submodule[0] != '-',
  993. UpToDate = submodule[0] != '+',
  994. CurrentCommitGuid = submodule.Substring(1, 40).Trim()
  995. };
  996. var localPath = submodule.Substring(42).Trim();
  997. if (localPath.Contains("("))
  998. {
  999. gitSubmodule.LocalPath = localPath.Substring(0, localPath.IndexOf("(")).TrimEnd();
  1000. gitSubmodule.Branch = localPath.Substring(localPath.IndexOf("(")).Trim(new[] { '(', ')', ' ' });
  1001. }
  1002. else
  1003. gitSubmodule.LocalPath = localPath;
  1004. return gitSubmodule;
  1005. }
  1006. public IEnumerable<IGitSubmoduleInfo> GetSubmodulesInfo()
  1007. {
  1008. var submodules = ReadGitOutputLines("submodule status");
  1009. string lastLine = null;
  1010. foreach (var submodule in submodules)
  1011. {
  1012. if (submodule.Length < 43)
  1013. continue;
  1014. if (submodule.Equals(lastLine))
  1015. continue;
  1016. lastLine = submodule;
  1017. yield return GetSubmoduleInfo(submodule);
  1018. }
  1019. }
  1020. public string FindGitSuperprojectPath(out string submoduleName, out string submodulePath)
  1021. {
  1022. submoduleName = null;
  1023. submodulePath = null;
  1024. if (!IsValidGitWorkingDir())
  1025. return null;
  1026. string superprojectPath = null;
  1027. string currentPath = Path.GetDirectoryName(_workingDir); // remove last slash
  1028. if (!string.IsNullOrEmpty(currentPath))
  1029. {
  1030. string path = Path.GetDirectoryName(currentPath);
  1031. for (int i = 0; i < 5; i++)
  1032. {
  1033. if (string.IsNullOrEmpty(path))
  1034. break;
  1035. if (File.Exists(Path.Combine(path, ".gitmodules")) &&
  1036. IsValidGitWorkingDir(path))
  1037. {
  1038. superprojectPath = path.EnsureTrailingPathSeparator();
  1039. break;
  1040. }
  1041. // Check upper directory
  1042. path = Path.GetDirectoryName(path);
  1043. }
  1044. }
  1045. if (File.Exists(_workingDir + ".git") &&
  1046. superprojectPath == null)
  1047. {
  1048. var lines = File.ReadLines(_workingDir + ".git");
  1049. foreach (string line in lines)
  1050. {
  1051. if (line.StartsWith("gitdir:"))
  1052. {
  1053. string gitpath = line.Substring(7).Trim();
  1054. int pos = gitpath.IndexOf("/.git/");
  1055. if (pos != -1)
  1056. {
  1057. gitpath = gitpath.Substring(0, pos + 1).Replace('/', '\\');
  1058. gitpath = Path.GetFullPath(Path.Combine(_workingDir, gitpath));
  1059. if (File.Exists(gitpath + ".gitmodules") && IsValidGitWorkingDir(gitpath))
  1060. superprojectPath = gitpath;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. if (!string.IsNullOrEmpty(superprojectPath))
  1066. {
  1067. submodulePath = currentPath.Substring(superprojectPath.Length).ToPosixPath();
  1068. var configFile = new ConfigFile(superprojectPath + ".gitmodules", true);
  1069. foreach (ConfigSection configSection in configFile.ConfigSections)
  1070. {
  1071. if (configSection.GetPathValue("path") == submodulePath.ToPosixPath())
  1072. {
  1073. submoduleName = configSection.SubSection;
  1074. return superprojectPath;
  1075. }
  1076. }
  1077. }
  1078. return null;
  1079. }
  1080. public string GetSubmoduleSummary(string submodule)
  1081. {
  1082. var arguments = string.Format("submodule summary {0}", submodule);
  1083. return RunGitCmd(arguments);
  1084. }
  1085. public string ResetSoft(string commit)
  1086. {
  1087. return ResetSoft(commit, "");
  1088. }
  1089. public string ResetMixed(string commit)
  1090. {
  1091. return ResetMixed(commit, "");
  1092. }
  1093. public string ResetHard(string commit)
  1094. {
  1095. return ResetHard(commit, "");
  1096. }
  1097. public string ResetSoft(string commit, string file)
  1098. {
  1099. var args = "reset --soft";
  1100. if (!string.IsNullOrEmpty(commit))
  1101. args += " \"" + commit + "\"";
  1102. if (!string.IsNullOrEmpty(file))
  1103. args += " -- \"" + file + "\"";
  1104. return RunGitCmd(args);
  1105. }
  1106. public string ResetMixed(string commit, string file)
  1107. {
  1108. var args = "reset --mixed";
  1109. if (!string.IsNullOrEmpty(commit))
  1110. args += " \"" + commit + "\"";
  1111. if (!string.IsNullOrEmpty(file))
  1112. args += " -- \"" + file + "\"";
  1113. return RunGitCmd(args);
  1114. }
  1115. public string ResetHard(string commit, string file)
  1116. {
  1117. var args = "reset --hard";
  1118. if (!string.IsNullOrEmpty(commit))
  1119. args += " \"" + commit + "\"";
  1120. if (!string.IsNullOrEmpty(file))
  1121. args += " -- \"" + file + "\"";
  1122. return RunGitCmd(args);
  1123. }
  1124. public string ResetFile(string file)
  1125. {
  1126. file = file.ToPosixPath();
  1127. return RunGitCmd("checkout-index --index --force -- \"" + file + "\"");
  1128. }
  1129. public string FormatPatch(string from, string to, string output, int start)
  1130. {
  1131. output = output.ToPosixPath();
  1132. var result = RunGitCmd("format-patch -M -C -B --start-number " + start + " \"" + from + "\"..\"" + to +
  1133. "\" -o \"" + output + "\"");
  1134. return result;
  1135. }
  1136. public string FormatPatch(string from, string to, string output)
  1137. {
  1138. output = output.ToPosixPath();
  1139. var result = RunGitCmd("format-patch -M -C -B \"" + from + "\"..\"" + to + "\" -o \"" + output + "\"");
  1140. return result;
  1141. }
  1142. public string Tag(string tagName, string revision, bool annotation, bool force)
  1143. {
  1144. if (annotation)
  1145. return RunGitCmd(string.Format("tag \"{0}\" -a {1} -F \"{2}\\TAGMESSAGE\" -- \"{3}\"", tagName.Trim(), (force ? "-f" : ""), GetGitDirectory(), revision));
  1146. return RunGitCmd(string.Format("tag {0} \"{1}\" \"{2}\"", (force ? "-f" : ""), tagName.Trim(), revision));
  1147. }
  1148. public string CheckoutFiles(IEnumerable<string> fileList, string revision, bool force)
  1149. {
  1150. string files = fileList.Select(s => s.Quote()).Join(" ");
  1151. return RunGitCmd("checkout " + force.AsForce() + revision.Quote() + " -- " + files);
  1152. }
  1153. /// <summary>Tries to start Pageant for the specified remote repo (using the remote's PuTTY key file).</summary>
  1154. /// <returns>true if the remote has a PuTTY key file; otherwise, false.</returns>
  1155. public bool StartPageantForRemote(string remote)
  1156. {
  1157. var sshKeyFile = GetPuttyKeyFileForRemote(remote);
  1158. if (string.IsNullOrEmpty(sshKeyFile) || !File.Exists(sshKeyFile))
  1159. return false;
  1160. StartPageantWithKey(sshKeyFile);
  1161. return true;
  1162. }
  1163. public static void StartPageantWithKey(string sshKeyFile)
  1164. {
  1165. RunExternalCmdDetached(AppSettings.Pageant, "\"" + sshKeyFile + "\"", "");
  1166. }
  1167. public string GetPuttyKeyFileForRemote(string remote)
  1168. {
  1169. if (string.IsNullOrEmpty(remote) ||
  1170. string.IsNullOrEmpty(AppSettings.Pageant) ||
  1171. !AppSettings.AutoStartPageant ||
  1172. !GitCommandHelpers.Plink())
  1173. return "";
  1174. return GetPathSetting(string.Format("remote.{0}.puttykeyfile", remote));
  1175. }
  1176. public static bool PathIsUrl(string path)
  1177. {
  1178. return path.Contains(Path.DirectorySeparatorChar) || path.Contains(AppSettings.PosixPathSeparator.ToString());
  1179. }
  1180. public string FetchCmd(string remote, string remoteBranch, string localBranch, bool? fetchTags = false)
  1181. {
  1182. var progressOption = "";
  1183. if (GitCommandHelpers.VersionInUse.FetchCanAskForProgress)
  1184. progressOption = "--progress ";
  1185. if (string.IsNullOrEmpty(remote) && string.IsNullOrEmpty(remoteBranch) && string.IsNullOrEmpty(localBranch))
  1186. return "fetch " + progressOp

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