static DirectoryFinder()
    {
        dataRoot = FindDataRoot();
        var root = dataRoot;

        DirectoryCleaner.CleanRoot(root);
    }
Exemple #2
0
        private IChromeProcess CreateLocalChrome(Uri uri, bool headless, bool hideScrollBars = false)
        {
            string       path               = Path.GetRandomFileName();
            var          directoryInfo      = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), path));
            var          remoteDebuggingArg = $"--remote-debugging-port={uri.Port}";
            var          userDirectoryArg   = $"--user-data-dir=\"{directoryInfo.FullName}\"";
            const string headlessArg        = "--headless --disable-gpu";
            var          chromeProcessArgs  = new List <string>
            {
                remoteDebuggingArg,
                userDirectoryArg,
                "--bwsi",
                "--no-first-run"
            };

            if (headless)
            {
                chromeProcessArgs.Add(headlessArg);
            }

            if (hideScrollBars)
            {
                chromeProcessArgs.Add("--hide-scrollbars");
            }

            var processStartInfo = new ProcessStartInfo(ChromePath, string.Join(" ", chromeProcessArgs));
            var chromeProcess    = Process.Start(processStartInfo);

            return(new LocalChromeProcess(uri, () => DirectoryCleaner.Delete(directoryInfo), chromeProcess));
        }
        public void CleanProperly()
        {
            using (DirectoryDeleter dd = new DirectoryDeleter(Extensions.GetTempDirectory()))
            {
                // Create 100 temporary files, and change their creation date/time so there's
                // one for each of the last 100 days. Then set a cleaner that deletes
                // files older than 50 days.
                int      count = 100;
                DateTime now   = DateTime.Now;
                for (int i = 0; i < count; ++i)
                {
                    FileInfo fi = new FileInfo(dd.Di.FullName + "\\" + Guid.NewGuid().ToString() + ".txt");
                    using (StreamWriter sw = fi.CreateText())
                    {
                    }
                    fi.CreationTime = fi.LastWriteTime = now - TimeSpan.FromDays(i);
                }

                List <FileInfo> files = new List <FileInfo>(dd.Di.GetFiles());
                Assert.Equal(count, files.Count);

                DateTime         fifty_days_ago = now - TimeSpan.FromDays(50);
                DirectoryCleaner cleaner        = new DirectoryCleaner(dd.Di.FullName, "*.txt");
                cleaner.Clean(r => r.LastWriteTime < fifty_days_ago);

                files = new List <FileInfo>(dd.Di.GetFiles());
                Assert.Equal(count / 2 + 1, files.Count);
            }
        }
Exemple #4
0
        public void DoClean()
        {
            if (IsTimeToClean == false)
            {
                return;
            }
            m_timer.Reset();

            string    msg   = $"Deleting old daily file(s) in {Filename.Directory} older than {DaysToKeep} days";
            Stopwatch watch = Stopwatch.StartNew();

            DirectoryCleaner cleaner = new DirectoryCleaner(Filename.Directory, "*.json");

            cleaner.Clean(fi =>
            {
                int age = (int)((DateTime.Now - fi.CreationTime).TotalDays);
                //log.LogInformation($"{fi.FullName} is {age} days old");
                bool to_delete = age >= DaysToKeep;

                if (to_delete)
                {
                    msg += $"\nDeleting {fi.FullName} -- it is {age} days old";
                }

                return(to_delete);
            });

            msg += $"\n\nDone deleting old daily file(s) -- it took {watch.ElapsedMilliseconds} ms";

            logging.EventLog log = new ApplicationEventLog();
            log.LogInformation(msg);
        }
