public override Task <object> ExecuteAsync(CancellationToken cancellationToken)
            {
                this.SetProgress(cancellationToken, "ensuring target directory exists");
                DirectoryEx.Create(this.TargetRootPath);

                int index = 0;

                if (this.DeleteExtra)
                {
                    this.SetProgress(cancellationToken, "checking existing files");
                    var remoteFileList = DirectoryEx.GetFileSystemInfos(this.TargetRootPath, MaskingContext.IncludeAll);

                    foreach (var file in remoteFileList)
                    {
                        index++;
                        this.SetProgress(cancellationToken, "checking existing files", 100 * index / remoteFileList.Count);

                        var relativeName = file.FullName.Substring(this.TargetRootPath.Length).Replace('\\', '/').Trim('/');
                        if (file is SlimDirectoryInfo)
                        {
                            if (!this.ExpectedDirectories.Contains(relativeName))
                            {
                                this.LogDebug("Deleting extra directory: " + relativeName);
                                DirectoryEx.Delete(file.FullName);
                            }
                        }
                        else
                        {
                            if (!this.ExpectedFiles.Contains(relativeName))
                            {
                                this.LogDebug($"Deleting extra file: " + relativeName);
                                FileEx.Delete(file.FullName);
                            }
                        }
                    }
                }

                index = 0;
                foreach (var relativeName in this.ExpectedDirectories)
                {
                    index++;
                    this.SetProgress(cancellationToken, "ensuring target subdirectories exist", 100 * index / this.ExpectedDirectories.Length);

                    DirectoryEx.Create(PathEx.Combine(Path.DirectorySeparatorChar, this.TargetRootPath, relativeName));
                }

                index = 0;
                foreach (var relativeName in this.ExpectedFiles)
                {
                    var sourcePath = PathEx.Combine(PathEx.Combine(Path.DirectorySeparatorChar, this.TempDirectoryName, "package"), relativeName);
                    var targetPath = PathEx.Combine(Path.DirectorySeparatorChar, this.TargetRootPath, relativeName);

                    index++;
                    this.SetProgress(cancellationToken, "moving files to target directory", 100 * index / this.ExpectedFiles.Length);

                    FileEx.Move(sourcePath, targetPath, true);
                }

                return(InedoLib.NullTask);
            }
Exemplo n.º 2
0
 protected override void OnDoWork(object sender, DoWorkEventArgs e)
 {
     FileEx.Delete(this._zipPath);
     using (ZipFile zipFiles = new ZipFile(this._zipPath))
     {
         zipFiles.AddFiles(
             from f in this._modPack.Files
             select f.FilePath, string.Empty);
         zipFiles.CompressionLevel = CompressionLevel.BestCompression;
         zipFiles.SaveProgress    += new EventHandler <SaveProgressEventArgs>(this.SaveProgress);
         zipFiles.Save(this._zipPath);
     }
 }
Exemplo n.º 3
0
 public void SaveChanges()
 {
     if (!this.Enabled)
     {
         FileEx.Delete(this.FilePath);
         return;
     }
     if (this.Action != ModFile.Actions.AddOrReplace || !File.Exists(this._newFilePath))
     {
         return;
     }
     File.Copy(this._newFilePath, this.OriginalFilePath, true);
     this.Cancel();
 }
Exemplo n.º 4
0
 public static void BlockLogs()
 {
     foreach (string str in Paths.Elsword.LogFiles.Where <string>((string logFile) => {
         if (!PathEx.Exists(logFile))
         {
             return(true);
         }
         return(!PathEx.IsDirectory(logFile));
     }))
     {
         FileEx.Delete(str);
         Directory.CreateDirectory(str).Attributes = FileAttributes.ReadOnly | FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory;
     }
 }
Exemplo n.º 5
0
        public void StartDownload(bool force = false)
        {
            DownloadStarted = false;
            if (Transfer.IsBusy)
            {
                if (!force)
                {
                    return;
                }
                Transfer.CancelAsync();
            }
            for (var i = 0; i < SrcData.Count; i++)
            {
                var(item1, item2, item3, item4) = SrcData[i];
                if (item4)
                {
                    continue;
                }
                if (!FileEx.Delete(DestPath))
                {
                    throw new InvalidOperationException();
                }

                SrcData[i] = Tuple.Create(item1, item2, item3, true);
                var userAgent = item3;
                if (!NetEx.FileIsAvailable(item1, UserData.Item1, UserData.Item2, 60000, userAgent))
                {
                    userAgent = UserAgents.WindowsChrome;
                    if (!NetEx.FileIsAvailable(item1, UserData.Item1, UserData.Item2, 60000, userAgent))
                    {
                        if (Log.DebugMode > 0)
                        {
                            Log.Write($"Transfer: Could not find target '{item1}'.");
                        }
                        continue;
                    }
                }
                if (Log.DebugMode > 0)
                {
                    Log.Write($"Transfer{(!string.IsNullOrEmpty(userAgent) ? $" [{userAgent}]" : string.Empty)}: '{item1}' has been found.");
                }

                Transfer.DownloadFile(item1, DestPath, UserData.Item1, UserData.Item2, true, 60000, userAgent, false);
                DownloadStarted = true;
            }
        }
