Skip to content

Commit ef01762

Browse files
committed
enhance: applying patch
- When a patch is generated by `git format-patch` or from a mailbox, allows to create commit while applying it - Handle am-inprogress state Signed-off-by: leo <longshuang@msn.cn>
1 parent 838e900 commit ef01762

10 files changed

Lines changed: 214 additions & 12 deletions

File tree

‎src/Commands/Am.cs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System.Text;
2+
3+
namespace SourceGit.Commands
4+
{
5+
public class Am : Command
6+
{
7+
public Am(string repo, string file, bool ignoreWhitespace, string whitespaceMode, string extra)
8+
{
9+
WorkingDirectory = repo;
10+
Context = repo;
11+
12+
var builder = new StringBuilder(1024);
13+
builder.Append("am ");
14+
15+
if (ignoreWhitespace)
16+
builder.Append("--ignore-whitespace ");
17+
else
18+
builder.Append("--whitespace=").Append(whitespaceMode).Append(' ');
19+
20+
if (!string.IsNullOrEmpty(extra))
21+
builder.Append(extra).Append(' ');
22+
23+
Args = builder.Append(file.Quoted()).ToString();
24+
}
25+
}
26+
}

‎src/Resources/Locales/en_US.axaml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
<x:String x:Key="Text.App.HideOthers" xml:space="preserve">Hide Others</x:String>
2222
<x:String x:Key="Text.App.ShowAll" xml:space="preserve">Show All</x:String>
2323
<x:String x:Key="Text.Apply.3Way" xml:space="preserve">3-Way Merge</x:String>
24+
<x:String x:Key="Text.Apply.CommitChanges" xml:space="preserve">Commit changes</x:String>
25+
<x:String x:Key="Text.Apply.CommitChanges.Tip" xml:space="preserve">Use `git am` instead of `git apply`</x:String>
2426
<x:String x:Key="Text.Apply.File.Placeholder" xml:space="preserve">Select patch file to apply</x:String>
2527
<x:String x:Key="Text.Apply.IgnoreWS" xml:space="preserve">Ignore whitespace changes</x:String>
2628
<x:String x:Key="Text.Apply.Source" xml:space="preserve">Source:</x:String>
@@ -577,6 +579,7 @@
577579
<x:String x:Key="Text.Init.CommandTip" xml:space="preserve">Do you want to run `git init` command under this path?</x:String>
578580
<x:String x:Key="Text.Init.ErrorMessageTip" xml:space="preserve">Open repository failed. Reason: </x:String>
579581
<x:String x:Key="Text.Init.Path" xml:space="preserve">Path:</x:String>
582+
<x:String x:Key="Text.InProgress.Am" xml:space="preserve">Applying patches in progress</x:String>
580583
<x:String x:Key="Text.InProgress.CherryPick" xml:space="preserve">Cherry-Pick in progress.</x:String>
581584
<x:String x:Key="Text.InProgress.CherryPick.Head" xml:space="preserve">Processing commit</x:String>
582585
<x:String x:Key="Text.InProgress.Merge" xml:space="preserve">Merge in progress.</x:String>

‎src/Resources/Locales/zh_CN.axaml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
<x:String x:Key="Text.App.HideOthers" xml:space="preserve">隐藏其他</x:String>
2626
<x:String x:Key="Text.App.ShowAll" xml:space="preserve">显示全部</x:String>
2727
<x:String x:Key="Text.Apply.3Way" xml:space="preserve">尝试三路合并</x:String>
28+
<x:String x:Key="Text.Apply.CommitChanges" xml:space="preserve">应用并提交修改</x:String>
29+
<x:String x:Key="Text.Apply.CommitChanges.Tip" xml:space="preserve">执行 `git am` 命令而非 `git apply` 命令</x:String>
2830
<x:String x:Key="Text.Apply.File.Placeholder" xml:space="preserve">选择补丁文件</x:String>
2931
<x:String x:Key="Text.Apply.IgnoreWS" xml:space="preserve">忽略空白符号</x:String>
3032
<x:String x:Key="Text.Apply.Source" xml:space="preserve">补丁来源 :</x:String>
@@ -581,6 +583,7 @@
581583
<x:String x:Key="Text.Init.CommandTip" xml:space="preserve">是否在该路径下执行 `git init` 命令(初始化仓库)?</x:String>
582584
<x:String x:Key="Text.Init.ErrorMessageTip" xml:space="preserve">打开本地仓库失败,原因:</x:String>
583585
<x:String x:Key="Text.Init.Path" xml:space="preserve">路径 :</x:String>
586+
<x:String x:Key="Text.InProgress.Am" xml:space="preserve">应用补丁操作进行中</x:String>
584587
<x:String x:Key="Text.InProgress.CherryPick" xml:space="preserve">挑选(Cherry-Pick)操作进行中。</x:String>
585588
<x:String x:Key="Text.InProgress.CherryPick.Head" xml:space="preserve">正在处理提交</x:String>
586589
<x:String x:Key="Text.InProgress.Merge" xml:space="preserve">合并操作进行中。</x:String>

