Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

check for error/bugs using CounterStrikeSharp.API.Core; using…

  1. User

    check for error/bugs

    using CounterStrikeSharp.API.Core; using Microsoft.Extensions.Logging;

    namespace RemoveOldFiles;

    public class RemoveOldFilesPlugin : BasePlugin, IPluginConfig { public override string ModuleName => "RemoveOldFiles"; public override string ModuleVersion => "1.0"; public override string ModuleAuthor => "Muinez"; public DeletionConfig Config { get; set; } = null!;

    public override void Load(bool hotReload)
    {
        RegisterListener<Listeners.OnMapStart>(OnMapStart);
    }
    
    private void OnMapStart(string map)
    {
        var time = DateTimeOffset.Now.ToUnixTimeSeconds();
    
        foreach (var config in Config.Directories)
        {
            if (!Directory.Exists(config.Path))
            {
                Logger.LogWarning("Directory doesn't exist: {path}", config.Path);
                continue;
            }
    
            var deleteCount = 0;
            foreach (var filePath in Directory.EnumerateFiles(config.Path, config.Filter))
            {
                var fileInfo = new FileInfo(filePath);
    
                if (time - new DateTimeOffset(fileInfo.LastWriteTime).ToUnixTimeSeconds() > config.MaxFileTimeSeconds)
                {
                    File.Delete(fileInfo.FullName);
                    deleteCount++;
                }
            }
    
            Logger.LogInformation("Deleted {deleteCount} files", deleteCount);
        }
    }
    
    public void OnConfigParsed(DeletionConfig deletionConfig)
    {
        Config = deletionConfig;
    }
    

    }

    public class DeletionConfig : IBasePluginConfig { public int Version { get; set; }

    public List<DirectoryConfig> Directories { get; set; } = new()
    {
        new()
        {
            Path = "/csgo/logs",
            Filter = "*.log",
            MaxFileTimeSeconds = 86400 * 7
        }
    };
    

    }

    public class DirectoryConfig { public string Path { get; set; } public string Filter { get; set; } public int MaxFileTimeSeconds { get; set; } }

  2. Assistant

    Your plugin code looks mostly correct, but I'll highlight a few issues and suggestions:

    1. Namespace Naming Conventions: Ensure that your namespace follows the standard naming conventions. Namespaces are typically PascalCase.

      namespace RemoveOldFiles; // This is fine, but just a reminder.
      
    2. Nullability Warning: You are initializing the Config property with null!, which bypasses null-checks. While you set it using OnConfigParsed, it's a good practice to avoid this if possible. Consider initializing it properly or ensuring null safety checks.

    3. Logging Dependency: Ensure that the Logger instance is initialized properly in the base class BasePlugin. The logging functions like Logger.LogWarning and Logger.LogInformation are dependent on this.

    4. Directory.Delete: When deleting a file, you might want to handle exceptions to log any issues during deletion, such as lack of permissions or file locks.

    5. Plugin Registration and Configuration: Make sure your plugin registration system calls Load and OnConfigParsed in the right order. This will ensure Config is not null when used in OnMapStart.

    6. Unknown RegisterListener method: Without seeing the implementation of RegisterListener, ensure it exists in the BasePlugin and works as expected for your Listeners.OnMapStart event.

    Here's the modified code with these considerations:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using CounterStrikeSharp.API.Core;
    using Microsoft.Extensions.Logging;
    
    namespace RemoveOldFiles
    {
        public class RemoveOldFilesPlugin : BasePlugin, IPluginConfig<DeletionConfig>
        {
            public override string ModuleName => "RemoveOldFiles";
            public override string ModuleVersion => "1.0";
            public override string ModuleAuthor => "Muinez";
            public DeletionConfig Config { get; set; } = new DeletionConfig();
    
            public override void Load(bool hotReload)
            {
                RegisterListener<Listeners.OnMapStart>(OnMapStart);
            }
    
            private void OnMapStart(string map)
            {
                var time = DateTimeOffset.Now.ToUnixTimeSeconds();
    
                foreach (var config in Config.Directories)
                {
                    if (!Directory.Exists(config.Path))
                    {
                        Logger.LogWarning("Directory doesn't exist: {path}", config.Path);
                        continue;
                    }
    
                    var deleteCount = 0;
                    foreach (var filePath in Directory.EnumerateFiles(config.Path, config.Filter))
                    {
                        var fileInfo = new FileInfo(filePath);
    
                        if (time - new DateTimeOffset(fileInfo.LastWriteTime).ToUnixTimeSeconds() > config.MaxFileTimeSeconds)
                        {
                            try
                            {
                                File.Delete(fileInfo.FullName);
                                deleteCount++;
                            }
                            catch (Exception ex)
                            {
                                Logger.LogError(ex, "Failed to delete file: {filePath}", fileInfo.FullName);
                            }
                        }
                    }
    
                    Logger.LogInformation("Deleted {deleteCount} files from {path}", deleteCount, config.Path);
                }
            }
    
            public void OnConfigParsed(DeletionConfig deletionConfig)
            {
                Config = deletionConfig ?? throw new ArgumentNullException(nameof(deletionConfig));
            }
        }
    
        public class DeletionConfig : IBasePluginConfig
        {
            public int Version { get; set; }
    
            public List<DirectoryConfig> Directories { get; set; } = new()
            {
                new()
                {
                    Path = "/csgo/logs",
                    Filter = "*.log",
                    MaxFileTimeSeconds = 86400 * 7
                }
            };
        }
    
        public class DirectoryConfig
        {
            public string Path { get; set; } = string.Empty;
            public string Filter { get; set; } = "*.*";
            public int MaxFileTimeSeconds { get; set; }
        }
    }
    

    Key Changes:

    1. Removed null! from Config initialization to avoid nullability bypass issues.
    2. Added exception handling to File.Delete for better logging and fault tolerance.
    3. Updated logging message in Logger.LogInformation to include directory path for more context.
    4. Added a null check in the OnConfigParsed method to ensure the configuration object is not null.

    These changes should help in making your plugin more robust and easier to troubleshoot if something goes wrong.