Example #1
0
        public void WriteVariablesToDiskCache(GitVersionCacheKey cacheKey, VersionVariables variablesFromCache)
        {
            var cacheDir      = PrepareCacheDirectory();
            var cacheFileName = GetCacheFileName(cacheKey, cacheDir);

            variablesFromCache.FileName = cacheFileName;

            Dictionary <string, string> dictionary;

            using (log.IndentLog("Creating dictionary"))
            {
                dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
            }

            void WriteCacheOperation()
            {
                using var stream = fileSystem.OpenWrite(cacheFileName);
                using var sw     = new StreamWriter(stream);
                using (log.IndentLog("Storing version variables to cache file " + cacheFileName))
                {
                    var serializer = new Serializer();
                    serializer.Serialize(sw, dictionary);
                }
            }

            var retryOperation = new RetryAction <IOException>(maxRetries: 6);

            retryOperation.Execute(WriteCacheOperation);
        }
        public static void WriteSample(string targetDirectory, IFileSystem fileSystem)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException(nameof(fileSystem));
            }

            var configFilePath = GetConfigFilePath(targetDirectory);

            if (!fileSystem.Exists(configFilePath))
            {
                _logger.Information("Writing sample file to '{ConfigFilePath}'", configFilePath);

                // The following try/finally statements is to ensure that
                // any stream is not disposed more than once.
                Stream stream = null;
                try
                {
                    stream = fileSystem.OpenWrite(configFilePath);
                    using (var writer = new StreamWriter(stream))
                    {
                        stream = null;
                        ConfigSerializer.WriteSample(writer);
                    }
                }
                finally
                {
                    stream?.Dispose();
                }
            }
            else
            {
                _logger.Error("Cannot write sample, '{File}' already exists", configFilePath);
            }
        }