Exemplo n.º 6
0
        private void Download_Completed(object sender, AsyncCompletedEventArgs e)
        {
            Download userState = (Download)e.UserState;
            bool     error     = e.Error != null;

            if (e.Cancelled || error)
            {
                try
                {
                    FileEx.Delete(userState.Destination);
                }
                catch
                {
                }
                if (e.Cancelled)
                {
                    this.OnDownloadCompleted(sender, new DownloadCompletedArgs(true));
                    return;
                }
                if (error)
                {
                    this.OnDownloadCompleted(sender, new DownloadCompletedArgs(false, e.Error));
                }
                return;
            }
            this._downloadQueue.RemoveAt(0);
            if (this._downloadQueue.All <Download>((Download d) => d.VoicePack != userState.VoicePack))
            {
                this.PacksQueue.RemoveAll <VoicePack>((VoicePack d) => d == userState.VoicePack);
            }
            string filePathWithoutExtension = PathEx.GetFilePathWithoutExtension(userState.Destination);

            FileEx.Move(userState.Destination, filePathWithoutExtension, true);
            if (!this._downloadQueue.Any <Download>())
            {
                this.OnDownloadCompleted(sender, new DownloadCompletedArgs(false));
                return;
            }
            PacksDownloader fileSize = this;

            fileSize._currentBytes = fileSize._currentBytes + userState.FileSize;
            this.StartNext();
        }
        internal static void Postfix(LevelGridGrid __instance)
        {
            if (!Mod.Instance.Config.EnableDeletePlaylistButton)
            {
                return;
            }

            LevelPlaylist playlist = __instance.playlist_;

            LevelPlaylistCompoundData data = playlist.GetComponent <LevelPlaylistCompoundData>();

            if (data && !playlist.IsResourcesPlaylist() && G.Sys.InputManager_.GetKeyUp(InternalResources.Constants.INPUT_DELETE_PLAYLIST))
            {
                MessageBox.Create($"Are you sure you want to remove [u]{playlist.Name_}[/u]?", "DELETE PLAYLIST")
                .SetButtons(MessageButtons.YesNo)
                .OnConfirm(() =>
                {
                    try
                    {
                        FileEx.Delete(data.FilePath);
                        playlist.Destroy();
                        Object.DestroyImmediate(data.gameObject);
                    }
                    catch (System.Exception e)
                    {
                        Mod.Instance.Logger.Exception(e);
                    }
                    finally
                    {
                        G.Sys.MenuPanelManager_.Pop();
                        __instance.levelGridMenu_.CreateEntries();
                    }
                })
                .Show();
            }
        }
        public async Task <string> ImportAsync()
        {
            this.Logger.LogInformation($"Importing artifact \"{this.ArtifactName}\" from TeamCity...");

            if (this.BuildConfigurationId == null)
            {
                if (this.BuildConfigurationName != null && this.ProjectName != null)
                {
                    await SetBuildConfigurationIdFromName().ConfigureAwait(false);
                }
                else
                {
                    throw new ExecutionFailureException("If BuildConfigurationId is not specified directly, a project name and configuration name are required.");
                }
            }

            if (string.IsNullOrEmpty(this.BuildNumber))
            {
                this.Logger.LogDebug("BuildNumber was not specified, using lastSuccessful...");
                this.BuildNumber = "lastSuccessful";
            }

            string relativeUrl = string.Format("repository/download/{0}/{1}/{2}", this.BuildConfigurationId, this.BuildNumber, this.ArtifactName);

            if (!string.IsNullOrEmpty(this.BranchName))
            {
                this.Logger.LogDebug("Branch name was specified: " + this.BranchName);
                relativeUrl += "?branch=" + Uri.EscapeDataString(this.BranchName);
            }

            this.Logger.LogDebug(string.Format("Importing TeamCity artifact \"{0}\" from {1}...", this.ArtifactName, this.ConnectionInfo.GetApiUrl() + relativeUrl));

            string tempFile = null;

            try
            {
                using (var client = new TeamCityWebClient(this.ConnectionInfo))
                {
                    tempFile = Path.GetTempFileName();
                    this.Logger.LogDebug($"Downloading temp file to \"{tempFile}\"...");
                    try
                    {
                        await client.DownloadFileTaskAsync(relativeUrl, tempFile).ConfigureAwait(false);
                    }
                    catch (WebException wex)
                    {
                        var response = wex.Response as HttpWebResponse;
                        if (response != null && response.StatusCode == HttpStatusCode.NotFound)
                        {
                            this.Logger.LogWarning("The TeamCity request returned a 404 - this could mean that the branch name, build number, or build configuration is invalid.");
                        }

                        throw;
                    }
                }

                this.Logger.LogInformation("Importing artifact into BuildMaster...");
                using (var file = File.OpenRead(tempFile))
                {
                    await SDK.CreateArtifactAsync(
                        applicationId : (int)this.Context.ApplicationId,
                        releaseNumber : this.Context.ReleaseNumber,
                        buildNumber : this.Context.BuildNumber,
                        deployableId : this.Context.DeployableId,
                        executionId : this.Context.ExecutionId,
                        artifactName : TrimWhitespaceAndZipExtension(this.ArtifactName),
                        artifactData : file,
                        overwrite : true
                        );
                }
            }
            finally
            {
                if (tempFile != null)
                {
                    this.Logger.LogDebug("Removing temp file...");
                    FileEx.Delete(tempFile);
                }
            }

            this.Logger.LogInformation(this.ArtifactName + " artifact imported.");

            return(await this.GetActualBuildNumber().ConfigureAwait(false));
        }
