forked from sourcegit-scm/sourcegit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommand.cs
More file actions
259 lines (215 loc) · 8.53 KB
/
Copy pathCommand.cs
File metadata and controls
259 lines (215 loc) · 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace SourceGit.Commands
{
public partial class Command
{
public class Result
{
public bool IsSuccess { get; set; } = false;
public string StdOut { get; set; } = string.Empty;
public string StdErr { get; set; } = string.Empty;
public static Result Failed(string reason) => new Result() { StdErr = reason };
}
public enum EditorType
{
None,
CoreEditor,
RebaseEditor,
}
public string Context { get; set; } = string.Empty;
public string WorkingDirectory { get; set; } = null;
public EditorType Editor { get; set; } = EditorType.CoreEditor;
public string SSHKey { get; set; } = string.Empty;
public string Args { get; set; } = string.Empty;
// Only used in `ExecAsync` mode.
public CancellationToken CancellationToken { get; set; } = CancellationToken.None;
public bool RaiseError { get; set; } = true;
public Models.ICommandLog Log { get; set; } = null;
public async Task<bool> ExecAsync()
{
Log?.AppendLine($"$ git {Args}\n");
var errs = new List<string>();
using var proc = new Process();
proc.StartInfo = CreateGitStartInfo(true);
proc.OutputDataReceived += (_, e) => HandleOutput(e.Data, errs);
proc.ErrorDataReceived += (_, e) => HandleOutput(e.Data, errs);
var captured = new CapturedProcess() { Process = proc };
var capturedLock = new object();
try
{
proc.Start();
// Not safe, please only use `CancellationToken` in readonly commands.
if (CancellationToken.CanBeCanceled)
{
CancellationToken.Register(() =>
{
lock (capturedLock)
{
if (captured is { Process: { HasExited: false } })
captured.Process.Kill();
}
});
}
}
catch (Exception e)
{
if (RaiseError)
RaiseException(e.Message);
Log?.AppendLine(string.Empty);
return false;
}
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
try
{
await proc.WaitForExitAsync(CancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
HandleOutput(e.Message, errs);
}
lock (capturedLock)
{
captured.Process = null;
}
Log?.AppendLine(string.Empty);
if (!CancellationToken.IsCancellationRequested && proc.ExitCode != 0)
{
if (RaiseError)
{
var errMsg = string.Join("\n", errs).Trim();
if (!string.IsNullOrEmpty(errMsg))
RaiseException(errMsg);
}
return false;
}
return true;
}
protected Result ReadToEnd()
{
using var proc = new Process();
proc.StartInfo = CreateGitStartInfo(true);
try
{
proc.Start();
}
catch (Exception e)
{
return Result.Failed(e.Message);
}
var rs = new Result() { IsSuccess = true };
rs.StdOut = proc.StandardOutput.ReadToEnd();
rs.StdErr = proc.StandardError.ReadToEnd();
proc.WaitForExit();
rs.IsSuccess = proc.ExitCode == 0;
return rs;
}
protected async Task<Result> ReadToEndAsync()
{
using var proc = new Process();
proc.StartInfo = CreateGitStartInfo(true);
try
{
proc.Start();
}
catch (Exception e)
{
return Result.Failed(e.Message);
}
var rs = new Result() { IsSuccess = true };
rs.StdOut = await proc.StandardOutput.ReadToEndAsync(CancellationToken).ConfigureAwait(false);
rs.StdErr = await proc.StandardError.ReadToEndAsync(CancellationToken).ConfigureAwait(false);
await proc.WaitForExitAsync(CancellationToken).ConfigureAwait(false);
rs.IsSuccess = proc.ExitCode == 0;
return rs;
}
protected ProcessStartInfo CreateGitStartInfo(bool redirect)
{
var start = new ProcessStartInfo();
start.FileName = Native.OS.GitExecutable;
start.UseShellExecute = false;
start.CreateNoWindow = true;
if (redirect)
{
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.StandardOutputEncoding = Encoding.UTF8;
start.StandardErrorEncoding = Encoding.UTF8;
}
// Force using this app as SSH askpass program
var selfExecFile = Process.GetCurrentProcess().MainModule!.FileName;
start.Environment.Add("SSH_ASKPASS", selfExecFile); // Can not use parameter here, because it invoked by SSH with `exec`
start.Environment.Add("SSH_ASKPASS_REQUIRE", "prefer");
start.Environment.Add("SOURCEGIT_LAUNCH_AS_ASKPASS", "TRUE");
if (!OperatingSystem.IsLinux())
start.Environment.Add("DISPLAY", "required");
// If an SSH private key was provided, sets the environment.
if (!start.Environment.ContainsKey("GIT_SSH_COMMAND") && !string.IsNullOrEmpty(SSHKey))
start.Environment.Add("GIT_SSH_COMMAND", $"ssh -i '{SSHKey}' -F '/dev/null'");
// Force using en_US.UTF-8 locale
if (OperatingSystem.IsLinux())
{
start.Environment.Add("LANG", "C");
start.Environment.Add("LC_ALL", "C");
}
var builder = new StringBuilder(2048);
builder
.Append("--no-pager -c core.quotepath=off -c credential.helper=")
.Append(Native.OS.CredentialHelper)
.Append(' ');
switch (Editor)
{
case EditorType.CoreEditor:
builder.Append($"""-c core.editor="\"{selfExecFile}\" --core-editor" """);
break;
case EditorType.RebaseEditor:
builder.Append($"""-c core.editor="\"{selfExecFile}\" --rebase-message-editor" -c sequence.editor="\"{selfExecFile}\" --rebase-todo-editor" -c rebase.abbreviateCommands=true """);
break;
default:
builder.Append("-c core.editor=true ");
break;
}
builder.Append(Args);
start.Arguments = builder.ToString();
// Working directory
if (!string.IsNullOrEmpty(WorkingDirectory))
start.WorkingDirectory = WorkingDirectory;
return start;
}
protected void RaiseException(string error)
{
Models.Notification.Send(Context, error, true);
}
private void HandleOutput(string line, List<string> errs)
{
if (line == null)
return;
Log?.AppendLine(line);
// Lines to hide in error message.
if (line.Length > 0)
{
if (line.StartsWith("remote: Enumerating objects:", StringComparison.Ordinal) ||
line.StartsWith("remote: Counting objects:", StringComparison.Ordinal) ||
line.StartsWith("remote: Compressing objects:", StringComparison.Ordinal) ||
line.StartsWith("Filtering content:", StringComparison.Ordinal) ||
line.StartsWith("hint:", StringComparison.Ordinal))
return;
if (REG_PROGRESS().IsMatch(line))
return;
}
errs.Add(line);
}
private class CapturedProcess
{
public Process Process { get; set; } = null;
}
[GeneratedRegex(@"\d+%")]
private static partial Regex REG_PROGRESS();
}
}