Example #3
0
        /// <summary>
        /// The actual functionality to download with optional hash verification
        /// subclasses that wish to return the contents of the downloaded file
        /// or do something else with it can override this instead of RunWithReturn.
        /// If you do, you must call RaiseOnStart()/RaiseOnEnd()
        /// </summary>
        /// <param name="success"></param>
        /// <returns></returns>
        protected virtual string RunDownload(bool success)
        {
            Exception exception = null;
            var       attempts  = 0;
            bool      result    = false;

            do
            {
                if (Token.IsCancellationRequested)
                {
                    break;
                }

                exception = null;

                try
                {
                    Logger.Trace($"Download of {Url} to {Destination} Attempt {attempts + 1} of {RetryCount + 1}");

                    using (var destinationStream = fileSystem.OpenWrite(Destination, FileMode.Append))
                    {
                        result = Utils.Download(Logger, Url, destinationStream,
                                                (value, total) =>
                        {
                            UpdateProgress(value, total);
                            return(!Token.IsCancellationRequested);
                        });
                    }

                    if (result && ValidationHash != null)
                    {
                        var md5 = fileSystem.CalculateFileMD5(TargetDirectory);
                        result = md5.Equals(ValidationHash, StringComparison.CurrentCultureIgnoreCase);

                        if (!result)
                        {
                            Logger.Warning($"Downloaded MD5 {md5} does not match {ValidationHash}. Deleting {TargetDirectory}.");
                            fileSystem.FileDelete(TargetDirectory);
                        }
                        else
                        {
                            Logger.Trace($"Download confirmed {md5}");
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            } while (attempts++ < RetryCount);

            if (!result)
            {
                Token.ThrowIfCancellationRequested();
                throw new DownloadException("Error downloading file", exception);
            }

            return(Destination);
        }
Example #4
0
        public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache)
        {
            var cacheDir      = PrepareCacheDirectory(gitPreparer);
            var cacheFileName = GetCacheFileName(cacheKey, cacheDir);

            variablesFromCache.FileName = cacheFileName;

            Dictionary <string, string> dictionary;

            using (Logger.IndentLog("Creating dictionary"))
            {
                dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
            }

            Action writeCacheOperation = () =>
            {
                using (var stream = fileSystem.OpenWrite(cacheFileName))
                {
                    using (var sw = new StreamWriter(stream))
                    {
                        using (Logger.IndentLog("Storing version variables to cache file " + cacheFileName))
                        {
                            var serializer = new Serializer();
                            serializer.Serialize(sw, dictionary);
                        }
                    }
                }
            };

            var retryOperation = new OperationWithExponentialBackoff <IOException>(new ThreadSleep(), writeCacheOperation, maxRetries: 6);

            retryOperation.ExecuteAsync().Wait();
        }
Example #5
0
 /// <summary>
 ///     Writes the contents of the given stream from its current position until its end into the file given by
 ///     <paramref name="fileName" />.
 /// </summary>
 /// <remarks>
 ///     This method works similar to <see cref="IFileSystem.WriteAllText" /> and <see cref="IFileSystem.WriteAllBytes" />:
 ///     If no such file exists, it will be created.
 ///     If the file exists, then its contents will be overwritten.
 /// </remarks>
 /// <param name="fileSystem"></param>
 /// <param name="fileName"></param>
 /// <param name="stream"></param>
 public static void WriteAllStream(this IFileSystem fileSystem, string fileName, Stream stream)
 {
     using (var file = fileSystem.OpenWrite(fileName))
     {
         stream.CopyTo(file);
     }
 }
Example #6
0
        protected override Task <bool> SaveData()
        {
            foreach (var tableItem in _dataTables)
            {
                var file = Path.Combine(_loadPath, $"{tableItem.Key}.{_extension}");

                using (var stream = _fileSystem.OpenWrite(file))
                    using (var writer = new StreamWriter(stream))
                    {
                        var csv   = new CsvWriter(writer);
                        var table = tableItem.Value;

                        foreach (var row in table)
                        {
                            foreach (var cell in row)
                            {
                                csv.WriteField(cell);
                            }
                            csv.NextRecord();
                        }
                    }
            }

            return(Task.FromResult(true));
        }
 private async Task WritePageDefinition(IPageViewDefinition viewDefinition, PathInfo fileName)
 {
     using (var stream = new StreamWriter(_fileSystem.OpenWrite(fileName)))
     {
         var value = JsonConvert.SerializeObject(viewDefinition, Formatting.Indented);
         await stream.WriteAsync(value).ConfigureAwait(false);
     }
 }
 private Task Update(object content, PathInfo filePath)
 {
     using (var stream = new StreamWriter(_fileSystem.OpenWrite(filePath)))
     {
         var value = JsonConvert.SerializeObject(content, Formatting.Indented);
         return(stream.WriteAsync(value));
     }
 }
Example #9
0
 private void Save(Dictionary <string, string> data)
 {
     using (var stream = new StreamWriter(_fileSystem.OpenWrite(_fileName)))
     {
         new JsonSerializer {
             Formatting = Formatting.Indented
         }.Serialize(new JsonTextWriter(stream), data);
     }
 }
Example #10
0
        public async Task TestWrite()
        {
            Assert.AreEqual(false, FileSystem.FileExists(TestFileName));

            var completion = new TaskCompletionSource <IFileInfo>();
            await FileSystem.SubscribeAsync(TestFilePattern, info => completion.SetResult(info)).ConfigureAwait(false);

            using (var stream = new StreamWriter(FileSystem.OpenWrite(TestFileName)))
            {
                stream.Write("123456");
            }

            await completion.Task.ConfigureAwait(false);

            Assert.AreEqual(true, FileSystem.FileExists(TestFileName));

            FileSystem.RemoveFile(TestFileName);
        }
Example #11
0
        public void Setup()
        {
            logs       = new Logs();
            fileSystem = A.Fake <IFileSystem>();
            A.CallTo(() => fileSystem.OpenWrite(A <string> ._)).ReturnsLazily(logs.CreateNewStream);
            fileName = "error.log";
            maxSize  = 100;

            sut = new LogFile(fileSystem, fileName, maxSize);
        }
        public async Task TestSubscription()
        {
            Assert.AreEqual(false, FileSystem.FileExists(TestFileName1));

            var c = new TaskCompletionSource <IFileInfo>();

            using (await FileSystem.SubscribeAsync(TestFilePattern, s => c.TrySetResult(s)).ConfigureAwait(false))
            {
                using (var writer = new StreamWriter(FileSystem.OpenWrite(TestFileName1)))
                {
                    writer.BaseStream.SetLength(0);
                    writer.Write("123456789");
                }

                var result = await c.Task.ConfigureAwait(false);

                Assert.AreEqual(TestFileName1.ToString(), Path.GetFileName(result.FilePath.ToString()));
            }
        }
Example #13
0
        private StreamWriter GetFileWriter()
        {
            if (currentWriter == null)
            {
                currentStream = fileSystem.OpenWrite(name);
                currentWriter = new StreamWriter(currentStream)
                {
                    AutoFlush = false
                };
            }

            return(currentWriter);
        }
Example #14
0
        /// <summary>
        /// The actual functionality to download with optional hash verification
        /// subclasses that wish to return the contents of the downloaded file
        /// or do something else with it can override this instead of RunWithReturn.
        /// </summary>
        /// <param name="success"></param>
        /// <returns></returns>
        protected virtual NPath RunDownload(bool success)
        {
            Exception exception   = null;
            var       attempts    = 0;
            bool      result      = false;
            var       partialFile = TargetDirectory.Combine(Filename + ".partial");

            TargetDirectory.EnsureDirectoryExists();
            do
            {
                exception = null;

                if (Token.IsCancellationRequested)
                {
                    break;
                }

                try
                {
                    Logger.Trace($"Download of {Url} to {Destination} Attempt {attempts + 1} of {RetryCount + 1}");

                    using (var destinationStream = fileSystem.OpenWrite(partialFile, FileMode.Append))
                    {
                        result = Downloader.Download(Logger, Url, destinationStream,
                                                     (value, total) =>
                        {
                            UpdateProgress(value, total);
                            return(!Token.IsCancellationRequested);
                        });
                    }

                    if (result)
                    {
                        partialFile.Move(Destination);
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                    result    = false;
                }
            } while (!result && attempts++ < RetryCount);

            if (!result)
            {
                Token.ThrowIfCancellationRequested();
                throw new DownloadException("Error downloading file", exception);
            }

            return(Destination);
        }
        public static void Init(string workingDirectory, IFileSystem fileSystem)
        {
            var configFilePath = GetConfigFilePath(workingDirectory);
            var config = new ConfigInitWizard().Run(Provide(workingDirectory, fileSystem), workingDirectory, fileSystem);
            if (config == null) return;

            using (var stream = fileSystem.OpenWrite(configFilePath))
            using (var writer = new StreamWriter(stream))
            {
                Logger.WriteInfo("Saving config file");
                ConfigSerialiser.Write(config, writer);
                stream.Flush();
            }
        }
        public void Update <T>(T newSettings) where T : ISettings
        {
            var settingsFile = GetSettingPath <T>();

            try
            {
                using var writer       = fileSystem.OpenWrite(settingsFile);
                using var streamWriter = new StreamWriter(writer);
                json.Serialize(streamWriter, newSettings);
            }
            catch (Exception e)
            {
                statusBar.Value.PublishNotification(new PlainNotification(NotificationType.Error, "Error while saving settings: " + e));
            }
        }
        public void Configure(string id, User user)
        {
            var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id);

            try
            {
                _gitCommand.Execute("--version");
            }
            catch (GitCommandException)
            {
                throw new RepositoryConfigurationException(string.Format("Git is not installed."));
            }

            try
            {
                _gitCommand.Execute("status");
            }
            catch (GitCommandException)
            {
                _writer.Write("Git repository is not initialized in this folder. Do you want to initialize it (type \"y\")?");
                if (_reader.ReadLine() != "y")
                {
                    throw new RepositoryConfigurationException("Git repository was not initialized.");
                }

                _gitCommand.Execute("init");
                using (var stream = _fileSystem.OpenWrite(Path.Combine(Directory.GetCurrentDirectory(), ".gitignore")))
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        writer.Write(DefaultGitIgnore);
                    }
                }
                _writer.WriteLine("Git repository was initialized with default .gitignore file.");
            }

            try
            {
                _gitCommand.Execute(string.Format("remote add appharbor {0}", repositoryUrl));

                _writer.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master.");
            }
            catch (GitCommandException)
            {
                throw new RepositoryConfigurationException(
                          string.Format("Couldn't add appharbor repository as a git remote. Repository URL is: {0}.", repositoryUrl));
            }
        }
