-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
190 lines (167 loc) · 5.75 KB
/
Program.cs
File metadata and controls
190 lines (167 loc) · 5.75 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
using System.Diagnostics;
using System.Text;
// defaults
var checkTime = false;
var dryRun = false;
var usageMessage = "Usage: checknew.exe [--dry-run] [--check-time] [local] host:remote";
int nextArg;
for (nextArg = 0; nextArg < args.Length && args[nextArg].StartsWith("--"); nextArg++) {
switch (args[nextArg]) {
case "--check-time":
checkTime = true;
break;
case "--dry-run":
dryRun = true;
break;
case "--help":
Console.WriteLine(usageMessage);
return 0;
default:
Console.WriteLine("Unknown option: {0}", args[nextArg]);
Console.WriteLine(usageMessage);
return 1;
}
}
args = args[nextArg..];
string[] remote = Array.Empty<string>();
string localDir = "";
if (args.Length == 2) {
localDir = args[0];
remote = args[1].Split(':', 2);
} else if (args.Length == 1) {
localDir = Directory.GetCurrentDirectory();
remote = args[0].Split(':', 2);
} else {
Console.WriteLine("Usage: checknew.exe [local] host:remote");
return 1;
}
if (remote.Length != 2) {
Debug.Assert(remote.Length == 1);
Console.WriteLine($"Wrong remote format: {remote[0]}");
Console.WriteLine(usageMessage);
return 1;
}
var remoteHost = remote[0];
var remoteDir = remote[1];
using var findCmd = new Process() {
StartInfo = {
FileName = "ssh",
RedirectStandardOutput = true,
ArgumentList = {
remoteHost, "find", ShellQuote(remoteDir), "-type", "f", "-printf '%T@ %s %P\\n'"
},
// This is needed because `ssh` command returns utf-8 encoded text.
StandardOutputEncoding = Encoding.UTF8
}
};
findCmd.Start();
var commands = Path.GetTempFileName();
bool newFilesFound = false;
using (var writer = new StreamWriter(commands)) {
string? line;
while ((line = findCmd.StandardOutput.ReadLine()) != null) {
var remoteFile = ParseFindString(line);
var filePath = remoteFile.Path.Replace('/', '\\');
var localPath = Path.Join(localDir, filePath);
var fileinfo = new FileInfo(localPath);
if (!fileinfo.Exists) {
Console.WriteLine($"File {filePath} doesn't exist locally!");
} else {
long localSize = fileinfo.Length;
DateTime localModified = fileinfo.LastWriteTime;
if (localSize != remoteFile.Size) {
Console.WriteLine($"File {filePath} has a different size. {ToHumanSize(localSize)} (local) <- {ToHumanSize(remoteFile.Size)} (remote).");
} else if (localModified < remoteFile.Modified) {
if (!checkTime) {
// ignore the difference in modified time
continue;
}
Console.WriteLine($"File {filePath} is outdated. {localModified} (local) <- {remoteFile.Modified} (remote).");
} else {
continue;
}
}
try {
Directory.CreateDirectory(fileinfo.DirectoryName!);
} catch (IOException) {
Console.WriteLine($"Can't create a local directory for a file: {localPath}. Skipping it.");
continue;
}
newFilesFound = true;
var remotePath = remoteDir.TrimEnd('/') + '/' + remoteFile.Path;
var command = $"get \"{remotePath}\" \"{localPath}\"";
writer.WriteLine(command);
}
}
findCmd.WaitForExit();
if (findCmd.ExitCode != 0) {
Console.WriteLine("Find command exited with non-zero code!");
return 1;
}
if (!newFilesFound) {
Console.WriteLine("Done! No new files found.");
return 0;
}
Console.WriteLine($"Commands to sftp: {commands}");
if (dryRun) {
Console.WriteLine("Dry run. No copying will be performed!");
return 0;
}
using var sftpCmd = new Process() {
StartInfo = {
FileName = "sftp",
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = $"-b {commands} {remoteHost}"
}
};
sftpCmd.Start();
var result = await Task.WhenAll(sftpCmd.StandardOutput.ReadToEndAsync(), sftpCmd.StandardError.ReadToEndAsync());
sftpCmd.WaitForExit();
if (sftpCmd.ExitCode != 0) {
Console.WriteLine("Sftp command exited with non-zero code!");
Console.WriteLine(result[1]);
return 1;
} else {
Console.WriteLine("Done!");
return 0;
}
string ShellQuote(string str) {
return "'" + str.Replace("'", "'\\''") + "'";
}
// example:
// 1739519415.0753701630 38694 .bash_history
(DateTime Modified, long Size, string Path) ParseFindString(string s) {
var data = s.Split(' ', 3);
Debug.Assert(data.Length == 3);
var date = TimestampToDateTime(data[0]);
return (date, long.Parse(data[1]), data[2]);
}
DateTime TimestampToDateTime(string unixTimestamp) {
unixTimestamp = unixTimestamp.Split(".")[0];
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimestamp));
DateTime dateTime = dateTimeOffset.DateTime.ToLocalTime();
return dateTime;
}
string ToHumanSize(long bytes) {
long KB = 1024;
long MB = KB * 1024;
long GB = MB * 1024;
long TB = GB * 1024;
double size = bytes;
if (bytes >= TB) {
size = Math.Round((double)bytes / TB, 2);
return $"{size} TB";
} else if (bytes >= GB) {
size = Math.Round((double)bytes / GB, 2);
return $"{size} GB";
} else if (bytes >= MB) {
size = Math.Round((double)bytes / MB, 2);
return $"{size} MB";
} else if (bytes >= KB) {
size = Math.Round((double)bytes / KB, 2);
return $"{size} KB";
} else {
return $"{size} Bytes";
}
}