Exemplo n.º 9
0
        public async Task <string> ImportAsync()
        {
            this.Logger.LogInformation($"Importing artifact \"{this.ArtifactName}\" from Jenkins...");

            string zipFileName        = null;
            string jenkinsBuildNumber = await this.ResolveJenkinsBuildNumber().ConfigureAwait(false);

            if (string.IsNullOrEmpty(jenkinsBuildNumber))
            {
                this.Logger.LogError($"An error occurred attempting to resolve Jenkins build number \"{this.BuildNumber}\". "
                                     + $"This can mean that the special build type was not found, there are no builds for job \"{this.JobName}\", "
                                     + "or that the job was not found or is disabled."
                                     );

                return(null);
            }

            try
            {
                this.Logger.LogInformation($"Importing {this.ArtifactName} from {this.JobName}...");
                var client = new JenkinsClient(this.ConnectionInfo, this.Logger);

                zipFileName = Path.GetTempFileName();
                this.Logger.LogDebug("Temp file: " + zipFileName);

                this.Logger.LogDebug("Downloading artifact...");
                await client.DownloadArtifactAsync(this.JobName, jenkinsBuildNumber, zipFileName).ConfigureAwait(false);

                this.Logger.LogInformation("Artifact downloaded.");

                using (var file = FileEx.Open(zipFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    await Artifact.CreateArtifactAsync(
                        (int)this.Context.ApplicationId,
                        this.Context.ReleaseNumber,
                        this.Context.BuildNumber,
                        this.Context.DeployableId,
                        this.Context.ExecutionId,
                        TrimWhitespaceAndZipExtension(this.ArtifactName),
                        file,
                        true
                        ).ConfigureAwait(false);
                }
            }
            finally
            {
                try
                {
                    if (zipFileName != null)
                    {
                        this.Logger.LogDebug("Removing temp file...");
                        FileEx.Delete(zipFileName);
                    }
                }
                catch (Exception ex)
                {
                    this.Logger.LogWarning("Error deleting temp file:" + ex.Message);
                }
            }

            this.Logger.LogInformation(this.ArtifactName + " artifact imported.");

            return(jenkinsBuildNumber);
        }
Exemplo n.º 10
0
 /// <summary>
 ///     Extracts all the <see cref="Image"/>'s from a valid icon file.
 /// </summary>
 /// <param name="path">
 ///     The full path to the icon to be extracted.
 /// </param>
 public static void Extract(string path)
 {
     try
     {
         var file = PathEx.Combine(path);
         if (!File.Exists(file))
         {
             throw new PathNotFoundException(file);
         }
         var dir = Path.GetDirectoryName(file);
         if (string.IsNullOrEmpty(dir))
         {
             throw new ArgumentNullException(nameof(dir));
         }
         var name = Path.GetFileNameWithoutExtension(file);
         if (string.IsNullOrEmpty(name))
         {
             throw new ArgumentNullException(nameof(name));
         }
         dir = Path.Combine(dir, $"{name} sources");
         if (Directory.Exists(dir))
         {
             DirectoryEx.EnumerateFiles(dir, "*.png")?.ForEach(x => FileEx.Delete(x));
         }
         else
         {
             Directory.CreateDirectory(dir);
         }
         var buffer = File.ReadAllBytes(file);
         var length = BitConverter.ToInt16(buffer, 4);
         for (var i = 0; i < length; i++)
         {
             var imageWidth  = buffer[SizeIconDir + SizeIconDirEntry * i];
             var imageHeight = buffer[SizeIconDir + SizeIconDirEntry * i + 1];
             var pixelFormat = (int)BitConverter.ToInt16(buffer, SizeIconDir + SizeIconDirEntry * i + 6);
             var imagePath   = Path.Combine(dir, $"{pixelFormat}@{imageWidth}x{imageHeight}.png");
             if (File.Exists(imagePath))
             {
                 for (var j = 0; j < byte.MaxValue; j++)
                 {
                     if (!File.Exists(imagePath))
                     {
                         break;
                     }
                     imagePath = Path.Combine(dir, $"{pixelFormat}@{imageWidth}x{imageHeight}_{i}.png");
                 }
             }
             var formatSize = BitConverter.ToInt32(buffer, SizeIconDir + SizeIconDirEntry * i + 8);
             var offset     = BitConverter.ToInt32(buffer, SizeIconDir + SizeIconDirEntry * i + 12);
             var ms         = default(MemoryStream);
             try
             {
                 ms = new MemoryStream();
                 using (var bw = new BinaryWriter(ms))
                 {
                     bw.Write(buffer, offset, formatSize);
                     ms.Seek(0, SeekOrigin.Begin);
                     using (var bmp = new Bitmap(ms))
                     {
                         ms = null;
                         bmp.Save(imagePath);
                     }
                 }
             }
             finally
             {
                 ms?.Dispose();
             }
         }
     }
     catch (Exception ex) when(ex.IsCaught())
     {
         Log.Write(ex);
     }
 }
Exemplo n.º 11
0
        private static void SecureOverrides(IReadOnlyDictionary <string, Dictionary <string, string> > regMap, bool elevated = false)
        {
            if (regMap?.Any() != true)
            {
                return;
            }
            var file = PathEx.Combine(Attributes.DataDir, $"Temp\\overwrite-{{{EnvironmentEx.MachineId}}}.reg");

            try
            {
                var dir = Path.GetDirectoryName(file);
                if (string.IsNullOrEmpty(dir))
                {
                    throw new ArgumentNullException(dir);
                }
                DirectoryEx.Create(dir);
                FileEx.Delete(file);
            }
            catch (Exception ex)
            {
                Log.Write(ex);
                return;
            }
            using (var sw = new StreamWriter(file, true, Encoding.GetEncoding(1252)))
            {
                sw.WriteLine("Windows Registry Editor Version 5.00");
                sw.WriteLine();
                foreach (var data in regMap)
                {
                    var section = data.Key;
                    if (!section.ContainsEx('\\'))
                    {
                        continue;
                    }
                    var levels = section.Split('\\');
                    var first  = levels.FirstOrDefault();
                    switch (first?.TrimStart('[', '-'))
                    {
                    case "HKEY_CLASSES_ROOT":
                    case "HKEY_CURRENT_CONFIG":
                    case "HKEY_CURRENT_USER":
                    case "HKEY_LOCAL_MACHINE":
                    case "HKEY_PERFORMANCE_DATA":
                    case "HKEY_USERS":
                        break;

                    case "HKCR":
                        levels[0] = "HKEY_CLASSES_ROOT";
                        break;

                    case "HKCC":
                        levels[0] = "HKEY_CURRENT_CONFIG";
                        break;

                    case "HKCU":
                        levels[0] = "HKEY_CURRENT_USER";
                        break;

                    case "HKLM":
                        levels[0] = "HKEY_LOCAL_MACHINE";
                        break;

                    case "HKPD":
                        levels[0] = "HKEY_PERFORMANCE_DATA";
                        break;

                    case "HKU":
                        levels[0] = "HKEY_USERS";
                        break;

                    default:
                        continue;
                    }
                    if (!first.Equals(levels[0]))
                    {
                        if (first.StartsWithEx("[-", "-"))
                        {
                            levels[0] = $"-{levels[0]}";
                        }
                        section = levels.Join('\\');
                    }
                    if (!section.StartsWith("["))
                    {
                        section = $"[{section}";
                    }
                    if (!section.EndsWith("]"))
                    {
                        section = $"{section}]";
                    }
                    sw.WriteLine(section);
                    if (regMap[data.Key]?.Any() != true)
                    {
                        sw.WriteLine();
                        continue;
                    }
                    foreach (var pair in regMap[data.Key])
                    {
                        var key   = !string.IsNullOrWhiteSpace(pair.Key) && !pair.Key.Equals("@") ? $"\"{pair.Key}\"" : "@";
                        var value = pair.Value;
                        if (string.IsNullOrWhiteSpace(value))
                        {
                            value = "-";
                        }
                        sw.WriteLine($"{key}={value}");
                    }
                    sw.WriteLine();
                }
                sw.WriteLine();
            }
            Reg.ImportFile(file, elevated || Elevation.IsAdministrator);
            ProcessEx.SendHelper.WaitThenDelete(file, 10, Elevation.IsAdministrator);
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Enables/disables the registry key redirection.
        /// </summary>
        /// <param name="option">
        ///     The option that determines whether the redirect will be enabled or disabled.
        /// </param>
        /// <param name="keys">
        ///     The registry keys for redirecting.
        /// </param>
        public static void KeyRedirection(PortalizerActions option, params string[] keys)
        {
            if (keys == null || keys.Length == 0)
            {
                return;
            }
            var backup = PathEx.Combine(Attributes.DataDir, $"Temp\\backup-{{{EnvironmentEx.MachineId}}}.reg");

            switch (option)
            {
            case PortalizerActions.Disable:
                if (keys.Length > 0)
                {
                    Reg.ExportKeys(Attributes.RegFilePath, keys);
                    foreach (var key in keys)
                    {
                        Reg.RemoveSubKey(key);
                    }
                    Reg.RemoveEntry(Attributes.RegPath, nameof(Attributes.RegKeys));
                }
                if (!File.Exists(backup))
                {
                    return;
                }
                Reg.ImportFile(backup);
                FileEx.TryDelete(backup);
                break;

            default:
                if (!Reg.SubKeyExists(Attributes.RegPath))
                {
                    Reg.CreateNewSubKey(Attributes.RegPath);
                }
                if (!Reg.EntryExists(Attributes.RegPath, nameof(Attributes.RegKeys)) && keys.Any(Reg.SubKeyExists))
                {
                    try
                    {
                        var dir = Path.GetDirectoryName(backup);
                        if (string.IsNullOrEmpty(dir))
                        {
                            throw new ArgumentNullException(dir);
                        }
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        FileEx.Delete(backup);
                    }
                    catch (Exception ex)
                    {
                        Log.Write(ex);
                    }
                    if (!File.Exists(backup))
                    {
                        Reg.ExportKeys(backup, keys);
                    }
                    foreach (var key in keys)
                    {
                        Reg.RemoveSubKey(key);
                    }
                }
                Reg.Write(Attributes.RegPath, nameof(Attributes.RegKeys), keys, RegistryValueKind.MultiString);
                if (File.Exists(Attributes.RegFilePath))
                {
                    Reg.ImportFile(Attributes.RegFilePath);
                }
                break;
            }
        }
Exemplo n.º 13
0
 /// <summary>
 ///     Extracts all the files in the specified zip archive to the specified directory on
 ///     the file system.
 /// </summary>
 /// <param name="srcPath">
 ///     The path of the zip archive to extract.
 /// </param>
 /// <param name="destDir">
 ///     The path to the directory to place the extracted files in.
 /// </param>
 /// <param name="delSrcPath">
 ///     true to delete the source archive after extracting; otherwise, false.
 /// </param>
 public static bool Unzip(string srcPath, string destDir, bool delSrcPath = true)
 {
     try
     {
         var src = PathEx.Combine(srcPath);
         if (string.IsNullOrEmpty(src))
         {
             throw new ArgumentNullException(nameof(src));
         }
         if (!File.Exists(src))
         {
             throw new FileNotFoundException();
         }
         var dest = PathEx.Combine(destDir);
         if (string.IsNullOrEmpty(dest))
         {
             throw new ArgumentNullException(nameof(dest));
         }
         using (var archive = ZipFile.OpenRead(src))
             try
             {
                 archive.ExtractToDirectory(dest);
             }
             catch
             {
                 foreach (var ent in archive.Entries)
                 {
                     try
                     {
                         var entPath  = ent.FullName;
                         var entIsDir = entPath.EndsWithEx(Path.AltDirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture));
                         entPath = PathEx.Combine(dest, entPath);
                         if (!PathEx.IsValidPath(entPath))
                         {
                             throw new NotSupportedException();
                         }
                         if (entIsDir && !Directory.Exists(entPath))
                         {
                             Directory.CreateDirectory(entPath);
                             continue;
                         }
                         if (ent.Length == 0)
                         {
                             continue;
                         }
                         FileEx.Delete(entPath);
                         var entDir = Path.GetDirectoryName(entPath);
                         if (string.IsNullOrEmpty(entDir))
                         {
                             continue;
                         }
                         if (!Directory.Exists(entDir))
                         {
                             FileEx.Delete(entDir);
                             Directory.CreateDirectory(entDir);
                         }
                         ent.ExtractToFile(entPath, true);
                     }
                     catch (Exception ex) when(ex.IsCaught())
                     {
                         Log.Write(ex);
                     }
                 }
             }
         if (delSrcPath)
         {
             FileEx.TryDelete(src);
         }
         return(true);
     }
     catch (Exception ex) when(ex.IsCaught())
     {
         Log.Write(ex);
         return(false);
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Downloads and imports and artifact from Visual Studio Online.
        /// </summary>
        /// <param name="configurer">The configurer.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="teamProject">The team project.</param>
        /// <param name="buildNumber">The build number.</param>
        /// <param name="artifactId">The artifact identifier.</param>
        public static string DownloadAndImport(TfsConfigurer configurer, ILogger logger, string teamProject, string buildNumber, string buildDefinitionName, ArtifactIdentifier artifactId)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (configurer == null)
            {
                throw new ArgumentNullException("A configurer must be configured or selected in order to import a VS online build.");
            }
            if (string.IsNullOrEmpty(configurer.BaseUrl))
            {
                throw new InvalidOperationException("The base URL property of the TFS configurer must be set to import a VS online build.");
            }

            var api = new TfsRestApi(configurer.BaseUrl, teamProject)
            {
                UserName = string.IsNullOrEmpty(configurer.Domain) ? configurer.UserName : string.Format("{0}\\{1}", configurer.Domain, configurer.UserName),
                Password = configurer.Password
            };

            logger.LogInformation($"Finding last successful build...");
            var buildDefinitions = api.GetBuildDefinitions();

            var buildDefinition = buildDefinitions.FirstOrDefault(b => b.name == buildDefinitionName);

            if (buildDefinition == null)
            {
                throw new InvalidOperationException($"The build definition {buildDefinitionName} could not be found.");
            }

            logger.LogInformation($"Finding {Util.CoalesceStr(buildNumber, "last successful")} build...");

            var builds = api.GetBuilds(
                buildDefinition: buildDefinition.id,
                buildNumber: InedoLib.Util.NullIf(buildNumber, ""),
                resultFilter: "succeeded",
                statusFilter: "completed",
                top: 2
                );

            if (builds.Length == 0)
            {
                throw new InvalidOperationException($"Could not find build number {buildNumber}. Ensure there is a successful, completed build with this number.");
            }

            var build = builds.FirstOrDefault();

            string tempFile = Path.GetTempFileName();

            try
            {
                logger.LogInformation($"Downloading {artifactId.ArtifactName} artifact from VSO...");
                logger.LogDebug("Downloading artifact file to: " + tempFile);
                api.DownloadArtifact(build.id, artifactId.ArtifactName, tempFile);
                logger.LogInformation("Artifact file downloaded from VSO, importing into BuildMaster artifact library...");

                using (var stream = FileEx.Open(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    ArtifactBuilder.ImportZip(artifactId, stream);
                }

                logger.LogInformation($"{artifactId.ArtifactName} artifact imported.");

                return(build.buildNumber);
            }
            finally
            {
                if (tempFile != null)
                {
                    FileEx.Delete(tempFile);
                }
            }
        }
Exemplo n.º 15
0
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var fullPath = context.ResolvePath(this.FileName);

            this.LogInformation($"Changing \"{fullPath}\" package version to {AH.CoalesceString(this.NewVersion, "remove pre-release label")}...");

            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("n"));

            try
            {
                DirectoryEx.Create(tempPath);
                UniversalPackageMetadata currentMetadata;
                using (var upack = new UniversalPackage(fullPath))
                {
                    currentMetadata = upack.GetFullMetadata();
                    await upack.ExtractAllItemsAsync(tempPath, context.CancellationToken);

                    FileEx.Delete(PathEx.Combine(tempPath, "upack.json"));
                }

                var newMetadata = currentMetadata.Clone();
                if (string.IsNullOrEmpty(this.NewVersion))
                {
                    newMetadata.Version = new UniversalPackageVersion(currentMetadata.Version.Major, currentMetadata.Version.Minor, currentMetadata.Version.Patch);
                }
                else
                {
                    newMetadata.Version = UniversalPackageVersion.Parse(this.NewVersion);
                }

                if (currentMetadata.Version == newMetadata.Version)
                {
                    this.LogWarning($"Current package version {currentMetadata.Version} and the new version {newMetadata.Version} are the same; nothing to do.");
                    return(null);
                }

                this.LogInformation("New version: " + newMetadata.Version);

                this.LogDebug("Adding repacking entry...");
                newMetadata.RepackageHistory.Add(
                    new RepackageHistoryEntry
                {
                    Id     = new UniversalPackageId(currentMetadata.Group, currentMetadata.Name) + ":" + currentMetadata.Version,
                    Date   = DateTimeOffset.Now,
                    Using  = SDK.ProductName + "/" + SDK.ProductVersion,
                    Reason = this.Reason
                }
                    );

                using (var builder = new UniversalPackageBuilder(fullPath, newMetadata))
                {
                    await builder.AddRawContentsAsync(tempPath, string.Empty, true, c => true, context.CancellationToken);
                }

                this.LogInformation("Package version changed.");

                return(null);
            }
            finally
            {
                try
                {
                    this.LogDebug($"Deleting temporary files from {tempPath}...");
                    DirectoryEx.Clear(tempPath);
                    DirectoryEx.Delete(tempPath);
                }
                catch (Exception ex)
                {
                    this.LogWarning("Unable to delete temporary files: " + ex.Message);
                }
            }
        }
Exemplo n.º 16
0
        public override void use(ClientPlayerInfo p, string message)
        {
            Match playlistCmdMatch = Regex.Match(message, @"^(\w+) ?(.*)$");

            if (!playlistCmdMatch.Success)
            {
                help(p);
                return;
            }
            MessageUtilities.pushMessageOption(new MessageStateOptionPlayer(p));
            string uniquePlayerString = GeneralUtilities.getUniquePlayerString(p);
            string playlistCmd        = playlistCmdMatch.Groups[1].Value.ToLower();
            string playlistCmdData    = playlistCmdMatch.Groups[2].Value;

            switch (playlistCmd)
            {
            default:
                MessageUtilities.sendMessage($"[A00000]Invalid sub-command `{playlistCmd}`[-]");
                help(p);
                break;

            case "list":
            {
                List <string> playlists = getPlaylists(playlistCmdData);
                var           results   = "";
                foreach (string playlist in playlists)
                {
                    results += "\n" + (playlist == "current" ? playlist : Resource.GetFileNameWithoutExtension(playlist));
                }
                if (results == "")
                {
                    results = "None";
                }
                MessageUtilities.sendMessage("[FFFFFF]Playlists: [-]" + results);
                break;
            }

            case "new":
            {
                LevelPlaylist list = LevelPlaylist.Create(true);
                list.Name_ = "New Playlist";
                FilteredPlaylist levels = new FilteredPlaylist(GeneralUtilities.getAllLevelsAndModes());
                GeneralUtilities.addFiltersToPlaylist(levels, p, playlistCmdData, true);
                list.Playlist_.AddRange(levels.Calculate().levelList);
                selectedPlaylists[uniquePlayerString] = list;
                MessageUtilities.sendMessage("[FFFFFF]New playlist with...[-]");
                MessageUtilities.sendMessage(GeneralUtilities.getPlaylistText(levels, GeneralUtilities.IndexMode.Final, levelFormat));
                break;
            }

            case "load":
            {
                int           matchingCount    = 0;
                LevelPlaylist selectedPlaylist = getPlaylistLevels(playlistCmdData, out matchingCount, getActivePlaylist(p));
                if (matchingCount == 0)
                {
                    MessageUtilities.sendMessage("[A00000]Could not find any playlists with that search[-]");
                    break;
                }
                else if (matchingCount == 1)
                {
                    MessageUtilities.sendMessage($"{selectedPlaylist.Name_} is now active");
                }
                else
                {
                    MessageUtilities.sendMessage($"{selectedPlaylist.Name_} is now active, but {matchingCount - 1} others matched too");
                }

                selectedPlaylists[uniquePlayerString] = selectedPlaylist;
                break;
            }

            case "save":
            {
                LevelPlaylist selectedPlaylist;
                if (!selectedPlaylists.TryGetValue(uniquePlayerString, out selectedPlaylist))
                {
                    MessageUtilities.sendMessage("[A00000]You have no active playlist[-]");
                    break;
                }
                if (selectedPlaylist.Playlist_.Count == 0)
                {
                    MessageUtilities.sendMessage("[A00000]Your active playlist is empty[-]");
                    break;
                }
                if (playlistCmdData == "")
                {
                    MessageUtilities.sendMessage($"[A05000]No name given. Using existing name: {selectedPlaylist.Name_}");
                    playlistCmdData = selectedPlaylist.Name_;
                }
                bool result = savePlaylist(selectedPlaylist, playlistCmdData);
                switch (playlistCmdData)
                {
                case "current":
                    if (result)
                    {
                        MessageUtilities.sendMessage("Set current playlist to active playlist.");
                    }
                    else
                    {
                        MessageUtilities.sendMessage("You cannot save to the current playlist right now.");
                    }
                    break;

                case "upcoming":
                    if (result)
                    {
                        MessageUtilities.sendMessage("Set upcoming levels to active playlist.");
                    }
                    else
                    {
                        MessageUtilities.sendMessage("You cannot save to the current playlist right now.");
                    }
                    break;

                case "active":
                    MessageUtilities.sendMessage("No changes made.");
                    break;

                default:
                    selectedPlaylist.Name_ = playlistCmdData;
                    MessageUtilities.sendMessage($"Saved playlist as {playlistCmdData}.");
                    break;
                }
                break;
            }

            case "active":
            {
                LevelPlaylist selectedPlaylist;
                if (!selectedPlaylists.TryGetValue(uniquePlayerString, out selectedPlaylist))
                {
                    MessageUtilities.sendMessage("[A00000]You have no active playlist[-]");
                    break;
                }
                MessageUtilities.sendMessage(selectedPlaylist.Name_);
                break;
            }

            case "del":
            {
                if (playlistCmdData == "")
                {
                    MessageUtilities.sendMessage("[A00000]You must enter a name[-]");
                    break;
                }
                List <string> toDelete;
                var           count = 0;
                if (deleteConfirmation.TryGetValue(uniquePlayerString, out toDelete))
                {
                    if (playlistCmdData.ToLower() == "yes")
                    {
                        foreach (string playlist in toDelete)
                        {
                            FileEx.Delete(playlist);
                            count++;
                        }
                        MessageUtilities.sendMessage($"Deleted {count} playlists.");
                        deleteConfirmation.Remove(uniquePlayerString);
                        break;
                    }
                    else if (playlistCmdData.ToLower() == "no")
                    {
                        deleteConfirmation.Remove(uniquePlayerString);
                        MessageUtilities.sendMessage("Cancelled deletion.");
                        break;
                    }
                }
                var           searchRegex = GeneralUtilities.getSearchRegex(playlistCmdData);
                List <string> playlists   = GeneralUtilities.playlists();
                playlists.RemoveAll((string s) => !Resource.FileExist(s));
                toDelete = new List <string>();
                var results = "";
                foreach (string playlist in playlists)
                {
                    if (Regex.IsMatch(playlist == "current" ? playlist : Resource.GetFileNameWithoutExtension(playlist), searchRegex, RegexOptions.IgnoreCase))
                    {
                        toDelete.Add(playlist);
                        results += "\n" + (playlist == "current" ? playlist : Resource.GetFileNameWithoutExtension(playlist));
                        count++;
                    }
                }
                if (count > 0)
                {
                    deleteConfirmation[uniquePlayerString] = toDelete;
                    MessageUtilities.sendMessage($"[FFFFFF]Use [A05000]!playlist del yes[-] to delete {count} playlists:[-] {results}");
                }
                else
                {
                    MessageUtilities.sendMessage("[A00000]No playlists found[-]");
                }
            }
            break;

            case "show":
            {
                LevelPlaylist selectedPlaylist;
                if (!selectedPlaylists.TryGetValue(uniquePlayerString, out selectedPlaylist))
                {
                    MessageUtilities.sendMessage("[A00000]You have no active playlist[-]");
                    break;
                }
                FilteredPlaylist filterer = new FilteredPlaylist(selectedPlaylist.Playlist_);
                GeneralUtilities.addFiltersToPlaylist(filterer, p, playlistCmdData, false);
                MessageUtilities.sendMessage(GeneralUtilities.getPlaylistText(filterer, GeneralUtilities.IndexMode.Initial, levelFormat));
                break;
            }

            case "filter":
            {
                LevelPlaylist selectedPlaylist;
                if (!selectedPlaylists.TryGetValue(uniquePlayerString, out selectedPlaylist))
                {
                    MessageUtilities.sendMessage("[A00000]You have no active playlist[-]");
                    break;
                }
                FilteredPlaylist filterer = new FilteredPlaylist(selectedPlaylist.Playlist_);
                GeneralUtilities.addFiltersToPlaylist(filterer, p, playlistCmdData, false);
                selectedPlaylist.Playlist_.Clear();
                selectedPlaylist.Playlist_.AddRange(filterer.Calculate().levelList);
                MessageUtilities.sendMessage("[FFFFFF]Filtered:[-]");
                MessageUtilities.sendMessage(GeneralUtilities.getPlaylistText(filterer, GeneralUtilities.IndexMode.Final, levelFormat));
                break;
            }

            case "add":
            {
                LevelPlaylist selectedPlaylist;
                if (!selectedPlaylists.TryGetValue(uniquePlayerString, out selectedPlaylist))
                {
                    MessageUtilities.sendMessage("[A00000]You have no active playlist[-]");
                    break;
                }
                FilteredPlaylist filterer = new FilteredPlaylist(GeneralUtilities.getAllLevelsAndModes());
                GeneralUtilities.addFiltersToPlaylist(filterer, p, playlistCmdData, true);
                selectedPlaylist.Playlist_.AddRange(filterer.Calculate().levelList);
                MessageUtilities.sendMessage("[FFFFFF]Added:[-]");
                MessageUtilities.sendMessage(GeneralUtilities.getPlaylistText(filterer, GeneralUtilities.IndexMode.Final, levelFormat));
                break;
            }

            case "clear":
            {
                LevelPlaylist selectedPlaylist;
                if (!selectedPlaylists.TryGetValue(uniquePlayerString, out selectedPlaylist))
                {
                    MessageUtilities.sendMessage("[A00000]You have no active playlist[-]");
                    break;
                }
                selectedPlaylist.Playlist_.Clear();
                MessageUtilities.sendMessage("[FFFFFF]Cleared[-]");
                break;
            }
            }
            MessageUtilities.popMessageOptions();
        }