Example #18
0
        public void Update()
        {
            log.Info("Updating GitVersion_WixVersion.wxi");

            var doc = new XmlDocument();

            doc.LoadXml(GetWixFormatFromVersionVariables());

            var xmlDecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            var root    = doc.DocumentElement;

            doc.InsertBefore(xmlDecl, root);

            using var fs = fileSystem.OpenWrite(WixVersionFile);
            doc.Save(fs);
        }
        public void Execute(VersionVariables variables, WixVersionContext context)
        {
            wixVersionFile = Path.Combine(context.WorkingDirectory, WixVersionFileName);
            log.Info("Updating GitVersion_WixVersion.wxi");

            var doc = new XmlDocument();

            doc.LoadXml(GetWixFormatFromVersionVariables(variables));

            var xmlDecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            var root    = doc.DocumentElement;

            doc.InsertBefore(xmlDecl, root);

            using var fs = fileSystem.OpenWrite(wixVersionFile);
            doc.Save(fs);
        }
Example #20
0
        public int Run()
        {
            try {
                var arguments = Args.Parse <Arguments>(args);
                var writter   = consoleFactory.CreateConsoleWritter(arguments.Colour);

                if (arguments.Help)
                {
                    ArgUsage.GetStyledUsage <Arguments>().Write();
                    return(0);
                }

                if (arguments.Version)
                {
                    writter.WriteInformationLine(Assembly.GetEntryAssembly().GetName().Version.ToString());
                    return(0);
                }

                var consoleFormatter = formatterFactory.CreateConsoleFormatter(arguments.Format, writter);
                var expressionRunner = expressionFactory.CreateExpressionRunner(arguments.DryRun);
                var specRunner       = runnerFactory.CreateSpecificationRunner(arguments.Parrallel, expressionRunner, finder, consoleFormatter);
                var files            = finder.GetSpecificationFiles(arguments.Path, arguments.Pattern);
                var appDomain        = new SpecificationAppDomain(specRunner);
                var results          = new List <ExpressionResult>();

                foreach (var file in files)
                {
                    results.AddRange(appDomain.ExecuteSpecifications(file, arguments.Example));
                }

                consoleFormatter.WriteSummary(results);
                reporter.Write(fileSystem.OpenWrite(arguments.Output), results);

                return(results.HasErrors() ? 1 : 0);
            } catch (ArgException e) {
                var consoleFormatter = consoleFactory.CreateConsoleWritter(false);
                consoleFormatter.WriteInformationLine(e.Message);
                consoleFormatter.WriteLine();
                ArgUsage.GetStyledUsage <Arguments>().Write();
                return(1);
            } catch (Exception e) {
                var consoleFormatter = consoleFactory.CreateConsoleWritter(false);
                consoleFormatter.WriteInformationLine(e.ToString().Trim());
                return(1);
            }
        }
        public static void WriteSample(string gitDirectory, IFileSystem fileSystem)
        {
            var configFilePath = GetConfigFilePath(gitDirectory);

            if (!fileSystem.Exists(configFilePath))
            {
                using (var stream = fileSystem.OpenWrite(configFilePath))
                using (var writer = new StreamWriter(stream))
                {
                    ConfigSerialiser.WriteSample(writer);
                }
            }
            else
            {
                Logger.WriteError("Cannot write sample, GitVersionConfig.yaml already exists");
            }
        }
        public static void WriteSample(string gitDirectory, IFileSystem fileSystem)
        {
            var configFilePath = GetConfigFilePath(gitDirectory);

            if (!fileSystem.Exists(configFilePath))
            {
                using (var stream = fileSystem.OpenWrite(configFilePath))
                    using (var writer = new StreamWriter(stream))
                    {
                        ConfigSerialiser.WriteSample(writer);
                    }
            }
            else
            {
                Logger.WriteError("Cannot write sample, GitVersionConfig.yaml already exists");
            }
        }