‎src/ViewModels/Apply.cs‎

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.ComponentModel.DataAnnotations;
34
using System.IO;
45
using System.Threading.Tasks;
@@ -38,8 +39,20 @@ public bool ThreeWayMerge
3839
{
3940
get;
4041
set;
42+
} = true;
43+
44+
public bool CanCreateCommit
45+
{
46+
get => _canCreateCommit;
47+
set => SetProperty(ref _canCreateCommit, value);
4148
}
4249

50+
public bool CommitChanges
51+
{
52+
get;
53+
set;
54+
} = true;
55+
4356
public IClipboard Clipboard
4457
{
4558
get;
@@ -58,14 +71,24 @@ public static ValidationResult ValidatePatchFile(string file, ValidationContext
5871
return new ValidationResult("Invalid object instance!!!");
5972

6073
if (apply.FromClipboard)
74+
{
75+
apply.CanCreateCommit = false;
6176
return ValidationResult.Success;
77+
}
6278

6379
if (string.IsNullOrEmpty(file))
80+
{
81+
apply.CanCreateCommit = false;
6482
return new ValidationResult("Please select a patch file!!!");
83+
}
6584

6685
if (!File.Exists(file))
86+
{
87+
apply.CanCreateCommit = false;
6788
return new ValidationResult($"File '{file}' can NOT be found!!!");
89+
}
6890

91+
apply.CheckPatchFileFormat(file);
6992
return ValidationResult.Success;
7093
}
7194

@@ -98,9 +121,21 @@ public override async Task<bool> Sure()
98121
Use(log);
99122

100123
var extra = ThreeWayMerge ? "--3way" : string.Empty;
101-
var succ = await new Commands.Apply(_repo.FullPath, finalPatchFile, _ignoreWhiteSpace, SelectedWhiteSpaceMode.Arg, extra)
102-
.Use(log)
103-
.ExecAsync();
124+
var succ = false;
125+
if (!_fromClipboard && _canCreateCommit && CommitChanges)
126+
{
127+
_repo.ClearCommitMessage();
128+
129+
succ = await new Commands.Am(_repo.FullPath, finalPatchFile, _ignoreWhiteSpace, SelectedWhiteSpaceMode.Arg, extra)
130+
.Use(log)
131+
.ExecAsync();
132+
}
133+
else
134+
{
135+
succ = await new Commands.Apply(_repo.FullPath, finalPatchFile, _ignoreWhiteSpace, SelectedWhiteSpaceMode.Arg, extra)
136+
.Use(log)
137+
.ExecAsync();
138+
}
104139

105140
log.Complete();
106141

@@ -110,9 +145,35 @@ public override async Task<bool> Sure()
110145
return succ;
111146
}
112147

148+
private void CheckPatchFileFormat(string file)
149+
{
150+
try
151+
{
152+
using var reader = new StreamReader(file);
153+
var lines = new List<string>();
154+
for (int i = 0; i < 4; i++)
155+
{
156+
if (reader.EndOfStream)
157+
break;
158+
lines.Add(reader.ReadLine());
159+
}
160+
161+
CanCreateCommit = lines.Count == 4 &&
162+
lines[0].StartsWith("From ", StringComparison.Ordinal) &&
163+
lines[1].StartsWith("From: ", StringComparison.Ordinal) &&
164+
lines[2].StartsWith("Date: ", StringComparison.Ordinal) &&
165+
lines[3].StartsWith("Subject: ", StringComparison.Ordinal);
166+
}
167+
catch
168+
{
169+
CanCreateCommit = false;
170+
}
171+
}
172+
113173
private readonly Repository _repo = null;
114174
private string _patchFile = string.Empty;
115175
private bool _fromClipboard = false;
116176
private bool _ignoreWhiteSpace = true;
177+
private bool _canCreateCommit = false;
117178
}
118179
}

