public CommandResult <string> NugetDownload( CommandEvaluationContext context, [Parameter(0, "package (.nuget) ID")] string id, [Parameter(1, "package version")] string ver, [Option("o", "output", "output path", true, true)] string @out = ".", [Option("u", "download-url", "nuget server api query service template url", true, true)] string url = DownloadUrl ) { id = id.Trim().ToLower(); ver = ver.ToLower(); var queryString = url .Replace("{LOWER_ID}", id) .Replace("{LOWER_VERSION}", ver); context.Out.Echo(context.ShellEnv.Colors.Log + $"GET {queryString} ... "); using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("GET"), queryString); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var str = result.Content.ReadAsStreamAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo if (str == null) { context.Warning("result is empty"); } else { var fn = $"{id}.{ver}.nupkg"; @out = Path.Combine(@out, fn); using var fstr = new FileStream(@out, FileMode.Create, FileAccess.Write); int b; while ((b = str.ReadByte()) != -1) { fstr.WriteByte((byte)b); } str.Close(); fstr.Close(); context.Out.Echoln($"package '{fn}' has been downloaded to: {new FilePath(@out)}"); return(new CommandResult <string>(@out)); } } else { context.Errorln($"can't get response content: {result.ReasonPhrase}"); return(new CommandResult <string>(ReturnCode.Error)); } return(new CommandResult <string>(ReturnCode.Error)); }
public CommandResult <PackageVersions> NugetVer( CommandEvaluationContext context, [Parameter(0, "package (.nuget) ID")] string id, [Option("q", "quiet", "mute output of result")] bool quiet = false, [Option("u", "get-url", "nuget server api query service template url", true, true)] string url = GetVerUrl ) { var queryString = url.Replace("{ID}", id.Trim()); context.Out.Echo(context.ShellEnv.Colors.Log + $"GET {queryString} ... "); using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("GET"), queryString); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var res = result.Content.ReadAsStringAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo if (res != null && !string.IsNullOrWhiteSpace(res)) { if (!quiet) { context.Out.Echoln(res); } var obj = JsonConvert.DeserializeObject <PackageVersions>(res); return(new CommandResult <PackageVersions>(obj)); } else { context.Warning("result is empty"); } } else { context.Errorln($"can't get response content: {result.ReasonPhrase}"); } return(new CommandResult <PackageVersions>(null)); }
public void CleanUpReadln() { if (_inputReaderThread != null) { lock (ConsoleLock) { //Out.ConsoleCursorPosRestore(); // both works Out.CursorPos = _beginOfLineCurPos; if (CommandLineProcessor.CommandEvaluationContext.ShellEnv.IsOptionSetted(ShellEnvironmentVar.settings_console_enableCompatibilityMode)) { /* 💥 */ // ED p0 clean up screen in ConPty Out.Write(ANSI.EL(ANSI.ELParameter.p0)); // minimum compatible } else { Out.Write(ANSI.ED(ANSI.EDParameter.p0)); // not in compatibility mode ( TODO: check) } _inputReaderStringBuilder.Clear(); } } }
public CommandResult <QueryResultRoot> NugetQuery( CommandEvaluationContext context, [Parameter("the search terms to used to filter packages", true)] string query, [Option("s", "skip", "the number of results to skip, for pagination", true, true)] int skip = -1, [Option("t", "take", "the number of results to return, for pagination", true, true)] int take = -1, [Option("r", "pre-release", "true or false determining whether to include pre-release packages (default no)")] bool preRelease = false, [Option("l", "sem-ver-level", "a SemVer 1.0.0 version string", true, true)] string semVerLevel = "2.0.0", [Option("p", "package-type", "the package type to use to filter packages (added in SearchQueryService/3.5.0)", true, true)] string packageType = null, [Option("u", "query-url", "nuget server api query service template url", true, true)] string url = QueryUrl ) { QueryResultRoot @return = null; query ??= ""; var queryString = url.Replace("{QUERY}", query.Trim()); if (skip > -1) { queryString = queryString.Replace("{SKIP}", skip + ""); } if (take > -1) { queryString = queryString.Replace("{TAKE}", take + ""); } queryString = queryString.Replace("{PRERELEASE}", preRelease.ToString().ToLower()); if (semVerLevel != null) { queryString = queryString.Replace("{SEMVERLEVEL}", semVerLevel); } if (packageType != null) { queryString = queryString.Replace("{PACKAGETYPE}", packageType); } queryString = queryString .Replace("&skip={SKIP}", "") .Replace("&take={TAKE}", "") .Replace("&prerelease={PRERELEASE}", "") .Replace("&semVerLevel={SEMVERLEVEL}", "") .Replace("&packageType={PACKAGETYPE}", ""); context.Out.Echo(context.ShellEnv.Colors.Log + $"GET {queryString} ... "); using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("GET"), queryString); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var res = result.Content.ReadAsStringAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo var obj = JsonConvert.DeserializeObject <QueryResultRoot>(res); @return = obj; if (obj != null && obj.Data != null) { obj.Echo(new EchoEvaluationContext(context.Out, context)); } else { context.Errorln("invalid json"); } } else { context.Errorln($"can't get response content: {result.ReasonPhrase}"); } return(new CommandResult <QueryResultRoot>(@return)); }
public CommandResult <string> NugetPush( CommandEvaluationContext context, [Parameter(0, "package (.nuget) file path")] FilePath pkgFile, [Parameter(1, "target server api key")] string apiKey, [Option("u", "push-url", "nuget server api push service url", true, true)] string url = PushUrl, [Option("p", "protocol-version", "nuget thir party client protocol version", true, true)] string protocolVersion = ProtocolVersion ) { var @return = ""; if (pkgFile.CheckExists(context)) { var ext = Path.GetExtension(pkgFile.FullName); var atExt = ".nupkg"; if (ext.ToLower() != atExt) { context.Errorln($"bad file extension: '{ext}', should be '{atExt}'"); } else { if (string.IsNullOrWhiteSpace(apiKey)) { context.Errorln($"api key is required and can't be empty"); } else { using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("PUT"), url); request.Headers.Add("X-NuGet-ApiKey", apiKey); request.Headers.AcceptEncoding.ParseAdd("gzip,deflate"); request.Headers.Add("X-NuGet-Protocol-Version", protocolVersion); //request.Headers.Add("X-NuGet-Client-Version", "5.8.1"); //request.Headers.Add("user-agent", "NuGet Command Line / 5.8.1 (Microsoft Windows NT 10.0.19042.0)"); var content = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(File.ReadAllBytes(pkgFile.FullName)); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue( "form-data" ) { FileName = "package.nupkg" }; fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); content.Add(fileContent); request.Content = content; context.Out.Echo(context.ShellEnv.Colors.Log + $"PUT {PushUrl} ... "); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var res = result.Content.ReadAsStringAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo @return = res; if (res != null) { if (!string.IsNullOrWhiteSpace(res)) { context.Out.Echoln(res); } } else { context.Warningln("quey result is empty"); } context.Warningln("quey result is empty"); if (result.StatusCode == HttpStatusCode.Created || result.StatusCode == HttpStatusCode.Accepted) { context.Out.Echoln($"package '{Path.GetFileName(pkgFile.FullName)}' has been successfully pushed"); } } else { context.Errorln($"can't get response content: {(int)result.StatusCode} {result.ReasonPhrase}"); } } } } return(new CommandResult <string>(@return)); }
public CommandResult <List <ModuleSpecification> > Module( CommandEvaluationContext context, [Option("l", "load", "load a module from the given path", true, true)] FilePath loadModulePath = null, [Option("n", "unload", "unload the module having the given name ", true, true)] string unloadModuleName = null, [Option("i", "install", "install a module from the nuget source", true, true)] string installModuleName = null, [Option("r", "remove", "uninstall a module and remove the module files", true, true)] string uninstallModuleName = null, [Option("u", "update", "try to update an installed module from the nuget source", true, true)] string updateModuleName = null, [Option("f", "fetch-list", "fetch list of modules from modules repositories", true)] bool fetchList = false, [Option("o", "fetch-info", "query modules repositories about a module name, if found fetch the module and output informations about it. the module is not installed", true, true)] string fetchInfoName = null, [Option("v", "version", "module version if applyable", true, true)] string version = null, [Option("s", "short", "output less informations", true)] bool @short = false, [Option(null, "force", "perform the requested operation even if already done, in case of it is meaningfull (example: -i --force constraint the command to reinstall a module)")] bool force = false ) { ModuleSpecification moduleSpecification = null; var f = context.ShellEnv.Colors.Default.ToString(); bool fetchInfo = fetchInfoName != null; var clog = context.ShellEnv.Colors.Log; var o = context.Out; if (loadModulePath == null && unloadModuleName == null && updateModuleName == null && installModuleName == null && uninstallModuleName == null && !fetchList && !fetchInfo) { // output reports on loaded modules var col1length = context.CommandLineProcessor.ModuleManager.Modules.Values.Select(x => x.Name.Length).Max() + 1; int n = 1; foreach (var kvp in context.CommandLineProcessor.ModuleManager.Modules) { var ver = kvp.Value.Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>()?.InformationalVersion; var af = new FileInfo(kvp.Value.Assembly.Location); var dat = af.CreationTimeUtc.ToString() + " UTC"; var comp = kvp.Value.Assembly.GetCustomAttribute <AssemblyCompanyAttribute>()?.Company; var aut_attr = kvp.Value.Assembly.GetCustomAttribute <ModuleAuthorsAttribute>(); var aut = (aut_attr == null) ? "" : string.Join(",", aut_attr.Auhors); var target = kvp.Value.Assembly.GetCustomAttribute <ModuleTargetPlateformAttribute>()?.TargetPlateform; target ??= TargetPlatform.Unspecified; var deps_attr = kvp.Value.Assembly.GetCustomAttributes <ModuleDependencyAttribute>(); var deps = (deps_attr.Count() == 0) ? "" : string.Join(",", deps_attr.Select(x => x.ModuleName + " " + x.ModuleMinVersion)); var sminv = kvp.Value.Assembly.GetCustomAttribute <ModuleShellMinVersionAttribute>()?.ShellMinVersion; o.Echoln($"{Darkcyan}{kvp.Value.Name.PadRight(col1length, ' ')}{f}{kvp.Value.Description}"); if (!@short) { o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}assembly : (rdc){kvp.Value.Assembly.FullName}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}path : (rdc){kvp.Value.Assembly.Location}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}version : (rdc){ver}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}date : (rdc){dat}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}target : (rdc){target}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}dependencies : (rdc){deps}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}shell min ver: (rdc){sminv}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}company : (rdc){comp}"); o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}authors : (rdc){aut}"); o.Echoln($"{"".PadRight(col1length, ' ')}{kvp.Value.Info.GetDescriptor(context)}"); } else { o.Echoln($"{"".PadRight(col1length, ' ')}{context.ShellEnv.Colors.Label}version : {context.ShellEnv.Colors.HalfDark}{ver} (target {((target == null) ? "" : target + ", ")}created {dat}) {context.ShellEnv.Colors.Label}Company : (rdc){comp} ({aut}) "); } if (n < context.CommandLineProcessor.ModuleManager.Modules.Count) { o.Echoln(); } n++; } return(new CommandResult <List <ModuleSpecification> >(context.CommandLineProcessor.ModuleManager.Modules.Values.ToList())); } if (!fetchList && !fetchInfo) { // install module if (installModuleName != null) { var lastVer = string.IsNullOrWhiteSpace(version); var queryMethod = typeof(NuGetServerApiCommands).GetMethod("NugetQuery"); var r0 = context.CommandLineProcessor.Eval(context, queryMethod, $"{installModuleName} -t 1", 0); if (r0.EvalResultCode != (int)ReturnCode.OK) { return(_ModuleErr(context, r0.ErrorReason)); } var queryRes = r0.Result as QueryResultRoot; if (queryRes == null) { return(_ModuleErr(context, "nuget query return a null result")); } if (queryRes.Data.Length == 0) { return(_ModuleErr(context, "module id unknown")); } var packageId = queryRes.Data[0].Id; o.Echoln(); var getVersMethod = typeof(NuGetServerApiCommands).GetMethod("NugetVer"); var r = context.CommandLineProcessor.Eval(context, getVersMethod, $"{installModuleName}", 0); if (r.EvalResultCode == (int)ReturnCode.OK) { var vers = (PackageVersions)r.Result; if (!lastVer && !vers.Versions.Contains(version)) { return(_ModuleErr(context, $"module version '{version}' not found")); } if (lastVer) { version = vers.Versions.Last(); o.Echoln($"{clog}select the last version of package: {version}(rdc)"); } var dwnMethod = typeof(NuGetServerApiCommands).GetMethod("NugetDownload"); var output = context.CommandLineProcessor.Settings.ModulesFolderPath; var folderName = packageId.ToLower(); var lowerVersion = version.ToLower(); var moduleLowerFullId = $"{folderName}.{lowerVersion}"; // == module lower id if (context.CommandLineProcessor.ModuleManager.IsModuleInstalled( context, folderName, version ) && !force) { // error already installed, !force return(_ModuleErr(context, $"module '{moduleLowerFullId}' is already installed (may try --force)")); } var moduleFolder = Path.Combine(output, folderName); if (!Directory.Exists(moduleFolder)) { Directory.CreateDirectory(moduleFolder); } moduleFolder = FileSystemPath.UnescapePathSeparators(moduleFolder); var rd = context.CommandLineProcessor.Eval(context, dwnMethod, $"{installModuleName} {version} -o {moduleFolder}", 0); if (rd.EvalResultCode == (int)ReturnCode.OK) { o.Echo(clog + "extracting package... "); var versionFolder = Path.Combine(moduleFolder, lowerVersion); if (!Directory.Exists(versionFolder)) { Directory.CreateDirectory(versionFolder); } var nupkgFileName = (string)rd.Result; ZipFile.ExtractToDirectory(Path.Combine(moduleFolder, nupkgFileName), versionFolder, true); o.Echoln(" Done(rdc)"); o.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo // find modules dlls : find {folderName}/{lowerVersion}/lib -p *.dll var findMethod = typeof(FileSystemCommands).GetMethod("Find"); var find = context.CommandLineProcessor.Eval(context, findMethod, $"{folderName}/{lowerVersion}/lib -p *.dll", 0); var nodllmess = "the module doesn't contain any dll in /lib"; if (find.EvalResultCode != (int)ReturnCode.OK) { return(_ModuleErr(context, nodllmess)); } var findResult = ((List <FileSystemPath>, FindCounts))find.Result; foreach (var dll in findResult.Item1) { if (!context.CommandLineProcessor.ModuleManager.IsAssemblyLoaded(dll.FullName)) { // candidate assembly o.Echoln(clog + $"importing dll: '{dll.Name}'"); } } o.Echoln("module installed"); } else { return(_ModuleErr(context, rd.ErrorReason)); } } else { return(_ModuleErr(context, "module id is required")); } } // load/init module if (loadModulePath != null) { if (loadModulePath.CheckExists(context)) { var a = Assembly.LoadFrom(loadModulePath.FileSystemInfo.FullName); moduleSpecification = context.CommandLineProcessor.ModuleManager.RegisterModule(context, a); if (moduleSpecification != null && moduleSpecification.Info != null) { o.Echoln($" Done : {moduleSpecification.Info.GetDescriptor(context)}"); } } else { return(_ModuleErr(null, null)); } } // unload module if (unloadModuleName != null) { if (context.CommandLineProcessor.ModuleManager.Modules.Values.Any(x => x.Name == unloadModuleName)) { moduleSpecification = context.CommandLineProcessor.ModuleManager.UnregisterModule(context, unloadModuleName); if (moduleSpecification != null && moduleSpecification.Info != null) { o.Echoln($"unloaded: {moduleSpecification.Info.GetDescriptor(context)}"); } } else { return(_ModuleErr(context, $"module '{unloadModuleName}' is not registered")); } } } else { // fetch mod repos if (_GetModuleListFromRepositories(context, out var modRefs)) { o.Echo(ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo if (modRefs.Count > 0) { // fetch module info if (fetchInfo) { var modRef = modRefs.Where(x => x.Name == fetchInfoName).FirstOrDefault(); if (modRef != null) { // try to fetch the module : name[,version]->nuget } else { o.Errorln("no module having name '{fetchInfoName}' can be found in repostories"); } } if (fetchList) { // get list var tb = new Table( ("name", typeof(string)), ("version", typeof(ModuleVersion)), ("description", typeof(string)) ); foreach (var modref in modRefs) { tb.AddRow(modref.Name, modref.Version, modref.Description); } tb.Echo(new EchoEvaluationContext( o, context, new TableFormattingOptions( context.ShellEnv.GetValue <TableFormattingOptions>( ShellEnvironmentVar.display_tableFormattingOptions)) { })); } } else { o.Errorln("module repository list doesn't contains any module reference"); } } } if (moduleSpecification != null) { return(new CommandResult <List <ModuleSpecification> >(new List <ModuleSpecification> { moduleSpecification })); } else { return(new CommandResult <List <ModuleSpecification> >(new List <ModuleSpecification> { })); } }