Example #23
0
        public void SaveTokens_SavesTokens()
        {
            IFileSystem fileSystem = Substitute.For <IFileSystem>();

            fileSystem.OpenWrite(Arg.Any <string>()).Returns(new MemoryStream());
            OAuthAccessTokens accessTokens = new OAuthAccessTokens
            {
                AccessToken  = "foo",
                RefreshToken = "bar",
                TokenType    = "bundy"
            };

            this.sut = new JsonFileTokenRepository(fileSystem);

            this.sut.SaveTokens(accessTokens);

            fileSystem.ReceivedWithAnyArgs().OpenWrite(default(string));
        }
        public void Update()
        {
            Logger.WriteInfo("Updating GitVersion_WixVersion.wxi");

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(GetWixFormatFromVersionVariables());

            XmlDeclaration xmlDecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            XmlElement     root    = doc.DocumentElement;

            doc.InsertBefore(xmlDecl, root);

            using (var fs = fileSystem.OpenWrite(WIX_VERSION_FILE))
            {
                doc.Save(fs);
            }
        }
        public static void Init(string workingDirectory, IFileSystem fileSystem)
        {
            var configFilePath = GetConfigFilePath(workingDirectory);
            var config         = new ConfigInitWizard().Run(Provide(workingDirectory, fileSystem), workingDirectory, fileSystem);

            if (config == null)
            {
                return;
            }

            using (var stream = fileSystem.OpenWrite(configFilePath))
                using (var writer = new StreamWriter(stream))
                {
                    Logger.WriteInfo("Saving config file");
                    ConfigSerialiser.Write(config, writer);
                    stream.Flush();
                }
        }
