Exemplo n.º 1
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns>true if successful</returns>
        public override bool Execute()
        {
            if (this.BuildEngine != null)
            {
                Logger = new LogWrapper(Log);
            }
            else
            {
                Logger = new MockTaskLogger();
            }
            string errorCode = "";

            try
            {
                if (string.IsNullOrEmpty(File))
                {
                    errorCode = MessageCodes.ReplaceInFile.EmptyFile;
                    throw new ArgumentNullException(null, $"'{nameof(File)}' is null or empty.");
                }
                FileInfo sourceFile = new FileInfo(File);
                if (!sourceFile.Exists)
                {
                    errorCode = MessageCodes.ReplaceInFile.MissingSource;
                    throw new FileNotFoundException($"File '{sourceFile.FullName}' does not exist.");
                }
                if (string.IsNullOrEmpty(Pattern))
                {
                    errorCode = MessageCodes.ReplaceInFile.EmptyPattern;
                    throw new ArgumentNullException(null, $"{nameof(Pattern)} cannot be null or empty.");
                }
                if (Substitute == null)
                {
                    Substitute = "";
                }
                string fileText = System.IO.File.ReadAllText(sourceFile.FullName);
                if (EscapeBackslash)
                {
                    Substitute = Substitute.Replace(@"\", @"\\");
                }
                Logger.LogMessage(MessageImportance.High, $"Replacing '{Pattern}' with '{Substitute}' in {sourceFile.FullName}");
                fileText = ReplaceText(fileText);
                System.IO.File.WriteAllText(sourceFile.FullName, fileText);
                return(true);
            }
            catch (Exception ex)
            {
                if (string.IsNullOrEmpty(errorCode))
                {
                    errorCode = MessageCodes.ReplaceInFile.ReplaceFailed;
                }
                if (BuildEngine != null)
                {
                    int line   = BuildEngine.LineNumberOfTaskNode;
                    int column = BuildEngine.ColumnNumberOfTaskNode;
                    Logger.LogError(null, errorCode, null, BuildEngine.ProjectFileOfTaskNode, line, column, line, column, $"{GetType().Name} failed - {ex.Message}");
                }
                else
                {
                    Logger.LogError(null, errorCode, null, null, 0, 0, 0, 0, $"Error in {GetType().Name}: {ex.Message}");
                }
                return(false);
            }
        }