Exemple #5
0
        private void CleanUpFolders(string installPath)
        {
            var directoryCleaner = new DirectoryCleaner();

            try
            {
                directoryCleaner.Clean(installPath);
            }
            catch (Exception ex)
            {
                WriteWarning("Failed to clean installation path. Clean removal might fail: " + ex.Message);
            }

            try
            {
                directoryCleaner.Clean(InstallationConstants.RabbitMq.ConfigurationPath);
            }
            catch (Exception ex)
            {
                WriteWarning("Failed to clean configuration path. Clean removal might fail: " + ex.Message);
            }

            try
            {
                directoryCleaner.Clean(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RabbitMq"));
            }
            catch (Exception ex)
            {
                WriteWarning("Failed to clean roaming path. Clean removal might fail: " + ex.Message);
            }
        }
Exemple #6
0
        void Init(Func <DbConnection, DbContextOptionsBuilder <TDbContext>, Task> buildTemplate,
                  Func <DbContextOptionsBuilder <TDbContext>, TDbContext> constructInstance,
                  string name,
                  string directory,
                  ushort templateSize,
                  DateTime timestamp)
        {
            Guard.AgainstNull(nameof(buildTemplate), buildTemplate);
            Guard.AgainstNullWhiteSpace(nameof(directory), directory);
            Guard.AgainstNullWhiteSpace(nameof(name), name);
            Guard.AgainstNull(nameof(constructInstance), constructInstance);
            this.constructInstance = constructInstance;

            DirectoryCleaner.CleanInstance(directory);

            Task BuildTemplate(DbConnection connection)
            {
                var builder = DefaultOptionsBuilder.Build <TDbContext>();

                builder.UseSqlServer(connection);
                return(buildTemplate(connection, builder));
            }

            Wrapper = new Wrapper(s => new SqlConnection(s), name, directory, templateSize);

            Wrapper.Start(timestamp, BuildTemplate);
        }
Exemple #7
0
        public static void CleanOldData()
        {
            bool is_time = c_clean_logs_timer.IsTime();

            if (is_time)
            {
                c_clean_logs_timer.Reset();

                string directory = string.Empty;
                lock (c_lock)
                {
                    if (LogFile != null)
                    {
                        directory = LogFile.Directory;
                    }
                }

                if (directory != string.Empty)
                {
                    DirectoryCleaner cleaner = new DirectoryCleaner(directory);
                    cleaner.Clean(fi =>
                    {
                        return((DateTime.Now - fi.LastAccessTime).TotalDays >= Options.keepDays);
                    });
                }
            }
        }
        public IChromeProcess Create(int port, bool headless, string userDirectory = null)
        {
            if (string.IsNullOrEmpty(userDirectory))
            {
                string path = Path.GetRandomFileName();
                userDirectory = Path.Combine(Path.GetTempPath(), path);
            }
            var          directoryInfo      = Directory.CreateDirectory(userDirectory);
            var          remoteDebuggingArg = $"--remote-debugging-port={port}";
            var          userDirectoryArg   = $"--user-data-dir=\"{directoryInfo.FullName}\"";
            const string headlessArg        = "--headless --disable-gpu";
            var          chromeProcessArgs  = new List <string>
            {
                remoteDebuggingArg,
                userDirectoryArg,
                "--bwsi",
                "--no-first-run"
            };

            if (headless)
            {
                chromeProcessArgs.Add(headlessArg);
            }
            var processStartInfo = new ProcessStartInfo(ChromePath, string.Join(" ", chromeProcessArgs));
            var chromeProcess    = Process.Start(processStartInfo);

            string remoteDebuggingUrl = "http://localhost:" + port;

            return(new LocalChromeProcess(new Uri(remoteDebuggingUrl), () => DirectoryCleaner.Delete(directoryInfo), chromeProcess));
        }
    public void FileAtRoot()
    {
        var fileAtRoot = Path.Combine(tempDir, "file.txt");

        File.WriteAllText(fileAtRoot, "content");
        DirectoryCleaner.CleanRoot(tempDir);
        Assert.True(File.Exists(fileAtRoot));
    }
Exemple #10
0
        /// <summary>
        /// Instantiate a <see cref="SqlInstance{TDbContext}"/>.
        /// Should usually be scoped as once instance per appdomain. So all tests use the same instance of <see cref="SqlInstance{TDbContext}"/>.
        /// </summary>
        /// <param name="constructInstance"></param>
        /// <param name="buildTemplate"></param>
        /// <param name="storage">Disk storage convention for where the mdb and the ldf files will be located. Optional.</param>
        /// <param name="timestamp"></param>
        /// <param name="templateSize">The size in MB for the template. Optional.</param>
        /// <param name="existingTemplate">Existing mdb and the ldf files to use when building the template. Optional.</param>
        /// <param name="callback">Callback that is executed after the template database has been created. Optional.</param>
        /// <param name="sqlOptionsBuilder">Passed to <see cref="SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder,string,Action{SqlServerDbContextOptionsBuilder})"/>.</param>
        public SqlInstance(
            ConstructInstance <TDbContext> constructInstance,
            TemplateFromConnection <TDbContext> buildTemplate,
            Storage?storage     = null,
            DateTime?timestamp  = null,
            ushort templateSize = 3,
            ExistingTemplate?existingTemplate = null,
            Callback <TDbContext>?callback    = null,
            Action <SqlServerDbContextOptionsBuilder>?sqlOptionsBuilder = null)
        {
            storage ??= DefaultStorage;
            var resultTimestamp = GetTimestamp(timestamp, buildTemplate);

            Guard.AgainstNull(nameof(buildTemplate), buildTemplate);
            Guard.AgainstNull(nameof(constructInstance), constructInstance);
            Model = BuildModel(constructInstance);
            this.constructInstance = constructInstance;
            this.sqlOptionsBuilder = sqlOptionsBuilder;

            var storageValue = storage.Value;

            DirectoryCleaner.CleanInstance(storageValue.Directory);

            Task BuildTemplate(DbConnection connection)
            {
                var builder = DefaultOptionsBuilder.Build <TDbContext>();

                builder.UseSqlServer(connection, sqlOptionsBuilder);
                return(buildTemplate(connection, builder));
            }

            Func <DbConnection, Task>?wrapperCallback = null;

            if (callback != null)
            {
                wrapperCallback = async connection =>
                {
                    var builder = DefaultOptionsBuilder.Build <TDbContext>();
                    builder.UseSqlServer(connection, sqlOptionsBuilder);
#if NET5_0
                    await using var context = constructInstance(builder);
#else
                    using var context = constructInstance(builder);
#endif
                    await callback(connection, context);
                };
            }

            Wrapper = new(
                s => new SqlConnection(s),
                storageValue.Name,
                storageValue.Directory,
                templateSize,
                existingTemplate,
                wrapperCallback);

            Wrapper.Start(resultTimestamp, BuildTemplate);
        }
    public void EmptyDirAtRoot()
    {
        var dirAtRoot = Path.Combine(tempDir, "Dir");

        Directory.CreateDirectory(dirAtRoot);
        Directory.SetCreationTime(dirAtRoot, DateTime.Now.AddDays(-3));
        DirectoryCleaner.CleanRoot(tempDir);
        Assert.False(Directory.Exists(dirAtRoot));
    }
        public IChromeProcess Create(int port, bool headless)
        {
            string path = System.IO.Path.GetRandomFileName();

            System.IO.DirectoryInfo directoryInfo = System.IO.Directory.CreateDirectory(
                System.IO.Path.Combine(
                    System.IO.Path.GetTempPath(), path)
                );

            string       remoteDebuggingArg = $"--remote-debugging-port={port}";
            string       userDirectoryArg   = $"--user-data-dir=\"{directoryInfo.FullName}\"";
            const string headlessArg        = "--headless --disable-gpu";

            // https://peter.sh/experiments/chromium-command-line-switches/
            System.Collections.Generic.List <string> chromeProcessArgs =
                new System.Collections.Generic.List <string>
            {
                remoteDebuggingArg,
                userDirectoryArg,
                // Indicates that the browser is in "browse without sign-in" (Guest session) mode.
                // Should completely disable extensions, sync and bookmarks.
                "--bwsi",
                "--no-first-run"
            };


            if (false)
            {
                string proxyProtocol = "socks5";
                proxyProtocol = "http";
                proxyProtocol = "https";
                string proxyIP   = "68.183.233.181";
                string proxyPort = "3128";
                string proxyArg  = "--proxy-server=\"" + proxyProtocol + "://" + proxyIP + ":" + proxyPort + "\"";
                chromeProcessArgs.Add(proxyArg);
            }


            if (headless)
            {
                chromeProcessArgs.Add(headlessArg);
            }

            if (IsRoot)
            {
                chromeProcessArgs.Add("--no-sandbox");
            }

            string args = string.Join(" ", chromeProcessArgs);

            System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo(ChromePath, args);
            System.Diagnostics.Process          chromeProcess    = System.Diagnostics.Process.Start(processStartInfo);

            string remoteDebuggingUrl = "http://localhost:" + port;

            return(new LocalChromeProcess(new System.Uri(remoteDebuggingUrl), () => DirectoryCleaner.Delete(directoryInfo), chromeProcess));
        }
        public MainWindow()
        {
            InitializeComponent();
            this.SelectFile.Multiselect = true;
            this.SelectFile.Title       = "Directory cleaner";
            this.ResizeMode             = ResizeMode.NoResize;

            dir_clean   = new DirectoryCleaner();
            DataContext = dir_clean;
        }
    public void NonEmptyDirAtRoot()
    {
        var dirAtRoot = Path.Combine(tempDir, "Dir");

        Directory.CreateDirectory(dirAtRoot);
        var file = Path.Combine(dirAtRoot, "file.txt");

        File.WriteAllText(file, "content");
        DirectoryCleaner.CleanRoot(tempDir);
        Assert.True(Directory.Exists(dirAtRoot));
        Assert.True(File.Exists(file));
    }
        private void CleanUpFolders(string installPath)
        {
            var directoryCleaner = new DirectoryCleaner();

            try
            {
                directoryCleaner.Clean(installPath);
            }
            catch (Exception ex)
            {
                WriteWarning("Failed to clean installation path. Clean removal might fail: " + ex.Message);
            }
        }
    public void CurrentDbFiles()
    {
        var dirAtRoot = Path.Combine(tempDir, "Dir");

        Directory.CreateDirectory(dirAtRoot);
        var mdfFile = Path.Combine(dirAtRoot, "file.mdf");

        File.WriteAllText(mdfFile, "content");
        var ldfFile = Path.Combine(dirAtRoot, "file.ldf");

        File.WriteAllText(ldfFile, "content");
        DirectoryCleaner.CleanRoot(tempDir);
        Assert.True(Directory.Exists(dirAtRoot));
        Assert.True(File.Exists(ldfFile));
        Assert.True(File.Exists(mdfFile));
    }
Exemple #17
0
        public SqlInstance(
            string name,
            Func <DbConnection, Task> buildTemplate,
            string?directory    = null,
            DateTime?timestamp  = null,
            ushort templateSize = 3)
        {
            Guard.AgainstNull(nameof(buildTemplate), buildTemplate);
            Guard.AgainstWhiteSpace(nameof(directory), directory);
            Guard.AgainstNullWhiteSpace(nameof(name), name);
            directory = DirectoryFinder.Find(name);
            DirectoryCleaner.CleanInstance(directory);
            var callingAssembly = Assembly.GetCallingAssembly();
            var resultTimestamp = GetTimestamp(timestamp, buildTemplate, callingAssembly);

            Wrapper = new Wrapper(s => new SqlConnection(s), name, directory, templateSize);
            Wrapper.Start(resultTimestamp, buildTemplate);
        }
    public void OldDbFiles()
    {
        var dirAtRoot = Path.Combine(tempDir, "Dir");

        Directory.CreateDirectory(dirAtRoot);
        var mdfFile = Path.Combine(dirAtRoot, "file.mdf");

        File.WriteAllText(mdfFile, "content");
        File.SetLastWriteTime(mdfFile, DateTime.Now.AddDays(-3));
        var ldfFile = Path.Combine(dirAtRoot, "file.ldf");

        File.WriteAllText(ldfFile, "content");
        File.SetLastWriteTime(ldfFile, DateTime.Now.AddDays(-3));
        Directory.SetCreationTime(dirAtRoot, DateTime.Now.AddDays(-3));
        DirectoryCleaner.CleanRoot(tempDir);
        Assert.False(Directory.Exists(dirAtRoot));
        Assert.False(File.Exists(ldfFile));
        Assert.False(File.Exists(mdfFile));
    }
Exemple #19
0
        public void CleanUp_should_recusively_delete_all_empty_parents()
        {
            var dir1 = Path.Combine(_testRoot, "A");
            var dir2 = Path.Combine(dir1, "B");
            var dir3 = Path.Combine(dir2, "C");
            var dir4 = Path.Combine(dir3, "D");
            var dir5 = Path.Combine(dir4, "E");

            Directory.CreateDirectory(dir5);
            var childFile = Path.Combine(dir1, "aFile");

            File.WriteAllText(childFile, string.Empty);

            int deletes = DirectoryCleaner.CleanUp(dir5);

            Directory.Exists(dir1).Should().Be.True();
            Directory.Exists(dir2).Should().Be.False();
            deletes.Should().Be.EqualTo(4);
        }
        public DirectoryCleanerTests()
        {
            IServiceProvider serviceProvider = new ServiceCollection()
                                               .AddLogging(builder =>
            {
                builder
                .AddDebug()
                .AddSimpleConsole(options =>
                {
                    options.ColorBehavior   = LoggerColorBehavior.Default;
                    options.SingleLine      = true;
                    options.TimestampFormat = "yyyy-MM-dd";
                });
            })
                                               .AddTransient <IFileSystem, FileSystem>()
                                               .AddTransient <DirectoryCleaner>()
                                               .BuildServiceProvider() ?? throw new ArgumentNullException(nameof(serviceProvider));

            directoryCleaner = serviceProvider
                               .GetService <DirectoryCleaner>() ?? throw new ArgumentNullException(nameof(directoryCleaner));
        }
Exemple #21
0
        public SqlInstance(
            ConstructInstance <TDbContext> constructInstance,
            TemplateFromConnection buildTemplate,
            Storage?storage     = null,
            DateTime?timestamp  = null,
            ushort templateSize = 3,
            ExistingTemplate?existingTemplate = null,
            Callback <TDbContext>?callback    = null)
        {
            storage ??= DefaultStorage;

            var resultTimestamp = GetTimestamp(timestamp, buildTemplate);

            Guard.AgainstNull(nameof(constructInstance), constructInstance);
            this.constructInstance = constructInstance;

            var storageValue = storage.Value;

            DirectoryCleaner.CleanInstance(storageValue.Directory);

            Func <DbConnection, Task>?wrapperCallback = null;

            if (callback != null)
            {
                wrapperCallback = async connection =>
                {
                    using var context = constructInstance(connection);
                    await callback(connection, context);
                };
            }
            Wrapper = new(
                s => new SqlConnection(s),
                storageValue.Name,
                storageValue.Directory,
                templateSize,
                existingTemplate,
                wrapperCallback);
            Wrapper.Start(resultTimestamp, connection => buildTemplate(connection));
        }
        public DeploymentService(
            DeployerConfiguration deployerConfiguration,
            ILogger logger,
            [NotNull] IKeyValueConfiguration keyValueConfiguration,
            IWebDeployHelper webDeployHelper,
            Func <DeploymentExecutionDefinition, IIisManager> iisManager,
            NuGetPackageInstaller nugetPackageInstaller,
            IFtpHandlerFactory ftpHandlerFactor)
        {
            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (keyValueConfiguration is null)
            {
                throw new ArgumentNullException(nameof(keyValueConfiguration));
            }

            DeployerConfiguration =
                deployerConfiguration ?? throw new ArgumentNullException(nameof(deployerConfiguration));

            _directoryCleaner = new DirectoryCleaner(logger);

            _packageInstaller = new PackageInstaller(logger, deployerConfiguration, keyValueConfiguration);

            _fileMatcher = new FileMatcher(logger);

            _xmlTransformer = new XmlTransformer(logger, _fileMatcher);

            _logger                = logger;
            _webDeployHelper       = webDeployHelper;
            _iisManager            = iisManager;
            _nugetPackageInstaller = nugetPackageInstaller;
            _ftpHandlerFactory     = ftpHandlerFactor;
        }
Exemple #23
0
        void Init(
            Func <DbConnection, Task> buildTemplate,
            Func <DbConnection, TDbContext> constructInstance,
            string name,
            string directory,
            ushort templateSize,
            DateTime timestamp,
            string?templatePath = null,
            string?logPath      = null)
        {
            Guard.AgainstNullWhiteSpace(nameof(directory), directory);
            Guard.AgainstNullWhiteSpace(nameof(name), name);
            Guard.AgainstNull(nameof(constructInstance), constructInstance);
            this.constructInstance = constructInstance;

            DirectoryCleaner.CleanInstance(directory);
            Task BuildTemplate(DbConnection connection)
            {
                return(buildTemplate(connection));
            }

            Wrapper = new Wrapper(s => new SqlConnection(s), name, directory, templateSize, templatePath, logPath);
            Wrapper.Start(timestamp, BuildTemplate);
        }
Exemple #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="port"></param>
        /// <param name="headless"></param>
        /// <param name="proxyServer">string ip:port (example: 213.226.76.117:8000)</param>
        /// <returns></returns>
        public IChromeProcess Create(int port, bool headless, string proxyServer = null, string path = null, string proxyProtocol = null)
        {
            /*
             * string path = Path.GetRandomFileName();
             * //string path = "1111rfdw111111111111111.dhd";
             * var directoryInfo = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), path));
             * var remoteDebuggingArg = $"--remote-debugging-port={port}";
             * var userDirectoryArg = $"--user-data-dir=\"{directoryInfo.FullName}\"";
             * //string proxyArgs = $"--proxy-server=\"https://213.226.76.117:8000\"";
             *
             *
             * //const string headlessArg = "--disable-gpu";
             * const string headlessArg = "--headless --disable-gpu";
             * var chromeProcessArgs = new List<string>
             * {
             *  remoteDebuggingArg,
             *  userDirectoryArg,
             *  "--bwsi",
             *  "--no-first-run"
             * };
             * if (headless)
             *  chromeProcessArgs.Add(headlessArg);
             * //chromeProcessArgs.Add(proxyArgs);
             * var processStartInfo = new ProcessStartInfo(ChromePath, string.Join(" ", chromeProcessArgs));
             * var chromeProcess = Process.Start(processStartInfo);
             *
             * string remoteDebuggingUrl = "http://localhost:" + port;
             * return new LocalChromeProcess(new Uri(remoteDebuggingUrl), () => DirectoryCleaner.Delete(directoryInfo), chromeProcess);*/

            //if (proxyServer != null)
            //{
            //    if(proxyProcol=="http")
            //    {
            //        proxyArgs = "--proxy-server=http://" + proxyServer;
            //    }

            //    if (proxyProcol == "socks5")
            //    {
            //        proxyArgs = "--proxy-server=socks5://" + proxyServer;
            //        proxyArgs += " --host-resolver-rules=\"MAP * ~NOTFOUND , EXCLUDE "+ proxyServer + "\"";
            //    }
            //}

            if (path == null)
            {
                path = Path.GetRandomFileName();
            }

            DirectoryInfo directoryInfo      = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), path));
            var           remoteDebuggingArg = $"--remote-debugging-port={port}";
            var           userDirectoryArg   = $"--user-data-dir=\"{directoryInfo.FullName}\"";
            const string  headlessArg        = "--headless --disable-gpu";
            const string  sizeArg            = "--window-size=900,640";
            var           chromeProcessArgs  = new List <string>
            {
                remoteDebuggingArg,
                userDirectoryArg,
                sizeArg,
                "--bwsi",
                "--no-first-run"
            };

            if (headless)
            {
                chromeProcessArgs.Add(headlessArg);
            }

            if (proxyServer != null)
            {
                if (proxyProtocol == "http")
                {
                    chromeProcessArgs.Add("--proxy-server=http://" + proxyServer);
                }

                if (proxyProtocol == "socks5")
                {
                    string arg = "--host-resolver-rules=\"MAP * ~NOTFOUND , EXCLUDE " + proxyServer + "\"";
                    chromeProcessArgs.Add("--proxy-server=\"socks5://" + proxyServer + "\"");
                    //chromeProcessArgs.Add(arg);
                    //chromeProcessArgs.Add("--proxy-server=http://" + proxyServer);
                }
            }
            //chromeProcessArgs.Add(extensionsArg);
            var processStartInfo = new ProcessStartInfo(ChromePath, string.Join(" ", chromeProcessArgs));
            var chromeProcess    = Process.Start(processStartInfo);


            string remoteDebuggingUrl = "http://localhost:" + port;

            return(new LocalChromeProcess(new Uri(remoteDebuggingUrl), () => DirectoryCleaner.Delete(directoryInfo), chromeProcess));
        }
 public void Empty()
 {
     DirectoryCleaner.CleanRoot(tempDir);
 }
