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
230 lines (193 loc) · 7.71 KB
/
Command.cs
File metadata and controls
230 lines (193 loc) · 7.71 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
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; }
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; }
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; }
public void Exec()
{
try
{
var start = CreateGitStartInfo(false);
Process.Start(start);
}
catch (Exception ex)
{
App.RaiseException(Context, ex.Message);
}
}
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);
Process dummy = null;
var dummyProcLock = new object();
try
{
proc.Start();
// Not safe, please only use `CancellationToken` in readonly commands.
if (CancellationToken.CanBeCanceled)
{
dummy = proc;
CancellationToken.Register(() =>
{
lock (dummyProcLock)
{
if (dummy is { HasExited: false })
dummy.Kill();
}
});
}
}
catch (Exception e)
{
if (RaiseError)
App.RaiseException(Context, 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);
}
if (dummy != null)
{
lock (dummyProcLock)
{
dummy = null;
}
}
Log?.AppendLine(string.Empty);
if (!CancellationToken.IsCancellationRequested && proc.ExitCode != 0)
{
if (RaiseError)
{
var errMsg = string.Join("\n", errs).Trim();
if (!string.IsNullOrEmpty(errMsg))
App.RaiseException(Context, errMsg);
}
return false;
}
return true;
}
protected async Task<Result> ReadToEndAsync()
{
using var proc = new Process() { 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;
}
private ProcessStartInfo CreateGitStartInfo(bool redirect)
{
var start = new ProcessStartInfo();
start.FileName = Native.OS.GitExecutable;
start.Arguments = "--no-pager -c core.quotepath=off -c credential.helper=manager ";
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;
if (!OperatingSystem.IsLinux())
start.Environment.Add("DISPLAY", "required");
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 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}'");
// Force using en_US.UTF-8 locale
if (OperatingSystem.IsLinux())
{
start.Environment.Add("LANG", "C");
start.Environment.Add("LC_ALL", "C");
}
// Force using this app as git editor.
start.Arguments += Editor switch
{
EditorType.CoreEditor => $"""-c core.editor="{selfExecFile.Quoted()} --core-editor" """,
EditorType.RebaseEditor => $"""-c core.editor="{selfExecFile.Quoted()} --rebase-message-editor" -c sequence.editor="{selfExecFile.Quoted()} --rebase-todo-editor" -c rebase.abbreviateCommands=true """,
_ => "-c core.editor=true ",
};
// Append command args
start.Arguments += Args;
// Working directory
if (!string.IsNullOrEmpty(WorkingDirectory))
start.WorkingDirectory = WorkingDirectory;
return start;
}
private void HandleOutput(string line, List<string> errs)
{
line ??= string.Empty;
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);
}
[GeneratedRegex(@"\d+%")]
private static partial Regex REG_PROGRESS();
}
}