Skip to content
This repository was archived by the owner on Feb 19, 2024. It is now read-only.

Commit 5634662

Browse files
committed
improved CLI, registering, uploading to repository
1 parent 41d8c40 commit 5634662

File tree

5 files changed

+186
-1
lines changed

5 files changed

+186
-1
lines changed

AccountManagement.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using Newtonsoft.Json;
2+
using Pastel;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
9+
namespace Zephyr
10+
{
11+
internal class AccountManagement
12+
{
13+
public static void Register(string username, string password, string repositoryUrl)
14+
{
15+
RepositoryHTTP.Post($"{repositoryUrl}/users/register", new
16+
{
17+
username,
18+
password
19+
}, "registering");
20+
21+
Console.WriteLine($"Account created!");
22+
}
23+
}
24+
}

CommandLineOptions.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,30 @@ internal class CommandLineOptionsCreatePackage
7272
{
7373

7474
}
75+
76+
[Verb("register", HelpText = "Register an account on the repository")]
77+
internal class CommandLineOptionsRegisterUser
78+
{
79+
[Value(0, HelpText = "The username of the user to register", Required = true)]
80+
public string Username { get; set; } = "";
81+
82+
[Value(1, HelpText = "The password of the user to register", Required = true)]
83+
public string Password { get; set; } = "";
84+
85+
[Option('r', "repository", HelpText = "The repository URL to register to", Default = PackageManager.DefaultRepository)]
86+
public string RepositoryUrl { get; set; } = PackageManager.DefaultRepository;
87+
}
88+
89+
[Verb("upload-package", HelpText = "Uploads the package in the current directory to the repository")]
90+
internal class CommandLineOptionsUploadPackage
91+
{
92+
[Option('r', "repository", HelpText = "The repository URL to upload to", Default = PackageManager.DefaultRepository)]
93+
public string RepositoryUrl { get; set; } = PackageManager.DefaultRepository;
94+
95+
[Option('u', "username", HelpText = "The username of the user", Required = true)]
96+
public string Username { get; set; } = "";
97+
98+
[Option('p', "password", HelpText = "The password of the user", Required = true)]
99+
public string Password { get; set; } = "";
100+
}
75101
}

PackageManager.cs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Diagnostics;
66
using System.IO.Compression;
77
using System.Linq;
8+
using System.Net.Http;
89
using System.Text;
910
using System.Threading.Tasks;
1011

@@ -156,6 +157,76 @@ public static void InstallPackage(string packageName, string packageVersion, Uri
156157
Console.WriteLine($"Done in {stopwatch.ElapsedMilliseconds}ms!");
157158
}
158159

160+
public static void UploadPackage(Uri repositoryUrl, string username, string password)
161+
{
162+
ZephyrPackageWithLocation package = GetZephyrPackage();
163+
164+
// Fetch all files
165+
List<string> files = new();
166+
167+
foreach (string file in Directory.EnumerateFiles(package.Location, "*.*", SearchOption.AllDirectories)
168+
.Where(s => !(Path.GetDirectoryName(s).Contains("zephyr_packages"))))
169+
{
170+
files.Add(file);
171+
}
172+
173+
long totalSize = 0;
174+
175+
Console.WriteLine($"Found {files.Count} files to upload");
176+
Console.WriteLine($"\n============ {files.Count} files ============");
177+
files.ForEach(x =>
178+
{
179+
long len = new FileInfo(x).Length;
180+
totalSize += len;
181+
Console.WriteLine($"{x.Replace(package.Location, "")} ({len}b)");
182+
});
183+
Console.WriteLine($"============ {files.Count} files ============\n");
184+
Console.WriteLine($"Total unzipped upload size will be {totalSize}b");
185+
Console.WriteLine($"\nYou are uploading {package.Package.Name}@{package.Package.Version} to {repositoryUrl}!");
186+
Console.Write($"Confirm upload, use -y to confirm in the future (y/n): ");
187+
string? cres = Console.ReadLine();
188+
189+
// Check if user confirmed
190+
if (cres != "y")
191+
{
192+
Environment.Exit(0);
193+
return;
194+
}
195+
196+
// Create ZIP file
197+
string zipfileLocation = $"{Path.Combine(package.Location, Guid.NewGuid().ToString())}.zip";
198+
Console.WriteLine($"Generating ZIP file... ({zipfileLocation})");
199+
200+
using (ZipArchive archive = ZipFile.Open(zipfileLocation, ZipArchiveMode.Create))
201+
{
202+
files.ForEach(file =>
203+
{
204+
string name = file.Replace("\\", "/").Replace(package.Location.Replace("\\", "/") + "/", "").Replace(package.Location.Replace("\\", "/"), "");
205+
archive.CreateEntryFromFile(file, name);
206+
Console.WriteLine($"Added {file} ({name}) to archive");
207+
});
208+
}
209+
210+
Console.WriteLine($"Uploading archive to {repositoryUrl} ({new FileInfo(zipfileLocation).Length}b)");
211+
string zipData = Convert.ToHexString(File.ReadAllBytes(zipfileLocation));
212+
213+
Console.WriteLine($"Cleaning up...");
214+
File.Delete(zipfileLocation);
215+
216+
// Send request
217+
RepositoryHTTP.Post($"{repositoryUrl}package/{package.Package.Name}/{package.Package.Version}/upload", new
218+
{
219+
username,
220+
password,
221+
data = zipData
222+
}, $"uploading {package.Package.Name}");
223+
224+
// Done
225+
Console.WriteLine($"\n{package.Package.Name}@{package.Package.Version} uploaded successfully!");
226+
Console.WriteLine($"\nDownload using zephyr install-package {package.Package.Name} {package.Package.Version}");
227+
Console.WriteLine($"Or navigate to {repositoryUrl}package/{package.Package.Name}/{package.Package.Version}");
228+
}
229+
159230
public static ZephyrPackageWithLocation GetZephyrPackage()
160231
{
161232
Console.WriteLine($"Finding package.json in closest directory...");

Program.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,11 @@ static void Main(string[] args)
6060
}
6161
}
6262

