<commit_before>﻿using Rareform.Validation;
using System.Collections.Generic;
using System.IO;

namespace Espera.Core.Management
{
    public class LibraryFileWriter : ILibraryWriter
    {
        private readonly string targetPath;

        public LibraryFileWriter(string targetPath)
        {
            if (targetPath == null)
                Throw.ArgumentNullException(() => targetPath);

            this.targetPath = targetPath;
        }

        public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath)
        {
            using (FileStream targetStream = File.Create(this.targetPath))
            {
                LibraryWriter.Write(songs, playlists, songSourcePath, targetStream);
            }
        }
    }
}<commit_msg>Create a temporary library file and rename it to reduce the chance of library corruption<commit_after>﻿using Rareform.Validation;
using System;
using System.Collections.Generic;
using System.IO;

namespace Espera.Core.Management
{
    public class LibraryFileWriter : ILibraryWriter
    {
        private readonly string targetPath;

        public LibraryFileWriter(string targetPath)
        {
            if (targetPath == null)
                Throw.ArgumentNullException(() => targetPath);

            this.targetPath = targetPath;
        }

        public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath)
        {
            // Create a temporary file, write the library it, then delete the original library file
            // and rename our new one. This ensures that there is a minimum possibility of things
            // going wrong, for example if the process is killed mid-writing.
            string tempFilePath = Path.Combine(Path.GetDirectoryName(this.targetPath), Guid.NewGuid().ToString());

            using (FileStream targetStream = File.Create(tempFilePath))
            {
                LibraryWriter.Write(songs, playlists, songSourcePath, targetStream);
            }

            File.Delete(this.targetPath);
            File.Move(tempFilePath, this.targetPath);
        }
    }
}
{'fraction_non_alphanumeric': 0.0777105630525826, 'fraction_numerical': 0.0, 'mean_word_length': 2.467741935483871, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5038308', 'n_tokens_mistral': 533, 'n_tokens_neox': 512, 'n_words': 146}