-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
319 lines (281 loc) · 12.3 KB
/
Program.cs
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using System.IO;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using System.Text.Json.Serialization;
using System.Diagnostics;
using Google.Apis.Upload;
using System.Collections;
using Google.Apis.Download;
namespace GoogleDriveLFS
{
internal class Program
{
const string ConfigName = ".gdrivelfs";
static readonly JsonSerializerOptions JsonOptions;
static TextWriter? LogStream;
static Program()
{
JsonOptions = new JsonSerializerOptions();
JsonOptions.IncludeFields = true;
JsonOptions.WriteIndented = false;
JsonOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
JsonOptions.Converters.Add(new JsonStringEnumConverter());
}
static void Main(string[] args)
{
var configPath = args.Length > 0 ? args[0] : ConfigName;
if (string.IsNullOrEmpty(configPath))
{
Console.Error.WriteLine($"{ConfigName} not found, working directory: {Environment.CurrentDirectory}");
return;
}
var config = JsonSerializer.Deserialize<Config>(System.IO.File.ReadAllText(configPath), JsonOptions);
if (config.attach_debugger)
{
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
Debugger.Break();
}
var initializer = new ServiceAccountCredential.Initializer(config.client_email) { Scopes = new string[] { DriveService.Scope.Drive } };
ServiceAccountCredential credential = new ServiceAccountCredential(initializer.FromPrivateKey(config.private_key));
// Create the service.
//using (var log = OpenLog(config.log_path))
{
//LogStream = log;
using (var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GoogleDriveLFS" }))
{
if (config.drive_id == null)
{
ListTeamDrives(service);
return;
}
Log($"Working directory: {Environment.CurrentDirectory}");
if (config.input_files != null)
{
foreach (var file in config.input_files)
{
using (var reader = new StreamReader(file))
{
Log($"Progressing commands from: {file}");
ProcessCommands(service, config.drive_id, reader, Console.Out);
}
}
}
else
{
Log($"Progressing commands from STDIN, STDIN Redirected {Console.IsInputRedirected}, STDOUT Redirected {Console.IsOutputRedirected}");
//using (var input = Console.IsInputRedirected ? new StreamReader(Console.OpenStandardInput(65536)) : Console.In)
//using (var output = Console.IsOutputRedirected ? new StreamWriter(Console.OpenStandardOutput(65536)) : Console.Out)
{
ProcessCommands(service, config.drive_id, Console.In, Console.Out);
}
}
}
}
}
private static StreamWriter? OpenLog(string logPath)
{
if (logPath != null && Environment.ProcessPath != null)
{
logPath = logPath.Replace("~", Path.GetDirectoryName(Environment.ProcessPath));
}
if (logPath != null)
{
logPath = Path.ChangeExtension(logPath, $"{Process.GetCurrentProcess().Id}" + Path.GetExtension(logPath));
}
return logPath != null ? System.IO.File.CreateText(logPath) : null;
}
private static bool TryGetCurrentDirConfig(out string path)
{
if (Environment.ProcessPath != null)
{
path = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), ConfigName);
return System.IO.File.Exists(path);
}
path = null;
return false;
}
private static void Log(string msg)
{
Console.Error.WriteLine(msg);
//if (LogStream != null)
//{
// LogStream.WriteLine(msg);
// LogStream.Flush();
//}
}
private static void ListTeamDrives(DriveService service)
{
Log("Listing team drives:");
foreach (var drive in service.Teamdrives.List().Execute().TeamDrives)
{
Log($"{drive.Id}: {drive.Name}");
}
}
private static void ProcessCommands(DriveService service, string driveId, TextReader inputCommands, TextWriter output)
{
Log("Processing commands...");
while (true)
{
string? cmdJson = inputCommands.ReadLine();
if (string.IsNullOrWhiteSpace(cmdJson))
{
Thread.Sleep(100);
continue;
}
Log("Processing: " + cmdJson);
var cmd = JsonSerializer.Deserialize<CommandData>(cmdJson, JsonOptions);
switch (cmd.@event)
{
case CommandKind.init: SendCommand(output, "{ }"); break;
case CommandKind.upload: HandleUpload(service, driveId, cmd.oid, cmd.size, cmd.path, cmd.action, output); break;
case CommandKind.download: HandleDownload(service, driveId, cmd.oid, cmd.size, cmd.action, output); break;
case CommandKind.terminate: Log("Processing commands...done"); return;
}
}
;
}
private static void HandleUpload(DriveService service, string driveId, string oid, long size, string path, ActionData action, TextWriter output)
{
using (var stream = System.IO.File.OpenRead(path))
{
var listRequest = service.Files.List();
listRequest.Q = $"name='{oid}'";
listRequest.Fields = "files(id)";
listRequest.Corpora = "drive";
listRequest.DriveId = driveId;
listRequest.IncludeItemsFromAllDrives = true;
listRequest.SupportsAllDrives = true;
var list = listRequest.Execute();
ResumableUpload<Google.Apis.Drive.v3.Data.File, Google.Apis.Drive.v3.Data.File> request;
if (list.Files.Count > 0)
{
string fileId = list.Files[0].Id;
// Only include fields which should be changed
var file = new Google.Apis.Drive.v3.Data.File();
file.MimeType = "application/octet-stream";
var updateRequest = service.Files.Update(file, fileId, stream, "application/octet-stream");
updateRequest.SupportsAllDrives = true;
request = updateRequest;
}
else
{
var driveFile = new Google.Apis.Drive.v3.Data.File();
driveFile.Name = oid;
driveFile.MimeType = "application/octet-stream";
driveFile.DriveId = driveId;
driveFile.Parents = new string[] { driveId };
var createRequest = service.Files.Create(driveFile, stream, "application/octet-stream");
createRequest.SupportsAllDrives = true;
createRequest.Fields = "id";
request = createRequest;
}
long bytes = 0;
request.ProgressChanged += progress =>
{
ReportProgress(output, oid, progress.BytesSent, progress.BytesSent - bytes);
bytes = progress.BytesSent;
};
var response = request.Upload();
if (response.Status != UploadStatus.Completed)
{
ReportError(output, oid, 3, $"Upload failed: {response.Exception.Message}");
}
else
{
Log($"File uploaded: {request.ResponseBody.Id}");
ReportComplete(output, oid, null);
}
}
}
private static void HandleDownload(DriveService service, string driveId, string oid, long size, ActionData action, TextWriter output)
{
var listRequest = service.Files.List();
listRequest.Q = $"name='{oid}'";
listRequest.Fields = "files(id)";
listRequest.Corpora = "drive";
listRequest.DriveId = driveId;
listRequest.IncludeItemsFromAllDrives = true;
listRequest.SupportsAllDrives = true;
var list = listRequest.Execute();
if (list.Files.Count == 0)
{
ReportError(output, oid, 2, "File not found");
return;
}
string tmpPath = "";
FileStream? stream = default;
try
{
tmpPath = GetLfsTempFile(oid);
stream = System.IO.File.Create(tmpPath);
}
catch (Exception e)
{
ReportError(output, oid, 4, "Could not create temporary file " + e.Message);
return;
}
IDownloadProgress? progress;
using (stream)
{
var file = list.Files[0];
var getRequest = service.Files.Get(file.Id);
getRequest.SupportsAllDrives = true;
long bytes = 0;
getRequest.MediaDownloader.ProgressChanged += progress =>
{
ReportProgress(output, oid, progress.BytesDownloaded, progress.BytesDownloaded - bytes);
bytes = progress.BytesDownloaded;
};
progress = getRequest.DownloadWithStatus(stream);
}
if (progress.Status != DownloadStatus.Completed)
{
ReportError(output, oid, 3, $"Download failed: {progress.Exception.Message}");
}
else
{
ReportComplete(output, oid, tmpPath);
}
}
private static string GetLfsTempFile(string oid)
{
// Git LFS uses rename to move tmp files to their destination. But rename does not work across
// drives, so we have to make sure that the tmp file is on the same drive as the repository.
var pwd = Directory.GetCurrentDirectory();
var tmpDir = Path.Combine(pwd, ".tmplfs");
if (!Directory.Exists(tmpDir))
{
Directory.CreateDirectory(tmpDir);
}
return Path.Combine(tmpDir, oid);
}
private static void SendCommand(TextWriter output, string cmd)
{
if (output != LogStream)
{
Log("-> " + cmd);
}
output.Write(cmd + "\n");
output.Flush();
}
private static void ReportProgress(TextWriter output, string oid, long bytesSoFar, long bytesSinceLast)
{
SendCommand(output, JsonSerializer.Serialize(new CommandData { @event = CommandKind.progress, oid = oid, bytesSoFar = bytesSoFar, bytesSinceLast = bytesSinceLast }, JsonOptions));
}
private static void ReportError(TextWriter output, string oid, int code, string message)
{
SendCommand(output, JsonSerializer.Serialize(new CommandData { @event = CommandKind.complete, oid = oid, error = new ErrorData { code = code, message = message } }, JsonOptions));
}
private static void ReportComplete(TextWriter output, string oid, string path)
{
SendCommand(output, JsonSerializer.Serialize(new CommandData { @event = CommandKind.complete, oid = oid, path = path }, JsonOptions));
}
}
}