63-
CommandLine.Parser.Default.ParseArguments<CommandLineOptions, CommandLineOptionsInstallPackage, CommandLineOptionsCreatePackage>(runnerArgs.ToArray())
63+
CommandLine.Parser.Default.ParseArguments<
64+
CommandLineOptions, CommandLineOptionsInstallPackage,
65+
CommandLineOptionsCreatePackage, CommandLineOptionsRegisterUser,
66+
CommandLineOptionsUploadPackage
67+
>(runnerArgs.ToArray())
6468
.WithParsed<CommandLineOptions>(o =>
6569
{
6670
Options = o;
@@ -140,6 +144,12 @@ static void Main(string[] args)
140144
}).WithParsed<CommandLineOptionsInstallPackage>(o =>
141145
{
142146
PackageManager.InstallPackage(o.PackageName, o.PackageVersion, new Uri(o.RepositoryUrl));
147+
}).WithParsed<CommandLineOptionsRegisterUser>(o =>
148+
{
149+
AccountManagement.Register(o.Username, o.Password, o.RepositoryUrl);
150+
}).WithParsed<CommandLineOptionsUploadPackage>(o =>
151+
{
152+
PackageManager.UploadPackage(new Uri(o.RepositoryUrl), o.Username, o.Password);
143153
});
144154
} catch (Exception e)
145155
{

RepositoryHTTP.cs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
using Newtonsoft.Json;
2+
using Pastel;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
9+
namespace Zephyr
10+
{
11+
internal class RepositoryHTTP
12+
{
13+
public static void Post(string url, object data, string action = "posting")
14+
{
15+
HttpClient httpClient = new HttpClient();
16+
string sendingData = JsonConvert.SerializeObject(data);
17+
18+
HttpResponseMessage? res = null;
19+
string? jsonRes = null;
20+
21+
try
22+
{
23+
Console.WriteLine($"POST {url}");
24+
res = httpClient.PostAsync(url, new StringContent(sendingData, Encoding.UTF8, "application/json")).GetAwaiter().GetResult();
25+
Console.WriteLine($"Recieved status code {res.StatusCode} ({(res.IsSuccessStatusCode ? "Success" : "Failure")})");
26+
27+
// Check if successful
28+
if (!res.IsSuccessStatusCode)
29+
{
30+
// Get result
31+
jsonRes = res.Content.ReadAsStringAsync().GetAwaiter().GetResult();
32+
33+
// Get message
34+
PackageManagerErrorResult? errRes = JsonConvert.DeserializeObject<PackageManagerErrorResult>(jsonRes);
35+
if (errRes == null) errRes.Message = "Unknown error";
36+
37+
Console.WriteLine($"Error[{(int)res.StatusCode}] occurred whilst {action}: {errRes.Message}".Pastel(ConsoleColor.Red));
38+
Environment.Exit(0);
39+
}
40+
}
41+
catch (HttpRequestException e)
42+
{
43+
Console.WriteLine($"Fatal HTTP error: {e.Message}, try again later!".Pastel(ConsoleColor.Red));
44+
Environment.Exit(0);
45+
}
46+
catch (JsonReaderException e)
47+
{
48+
Console.WriteLine($"Failed to read response ({e.Message})".Pastel(ConsoleColor.Red));
49+
Console.WriteLine($"{jsonRes}".Pastel(ConsoleColor.Red));
50+
Environment.Exit(0);
51+
}
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)