Exemple #26
0
        private IList <FileInfo> ProcessTtcFonts(Config config, IList <FileInfo> fonts, ProgressBar pb)
        {
            var failureList = new List <FileInfo>();

            if (!fonts.Any())
            {
                return(failureList);
            }

            var tempInputDirectory = Path.Combine(config.InputDirectory, "temp");

            if (!Directory.Exists(tempInputDirectory))
            {
                // Create a temp folder in the input folder
                Directory.CreateDirectory(tempInputDirectory);
            }
            else
            {
                // Clean the temp files
                DirectoryCleaner.CleanDirectoryAsync(tempInputDirectory).Wait();
            }

            // Create a temp folder in the output folder
            var tempOutputDirectory = Path.Combine(config.OutputDirectory, "temp");

            if (!Directory.Exists(tempOutputDirectory))
            {
                // Create a temp folder in the input folder
                Directory.CreateDirectory(tempOutputDirectory);
            }
            else
            {
                // Clean the temp files
                DirectoryCleaner.CleanDirectoryAsync(tempOutputDirectory).Wait();
            }

            pb.StartProcessingTtc();

            foreach (var font in fonts)
            {
                pb.StartProcessingTtc(font.Name);

                // X: & cd {InputDirectory}\temp & call "{AfdkoDirectory}\otc2otf.cmd" "{fontFullname}"
                pb.StartExtractingTtc(font.Name);
                var exitCode =
                    CmdExecutor.ExecuteCommand(
                        $"{tempInputDirectory.Substring(0, 2)} & cd \"{tempInputDirectory}\" & call \"{Path.Combine(config.AfdkoDirectory, "otc2otf.cmd")}\" \"{font.FullName}\"");

                Debug.Assert(exitCode == 0); // TODO
                if (exitCode != 0)
                {
                    failureList.Add(font);
                }
                else
                {
                    pb.StartProcessingExtractedFilesOf(font.Name);
                    var extractedTtfFiles = Directory.GetFiles(tempInputDirectory);
                    Debug.Assert(extractedTtfFiles.Any());
                    var exitCode2 = 0;
                    // Gasphack the extracted TTF files. Note that they should be processed in order of creation time to maintain the same order as the components in the original TTC file.
                    foreach (var extractedTtf in extractedTtfFiles.Select(it => new FileInfo(it)).OrderBy(it => it.CreationTimeUtc))
                    {
                        // X: & cd "{TtxExeDirectory}" & ttx.exe -o "{OutputDirectory}\temp\{fontName}" -m "{InputDirectory}\temp\{fontName}" GaspHack.ttx
                        exitCode2 = CmdExecutor.ExecuteCommand(
                            $"{config.TtxExeDirectory.Substring(0, 2)} & cd \"{config.TtxExeDirectory}\" & ttx.exe -o \"{Path.Combine(tempOutputDirectory, extractedTtf.Name)}\" -m \"{extractedTtf.FullName}\" GaspHack.ttx");
                        Debug.Assert(exitCode2 == 0); // TODO
                        if (exitCode2 != 0)
                        {
                            break;
                        }
                    }

                    if (exitCode2 != 0)
                    {
                        failureList.Add(font);
                    }
                    else
                    {
                        Debug.Assert(Directory.EnumerateFiles(tempOutputDirectory).Any());
                        pb.StartBuildingProcessedTtc(font.Name);
                        // X: & cd "{OutputDirectory}" & call "{AfdkoDirectory}\otf2otc.cmd" -o "{OutputDirectory}\{fontName}" "{OutputDirectory}\temp\1.ttf" "{OutputDirectory}\temp\2.ttf" ...
                        // Note that the input files should be ordered be creation time to maintain the same order as the components in the original TTC file.
                        var command = $"{config.OutputDirectory.Substring(0, 2)} & cd \"{config.OutputDirectory}\" & call \"{Path.Combine(config.AfdkoDirectory, "otf2otc.cmd")}\" -o \"{Path.Combine(config.OutputDirectory, font.Name)}\" ";
                        command = Directory.EnumerateFiles(tempOutputDirectory).Select(it => new FileInfo(it)).OrderBy(it => it.CreationTimeUtc)
                                  .Aggregate(command,
                                             (current, processedExtractedTtf) => current + $"\"{processedExtractedTtf.FullName}\" ");

                        var exitCode3 = CmdExecutor.ExecuteCommand(command);
                        Debug.Assert(exitCode3 == 0); // TODO
                        if (exitCode3 != 0)
                        {
                            failureList.Add(font);
                        }
                    }
                }

                // Clean the temp files
                Task.WaitAll(
                    DirectoryCleaner.CleanDirectoryAsync(tempInputDirectory),
                    DirectoryCleaner.CleanDirectoryAsync(tempOutputDirectory)
                    );
                pb.DoneProcessingTtc(font.Name);
            }

            // Delete the temp folders
            Debug.Assert(!Directory.EnumerateFiles(tempInputDirectory).Any());
            Debug.Assert(!Directory.EnumerateFiles(tempOutputDirectory).Any());
            try
            {
                Directory.Delete(tempInputDirectory);
                Directory.Delete(tempOutputDirectory);
            }
            catch (IOException)
            {
                // Doesn't matter if the temp folder is occupied.
            }

            // # {InputDirectory}\*.ttc should == # {OutputDirectory}\*.ttc + # failure fonts
            Debug.Assert(fonts.Count ==
                         Directory.EnumerateFiles(config.OutputDirectory, "*.*").Count(it => it.ToLowerInvariant().EndsWith(".ttc")) +
                         failureList.Count);

            pb.DoneProcessingTtc();

            return(failureList);
        }