Example #26
0
        public void Init(string workingDirectory)
        {
            var configFilePath       = configFileLocator.GetConfigFilePath(workingDirectory);
            var currentConfiguration = Provide(workingDirectory, false);

            var config = configInitWizard.Run(currentConfiguration, workingDirectory);

            if (config == null)
            {
                return;
            }

            using var stream = fileSystem.OpenWrite(configFilePath);
            using var writer = new StreamWriter(stream);
            log.Info("Saving config file");
            ConfigSerializer.Write(config, writer);
            stream.Flush();
        }
        public static void Init(string workingDirectory, IFileSystem fileSystem, IConsole console)
        {
            var configFilePath       = GetConfigFilePath(workingDirectory, fileSystem);
            var currentConfiguration = Provide(workingDirectory, fileSystem, applyDefaults: false);
            var config = new ConfigInitWizard(console, fileSystem).Run(currentConfiguration, workingDirectory);

            if (config == null)
            {
                return;
            }

            using (var stream = fileSystem.OpenWrite(configFilePath))
                using (var writer = new StreamWriter(stream))
                {
                    Logger.WriteInfo("Saving config file");
                    ConfigSerialiser.Write(config, writer);
                    stream.Flush();
                }
        }
Example #28
0
        public BuildEngine(Arguments arguments, IFileSystem fileSystem)
        {
            if (arguments == null)
            {
                throw new ArgumentNullException("arguments");
            }

            if (arguments.MaxCpuCount <= 0 || arguments.MaxCpuCount > 1024)
            {
                throw new BuildException(
                          string.Format(
                              "error MSB1032: Maximum CPU count is not valid. Value must be an integer greater than zero and nore more than 1024.\r\nSwitch: {0}",
                              arguments.MaxCpuCount));
            }

            _fileSystem = fileSystem;
            var buildlogStream = _fileSystem.OpenWrite("buildlog.txt");

            Log = new BuildLog(arguments, buildlogStream, true);
            _csharpProjectParser = new ProjectParser(_fileSystem);
            _solutionParser      = new SolutionParser(_csharpProjectParser);
            _expressionEngine    = new ExpressionEngine.ExpressionEngine(fileSystem);
            _taskEngine          = new TaskEngine.TaskEngine(_expressionEngine, fileSystem);
            _arguments           = arguments;
            if (_arguments.Targets.Count == 0)
            {
                _arguments.Targets.Add(Targets.Build);
            }
            else
            {
                _arguments.Targets.Sort(new TargetComparer());
            }

            _environment = new BuildEnvironment(name: "Build Engine Environment");
            foreach (var property in arguments.Properties)
            {
                _environment.Properties.Add(property.Name, property.Value);
            }

            _buildScript = LoadBuildScript();
        }