‎src/ViewModels/Conflict.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ public Conflict(Repository repo, WorkingCopy wc, Models.Change change)
4949
{
5050
CherryPickInProgress cherryPick => (_head, cherryPick.Head),
5151
RebaseInProgress rebase => (rebase.Onto, rebase.StoppedAt),
52+
AmInProgress applying => (_head, (object)"Patch"),
5253
RevertInProgress revert => (_head, revert.Head),
5354
MergeInProgress merge => (_head, merge.Source),
5455
_ => (_head, (object)"Stash or Patch"),

‎src/ViewModels/InProgressContexts.cs‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,76 @@ protected override void OnAborted()
171171
private readonly string _gitDir;
172172
}
173173

174+
public class AmInProgress : InProgressContext
175+
{
176+
public string Progress
177+
{
178+
get;
179+
}
180+
181+
public bool CanSkip
182+
{
183+
get;
184+
}
185+
186+
public AmInProgress(Repository repo)
187+
{
188+
_repo = repo;
189+
Name = "Apply Patch";
190+
191+
_continueCmd = new Commands.Command
192+
{
193+
WorkingDirectory = repo.FullPath,
194+
Context = repo.FullPath,
195+
Editor = Commands.Command.EditorType.None,
196+
Args = "am --continue",
197+
};
198+
199+
_skipCmd = new Commands.Command
200+
{
201+
WorkingDirectory = repo.FullPath,
202+
Context = repo.FullPath,
203+
Args = "am --skip",
204+
};
205+
206+
_abortCmd = new Commands.Command
207+
{
208+
WorkingDirectory = repo.FullPath,
209+
Context = repo.FullPath,
210+
Args = "am --abort",
211+
};
212+
213+
var next = ReadIntFromFile(Path.Combine(repo.GitDir, "rebase-apply", "next"));
214+
var total = ReadIntFromFile(Path.Combine(repo.GitDir, "rebase-apply", "last"));
215+
Progress = $"({next - 1}/{total})";
216+
CanSkip = next < total;
217+
}
218+
219+
protected override void OnAborted()
220+
{
221+
var rebaseApplyDir = Path.Combine(_repo.GitDir, "rebase-apply");
222+
if (Directory.Exists(rebaseApplyDir))
223+
Directory.Delete(rebaseApplyDir, true);
224+
225+
// Force update local changes.
226+
_repo.MarkWorkingCopyDirtyManually();
227+
}
228+
229+
private int ReadIntFromFile(string file)
230+
{
231+
if (!File.Exists(file))
232+
return 0;
233+
234+
var content = File.ReadAllText(file).Trim();
235+
if (int.TryParse(content, out var value))
236+
return value;
237+
238+
return 0;
239+
}
240+
241+
private readonly Repository _repo;
242+
}
243+
174244
public class RevertInProgress : InProgressContext
175245
{
176246
public Models.Commit Head

‎src/ViewModels/MergeConflictEditor.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ public MergeConflictEditor(Repository repo, Models.Commit head, string filePath)
8888
{
8989
CherryPickInProgress cherryPick => (head, cherryPick.Head),
9090
RebaseInProgress rebase => (rebase.Onto, rebase.StoppedAt),
91+
AmInProgress applying => (head, (object)"Patch"),
9192
RevertInProgress revert => (head, revert.Head),
9293
MergeInProgress merge => (head, merge.Source),
9394
_ => (head, (object)"Stash or Patch"),

‎src/ViewModels/WorkingCopy.cs‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -799,8 +799,10 @@ private void UpdateInProgressState()
799799

800800
if (File.Exists(Path.Combine(_repo.GitDir, "CHERRY_PICK_HEAD")))
801801
InProgressContext = new CherryPickInProgress(_repo);
802-
else if (Directory.Exists(Path.Combine(_repo.GitDir, "rebase-merge")) || Directory.Exists(Path.Combine(_repo.GitDir, "rebase-apply")))
802+
else if (Directory.Exists(Path.Combine(_repo.GitDir, "rebase-merge")))
803803
InProgressContext = new RebaseInProgress(_repo);
804+
else if (Directory.Exists(Path.Combine(_repo.GitDir, "rebase-apply")))
805+
InProgressContext = new AmInProgress(_repo);
804806
else if (File.Exists(Path.Combine(_repo.GitDir, "REVERT_HEAD")))
805807
InProgressContext = new RevertInProgress(_repo);
806808
else if (File.Exists(Path.Combine(_repo.GitDir, "MERGE_HEAD")))
@@ -820,13 +822,18 @@ private void UpdateInProgressState()
820822
if (LoadCommitMessageFromFile(Path.Combine(_repo.GitDir, "MERGE_MSG")))
821823
return;
822824

823-
if (_inProgressContext is not RebaseInProgress { } rebasing)
824-
return;
825-
826-
if (LoadCommitMessageFromFile(Path.Combine(_repo.GitDir, "rebase-merge", "message")))
827-
return;
828-
829-
SetAutoLoadedCommitMessage(new Commands.QueryCommitFullMessage(_repo.FullPath, rebasing.StoppedAt.SHA).GetResult());
825+
if (_inProgressContext is RebaseInProgress rebasing)
826+
{
827+
if (!LoadCommitMessageFromFile(Path.Combine(_repo.GitDir, "rebase-merge", "message")))
828+
{
829+
var message = new Commands.QueryCommitFullMessage(_repo.FullPath, rebasing.StoppedAt.SHA).GetResult();
830+
SetAutoLoadedCommitMessage(message);
831+
}
832+
}
833+
else if (_inProgressContext is AmInProgress applying)
834+
{
835+
LoadCommitMessageFromFile(Path.Combine(_repo.GitDir, "rebase-apply", "final-commit"));
836+
}
830837
}
831838

832839
private bool LoadCommitMessageFromFile(string file)

‎src/Views/Apply.axaml‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
Text="{DynamicResource Text.Apply.Title}"/>
1919
</StackPanel>
2020

21-
<Grid Margin="0,16,0,0" RowDefinitions="32,Auto,32,32,32" ColumnDefinitions="120,*">
21+
<Grid Margin="0,16,0,0" RowDefinitions="32,Auto,32,32,32,Auto" ColumnDefinitions="120,*">
2222
<TextBlock Grid.Row="0" Grid.Column="0"
2323
HorizontalAlignment="Right" VerticalAlignment="Center"
2424
Margin="0,0,8,0"
@@ -98,6 +98,19 @@
9898
Content="{DynamicResource Text.Apply.3Way}"
9999
IsChecked="{Binding ThreeWayMerge, Mode=TwoWay}"
100100
ToolTip.Tip="--3way"/>
101+
102+
<CheckBox Grid.Row="5" Grid.Column="1"
103+
Height="32"
104+
Content="{DynamicResource Text.Apply.CommitChanges}"
105+
IsChecked="{Binding CommitChanges, Mode=TwoWay}"
106+
ToolTip.Tip="{DynamicResource Text.Apply.CommitChanges.Tip}">
107+
<CheckBox.IsVisible>
108+
<MultiBinding Converter="{x:Static BoolConverters.And}">
109+
<Binding Path="FromClipboard" Mode="OneWay" Converter="{x:Static BoolConverters.Not}"/>
110+
<Binding Path="CanCreateCommit" Mode="OneWay"/>
111+
</MultiBinding>
112+
</CheckBox.IsVisible>
113+
</CheckBox>
101114
</Grid>
102115
</StackPanel>
103116
</UserControl>

‎src/Views/Repository.axaml‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,23 @@
217217
<TextBlock FontWeight="Bold" Margin="4,0,0,0" Foreground="DarkOrange" Text="{Binding Current}"/>
218218
</StackPanel>
219219
</DataTemplate>
220+
221+
<DataTemplate DataType="vm:AmInProgress">
222+
<Grid ColumnDefinitions="*,Auto">
223+
<StackPanel Grid.Column="0" Orientation="Horizontal">
224+
<TextBlock FontWeight="Bold" Foreground="{DynamicResource Brush.Conflict.Foreground}" Text="{DynamicResource Text.InProgress.Am}"/>
225+
<TextBlock FontWeight="Bold"
226+
Margin="4,0,0,0"
227+
Foreground="{DynamicResource Brush.Conflict.Foreground}"
228+
FontFamily="{DynamicResource Fonts.Monospace}"
229+
Text="{Binding Progress, Mode=OneWay}"/>
230+
</StackPanel>
231+
232+
<Button Grid.Column="1" Classes="flat" FontWeight="Regular" BorderThickness="0"
233+
Content="{DynamicResource Text.Repository.Skip}" Padding="8,2" Click="OnSkipInProgress"
234+
IsVisible="{Binding CanSkip}" />
235+
</Grid>
236+
</DataTemplate>
220237
</ContentControl.DataTemplates>
221238
</ContentControl>
222239

0 commit comments

Comments
 (0)