Example #29
0
        public void Run(ICommandLine args)
        {
            var files = args.GetFiles();

            foreach (var inFileName in files)
            {
                var outFileName = Path.Combine(
                    Path.GetDirectoryName(inFileName),
                    $"{Path.GetFileNameWithoutExtension(inFileName)} (converted).fst");

                using (var inStream = _fileSystem.OpenRead(inFileName))
                    using (var outStream = _fileSystem.OpenWrite(outFileName))
                    {
                        var inFlWasp   = _fstPresetStreamer.Read(inStream);
                        var preset     = _waspPresetConverter.DecodeFlWasp(inFlWasp);
                        var outVstWasp = _waspPresetConverter.EncodeVstWasp(preset);
                        _fstPresetStreamer.Write(outStream, outVstWasp);
                        outStream.Flush();
                    }
            }
        }
Example #30
0
        public void Run(TextWriter log, Args args)
        {
            var outFolder = _argResolver.GetOutputDirectory(args);
            var files     = _argResolver.GetInputFiles(args).ToArray();

            Iteration.ForEach(files, file =>
            {
                var fileName       = Path.GetFileNameWithoutExtension(file);
                using var inStream = _fileSystem.OpenRead(file);
                var xwbSounds      = _xwbStreamReader.Read(inStream).ToArray();
                Iteration.ForEach(xwbSounds, xwbSound =>
                {
                    var decoded = _xwbDecoder.Decode(xwbSound);
                    var riff    = _riffPcm16SoundEncoder.Encode(decoded);
                    var outPath = Path.Combine(outFolder, fileName,
                                               _fileSystem.GetSafeFileName(xwbSound.Name) + ".wav");
                    using var outStream = _fileSystem.OpenWrite(outPath);
                    _riffStreamWriter.Write(outStream, riff);
                    outStream.Flush();
                });
            });
        }
Example #31
0
        private void UnpackArchiveEntry(IArchiveEntry archiveEntry, string zipArchiveName)
        {
            var outputPath = Path.Combine(importFolderConfiguration.InitialFolder, archiveEntry.Name);

            Console.WriteLine(outputPath);
            try
            {
                using (var outputStream = fileSystem.OpenWrite(outputPath))
                {
                    var archiveStream = archiveEntry.GetStream();

                    StreamUtil.CopyAndClose(archiveStream, outputStream);
                }

                CreateDoneFileForUnpackedFile(Path.ChangeExtension(outputPath, doneFileExtension));
            }
            catch (Exception exception)
            {
                Console.WriteLine(string.Format("Error during archive entry unpack. Archive {0}, entry{1}", zipArchiveName,
                                                archiveEntry.Name), exception);
            }
        }
        public static void WriteSample(string targetDirectory, IFileSystem fileSystem)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException(nameof(fileSystem));
            }

            var configFilePath = GetConfigFilePath(targetDirectory);

            if (!fileSystem.Exists(configFilePath))
            {
                using (var stream = fileSystem.OpenWrite(configFilePath))
                    using (var writer = new StreamWriter(stream))
                    {
                        ConfigSerializer.WriteSample(writer);
                    }
            }
            else
            {
                Logger.WriteError("Cannot write sample, GitReleaseManager.yaml already exists");
            }
        }
        public static void WriteSample(string targetDirectory, IFileSystem fileSystem)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }

            var configFilePath = GetConfigFilePath(targetDirectory);

            if (!fileSystem.Exists(configFilePath))
            {
                using (var stream = fileSystem.OpenWrite(configFilePath))
                using (var writer = new StreamWriter(stream))
                {
                    ConfigSerializer.WriteSample(writer);
                }
            }
            else
            {
                Logger.WriteError("Cannot write sample, GitReleaseManager.yaml already exists");
            }
        }
        public static void Init(string workingDirectory, IFileSystem fileSystem, IConsole console)
        {
            var configFilePath = GetConfigFilePath(workingDirectory);
            var currentConfiguration = Provide(workingDirectory, fileSystem, applyDefaults: false);
            var config = new ConfigInitWizard(console, fileSystem).Run(currentConfiguration, workingDirectory);
            if (config == null) return;

            using (var stream = fileSystem.OpenWrite(configFilePath))
            using (var writer = new StreamWriter(stream))
            {
                Logger.WriteInfo("Saving config file");
                ConfigSerialiser.Write(config, writer);
                stream.Flush();
            }
        }