예제 #1
0
        protected override async Task <int> DoExecuteAsync(ITaskContextInternal context)
        {
            var client   = WebApiClientFactory.Create(context.Properties.Get <string>(BuildProps.LastWebApiBaseUrl));
            var response = await client.ExecuteAsync(c => c.UploadPackageAsync(new UploadPackageRequest
            {
                PackageSearchPattern = _packageSearchPattern,
                DirectoryPath        = _directoryPath,
                UploadToSubDirectory = _uploadToSubDirectory,
            }));

            if (response.Error != null)
            {
                throw new TaskExecutionException($"Upload packages failed: ErrorCode: {response.Error.ErrorCode} ErrorMessage: {response.Error.ErrorMessage}", 99);
            }

            if (response.Data == null || response.Data.Count == 0)
            {
                context.LogInfo("No packages uploaded.");
            }
            else
            {
                foreach (var package in response.Data)
                {
                    context.LogInfo($"Uploaded: {package}");
                }
            }

            return(0);
        }
예제 #2
0
        public void LogTargetsHelp(ITaskContextInternal context)
        {
            context.DecreaseDepth();
            context.LogInfo("Targets:");

            // first sort the targets
            var sortedTargets = new SortedList <string, ITargetInternal>();

            foreach (var target in _targets.Values)
            {
                sortedTargets.Add(target.TargetName, target);
            }

            // now display them in sorted order
            foreach (ITargetInternal target in sortedTargets.Values)
            {
                if (target.IsHidden == false)
                {
                    context.LogInfo($"  {target.TargetName} : {target.Description}");
                }
            }

            if (ScriptArgsHelp?.Count > 0)
            {
                context.LogInfo(" ");
                context.LogInfo("Global build script arguments:");
                foreach (var argHelp in ScriptArgsHelp)
                {
                    context.LogInfo($"  {argHelp}");
                }
            }

            context.IncreaseDepth();
        }
예제 #3
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            if (_targetTree == null)
            {
                throw new ArgumentNullException(nameof(_targetTree), "TargetTree must be set before Execution of target.");
            }

            context.LogInfo($"Executing target {TargetName}");

            _targetTree.MarkTargetAsExecuted(this);
            _targetTree.EnsureDependenciesExecuted(context, TargetName);

            if (_args.TargetsToExecute != null)
            {
                if (!_args.TargetsToExecute.Contains(TargetName))
                {
                    throw new TaskExecutionException($"Target {TargetName} is not on the TargetsToExecute list", 3);
                }
            }

            int n = _tasks.Count;
            List <System.Threading.Tasks.Task> tasks = new List <System.Threading.Tasks.Task>();

            for (int i = 0; i < n; i++)
            {
                context.LogInfo($"Executing task {_tasks[i].Item1.GetType().Name}");
                if (_tasks[i].Item2 == TaskExecutionMode.Synchronous)
                {
                    _tasks[i].Item1.ExecuteVoid(context);
                }
                else
                {
                    var i1 = i;
                    tasks.Add(_tasks[i1].Item1.ExecuteVoidAsync(context));
                    if (i + 1 < n)
                    {
                        if (_tasks[i + 1].Item2 != TaskExecutionMode.Synchronous)
                        {
                            continue;
                        }
                        if (tasks.Count <= 0)
                        {
                            continue;
                        }
                        System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
                        tasks = new List <System.Threading.Tasks.Task>();
                    }
                    else
                    {
                        if (tasks.Count > 0)
                        {
                            System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
                        }
                    }
                }
            }

            return(0);
        }
예제 #4
0
        protected override string DoExecute(ITaskContextInternal context)
        {
            if (!File.Exists(_firstFilePathToCompare))
            {
                if (_failOnFileNotFound)
                {
                    throw new TaskExecutionException($"first file not found '{_firstFilePathToCompare}'.", 20);
                }

                context.LogInfo($"first file not found '{_firstFilePathToCompare}'. Skipping compare.");
                return(null);
            }

            if (!File.Exists(_secondFilePathToCompare))
            {
                if (_failOnFileNotFound)
                {
                    throw new TaskExecutionException($"second file not found '{_secondFilePathToCompare}'.", 20);
                }

                context.LogInfo($"second file not found '{_secondFilePathToCompare}'. Skipping compare.");
                return(null);
            }

            string newConfig = File.ReadAllText(_secondFilePathToCompare);

            var oldCOnf          = File.ReadAllText(_firstFilePathToCompare);
            diff_match_patch dmp = new diff_match_patch();

            dmp.Diff_EditCost = 4;
            List <Diff> diff = dmp.diff_main(oldCOnf, newConfig);

            if (diff.Count == 1)
            {
                if (diff[0].operation == Operation.EQUAL)
                {
                    //// Files are the same.
                    return(null);
                }
            }

            dmp.diff_cleanupSemantic(diff);

            var html = dmp.diff_prettyHtml(diff);

            if (!_noExportToFile)
            {
                File.WriteAllText(_htmlReportOutputPath, html);
            }

            if (_failOnDiff)
            {
                throw new TaskExecutionException($"File {_firstFilePathToCompare} and {_secondFilePathToCompare} are not the same", 21);
            }

            return(html);
        }
예제 #5
0
        public virtual void LogTasksHelp(ITaskContextInternal context)
        {
            context.LogInfo("Tasks:");

            IEnumerable <ITask> tasks = _provider.GetServices <ITask>();

            foreach (ITask task in tasks)
            {
                context.LogInfo($"  {task.GetType().FullName}");
            }
        }
예제 #6
0
        public void TargetHelp(ITaskContextInternal context)
        {
            _targetTree.MarkTargetAsExecuted(this);
            context.LogInfo(" ");
            context.LogInfo($"Target {TargetName} will execute next tasks:");

            for (int i = 0; i < _tasks.Count; i++)
            {
                var task = (TaskHelp)_tasks[i].Item1;
                task.LogTaskHelp(context);
            }
        }
예제 #7
0
        private void TasksHelp(ITaskContextInternal context)
        {
            context.LogInfo("Tasks:");

            // first sort the targets
            IEnumerable <ITask> tasks = _provider.GetServices <ITask>();

            // now display them in sorted order
            foreach (ITask task in tasks)
            {
                context.LogInfo($"  {task.GetType().FullName}");
            }
        }
예제 #8
0
        public IPackageDef Process(IPackageDef packageDef)
        {
            StandardPackageDef  zippedPackageDef = new StandardPackageDef();
            List <FileFullPath> filesToZip       = new List <FileFullPath>();

            foreach (IFilesSource childSource in packageDef.ListChildSources())
            {
                if (_sourcesToZip.Contains(childSource.Id))
                {
                    foreach (PackagedFileInfo file in childSource.ListFiles())
                    {
                        if (!LoggingHelper.LogIfFilteredOut(file.FileFullPath.ToString(), _filter, _taskContext, _logFiles))
                        {
                            continue;
                        }

                        if (_logFiles)
                        {
                            _taskContext.LogInfo($"Adding file '{file.FileFullPath}' to zip package");
                        }

                        filesToZip.Add(file.FileFullPath);
                    }
                }
            }

            _zipper.ZipFiles(_zipFileName, _baseDir, filesToZip, _optimizeFiles);

            SingleFileSource singleFileSource = new SingleFileSource("zip", _zipFileName);

            zippedPackageDef.AddFilesSource(singleFileSource);

            return(zippedPackageDef);
        }
예제 #9
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            //// write task logic here.
            context.LogInfo(!string.IsNullOrEmpty(_message) ? _message : "Just some dummy code");

            return(0);
        }
예제 #10
0
        public void ZipFiles(
            FileFullPath zipFileName,
            FullPath baseDir,
            IEnumerable <FileFullPath> filesToZip,
            bool optimizeFiles)
        {
            _taskContext.LogInfo($"Zipping {zipFileName}");
            var zipFileFullPath = zipFileName.ToFullPath();

            if (File.Exists(zipFileFullPath))
            {
                File.Delete(zipFileFullPath);
            }

            List <FileFullPath> tmpList = filesToZip.ToList();

            if (optimizeFiles)
            {
                tmpList = RemoveDuplicateFiles(tmpList, baseDir);
            }

            using (ZipArchive newFile = ZipFile.Open(zipFileFullPath, ZipArchiveMode.Create))
            {
                foreach (FileFullPath fileToZip in tmpList)
                {
                    LocalPath debasedFileName = fileToZip.ToFullPath().DebasePath(baseDir);
                    newFile.CreateEntryFromFile(fileToZip.ToString(), debasedFileName, CompressionLevel.Optimal);
                }
            }
        }
예제 #11
0
        /// <summary>
        ///     The target for displaying help in the command line.
        /// </summary>
        /// <param name="context">The task context.</param>
        public void LogTargetsWithHelp(ITaskContextInternal context)
        {
            if (context != null && !string.IsNullOrEmpty(context.FlubuHelpText))
            {
                context.LogInfo(context.FlubuHelpText);
            }

            LogTargetsHelp(context);
        }
예제 #12
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            // do not push new packages from a local build
            if (context.BuildSystems().IsLocalBuild&& _skipPushOnLocalBuild)
            {
                context.LogInfo("pushing package on local build is disabled in build script...Skiping.");
                return(1);
            }

            return(base.DoExecute(context));
        }
예제 #13
0
        /// <summary>
        ///     The target for displaying help in the command line.
        /// </summary>
        /// <param name="context">The task context.</param>
        public void TargetsHelp(ITaskContextInternal context)
        {
            context.LogInfo("Targets:");

            // first sort the targets
            var sortedTargets = new SortedList <string, ITarget>();

            foreach (var target in _targets.Values)
            {
                sortedTargets.Add(target.TargetName, target);
            }

            // now display them in sorted order
            foreach (ITarget target in sortedTargets.Values)
            {
                if (target.IsHidden == false)
                {
                    context.LogInfo($"  {target.TargetName} : {target.Description}");
                }
            }
        }
예제 #14
0
            public void PerformVisit(ITaskContextInternal context, XmlDocument xmlDoc)
            {
                context.LogInfo($"Performing visit on XPath '{_xpath}'");

                XmlNodeList nodes = xmlDoc.SelectNodes(_xpath);

                if (nodes == null || nodes.Count == 0)
                {
                    context.LogInfo($"XPath '{_xpath}' returns empty list");
                    return;
                }

                context.LogInfo($"XPath '{_xpath}' returns {nodes.Count} nodes");
                foreach (XmlNode node in nodes)
                {
                    if (!_visitorFunc(node))
                    {
                        return;
                    }
                }
            }
예제 #15
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            _packagePath.MustNotBeNullOrEmpty("packagePath (path to .nupkg) must not be null or empty.");

            // do not push new packages from a local build
            if (context.BuildServers().IsLocalBuild&& _skipPushOnLocalBuild)
            {
                context.LogInfo("pushing package on local build is disabled in build script...Skiping.");
                return(1);
            }

            return(base.DoExecute(context));
        }
예제 #16
0
        public void RunTargetHelp(ITaskContextInternal taskContext, string targetName)
        {
            if (!_targets.ContainsKey(targetName))
            {
                throw new ArgumentException($"The target '{targetName}' does not exist");
            }

            Target target = _targets[targetName] as Target;

            target.TargetHelp(taskContext);

            if (target.Dependencies.Count > 0)
            {
                taskContext.LogInfo(" ");
                taskContext.LogInfo($"Target {targetName}  dependencies: ");
                foreach (var targetDependencyName in target.Dependencies)
                {
                    var targetDependecy = _targets[targetDependencyName.Key] as Target;
                    targetDependecy?.TargetHelp(taskContext);
                }
            }
        }
        public void CheckLbStatus(ITaskContextInternal context, string enviroment)
        {
            if (enviroment != "Production" && enviroment != "Test")
            {
                context.LogInfo($"Switch healthcheck http status for enviroment {enviroment} is not turned on.");
                return;
            }

            WebClient client = new WebClient();

            client.BaseAddress = WebApiBaseUrl(enviroment);
            var resposne = client.DownloadString("HealthCheck/Lb");
        }
예제 #18
0
        public virtual void LogTargetsHelp(ITaskContextInternal context)
        {
            context.DecreaseDepth();
            context.LogInfo("Targets:");

            // first sort the targets
            var sortedTargets = new SortedList <string, ITargetInternal>();

            foreach (var target in _targets.Values)
            {
                sortedTargets.Add(target.TargetName, target);
            }

            // now display them in sorted order
            foreach (ITargetInternal target in sortedTargets.Values)
            {
                if (target.IsHidden == false)
                {
                    string help = $"  {target.TargetName.Capitalize()}";

                    if (target.Dependencies != null && target.Dependencies.Count != 0)
                    {
                        help = $"{help} ({string.Join(", ", target.Dependencies.GetKeys())})";
                    }

                    help = $"{help} : {target.Description}";

                    if (DefaultTargets.Contains(target))
                    {
#if !NETSTANDARD1_6
                        context.LogInfo(help, Color.DarkOrange);
#else
                        context.LogInfo(help);
#endif
                    }
                    else
                    {
                        context.LogInfo(help);
                    }
                }
            }

            if (ScriptArgsHelp?.Count > 0)
            {
                context.LogInfo(" ");
                context.LogInfo("Global build script arguments:");
                foreach (var argHelp in ScriptArgsHelp)
                {
                    context.LogInfo($"  {argHelp}");
                }
            }

            context.IncreaseDepth();
        }
예제 #19
0
        public static bool LogIfFilteredOut(string fileName, IFilter filter, ITaskContextInternal taskContext, bool logFiles)
        {
            if (filter != null && !filter.IsPassedThrough(fileName))
            {
                if (logFiles)
                {
                    taskContext.LogInfo($"File '{fileName}' has been filtered out.");
                }

                return(false);
            }

            return(true);
        }
예제 #20
0
        public void Copy(FileFullPath sourceFileName, FileFullPath destinationFileName)
        {
            var directoryName = destinationFileName.Directory.ToString();

            if (!string.IsNullOrEmpty(directoryName))
            {
                if (!Directory.Exists(directoryName))
                {
                    if (_logCopiedFiles)
                    {
                        _taskContext.LogInfo($"Creating directory '{directoryName}'");
                    }

                    Directory.CreateDirectory(directoryName);
                }
            }

            if (_logCopiedFiles)
            {
                _taskContext.LogInfo($"Copying file '{sourceFileName}' to '{destinationFileName}'");
            }

            File.Copy(sourceFileName.ToString(), destinationFileName.ToString(), true);
        }
예제 #21
0
        protected override async Task <int> DoExecuteAsync(ITaskContextInternal context)
        {
            if (string.IsNullOrEmpty(_saveAs))
            {
                throw new ArgumentNullException(nameof(_saveAs));
            }

            var extension = Path.GetExtension(_saveAs);

            if (string.IsNullOrEmpty(extension) || !extension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
            {
                throw new TaskExecutionException("SaveAs file extension must be .zip", 99);
            }

            var client = WebApiClientFactory.Create(context.Properties.Get <string>(BuildProps.LastWebApiBaseUrl));

            try
            {
                var reports = await client.DownloadReportsAsync(new DownloadReportsRequest()
                {
                    DownloadFromSubDirectory = _subDirectory
                }) as MemoryStream;

                using (FileStream file = new FileStream(_saveAs, FileMode.Create, FileAccess.Write))
                {
                    reports.WriteTo(file);

#if !NETSTANDARD1_6
                    reports.Close();
                    file.Close();
#endif
                }
            }
            catch (WebApiException e)
            {
                if (e.ErrorCode == "NoReportsFound" && !_failWhenNoReportsFound)
                {
                    context.LogInfo("No reports found on server.");
                    return(0);
                }

                throw;
            }

            return(0);
        }
예제 #22
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            if (_targetTree == null)
            {
                throw new ArgumentNullException(nameof(_targetTree), "TargetTree must be set before Execution of target.");
            }

            if (_mustCondition != null)
            {
                var conditionMeet = _mustCondition.Invoke();

                if (conditionMeet == false)
                {
                    throw new TaskExecutionException($"Condition in must was not meet. Failed to execute target: '{TargetName}'.", 50);
                }
            }

#if  !NETSTANDARD1_6
            context.LogInfo($"Executing target {TargetName}", Color.DimGray);
#else
            context.LogInfo($"Executing target {TargetName}");
#endif

            _targetTree.EnsureDependenciesExecuted(context, TargetName);
            _targetTree.MarkTargetAsExecuted(this);

            if (_args.TargetsToExecute != null)
            {
                if (!_args.TargetsToExecute.Contains(TargetName))
                {
                    throw new TaskExecutionException($"Target {TargetName} is not on the TargetsToExecute list", 3);
                }
            }

            int taskGroupsCount = _taskGroups.Count;
            List <System.Threading.Tasks.Task> tasks = new List <System.Threading.Tasks.Task>();
            for (int i = 0; i < taskGroupsCount; i++)
            {
                int tasksCount = _taskGroups[i].Tasks.Count;
                if (_taskGroups[i].CleanupOnCancel)
                {
                    CleanUpStore.AddCleanupAction(_taskGroups[i].FinallyAction);
                }

                try
                {
                    for (int j = 0; j < tasksCount; j++)
                    {
                        var task = (TaskHelp)_taskGroups[i].Tasks[j].task;
#if !NETSTANDARD1_6
                        context.LogInfo($"Executing task {task.TaskName}", Color.DimGray);
#else
                        context.LogInfo($"Executing task {task.TaskName}");
#endif

                        if (_taskGroups[i].Tasks[j].taskExecutionMode == TaskExecutionMode.Synchronous)
                        {
                            _taskGroups[i].Tasks[j].task.ExecuteVoid(context);
                        }
                        else
                        {
                            tasks.Add(_taskGroups[i].Tasks[j].task.ExecuteVoidAsync(context));
                            if (j + 1 < tasksCount)
                            {
                                if (_taskGroups[i].Tasks[j + 1].taskExecutionMode != TaskExecutionMode.Synchronous)
                                {
                                    continue;
                                }
                                if (tasks.Count <= 0)
                                {
                                    continue;
                                }
                                Task.WaitAll(tasks.ToArray());
                                tasks = new List <Task>();
                            }
                            else if (i + 1 < taskGroupsCount)
                            {
                                if (_taskGroups[i + 1].Tasks[0].taskExecutionMode != TaskExecutionMode.Synchronous)
                                {
                                    continue;
                                }
                                if (tasks.Count <= 0)
                                {
                                    continue;
                                }
                                Task.WaitAll(tasks.ToArray());
                                tasks = new List <Task>();
                            }
                            else if (tasksCount > 0)
                            {
                                Task.WaitAll(tasks.ToArray());
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _taskGroups[i].OnErrorAction?.Invoke(context, e);
                    throw;
                }
                finally
                {
                    if (!CleanUpStore.StoreAccessed)
                    {
                        if (_taskGroups[i].CleanupOnCancel)
                        {
                            CleanUpStore.RemoveCleanupAction(_taskGroups[i].FinallyAction);
                        }

                        _taskGroups[i].FinallyAction?.Invoke(context);
                    }
                }
            }

            return(0);
        }
예제 #23
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            if (_targetTree == null)
            {
                throw new ArgumentNullException(nameof(_targetTree), "TargetTree must be set before Execution of target.");
            }

            context.LogInfo($"Executing target {TargetName}");

            _targetTree.EnsureDependenciesExecuted(context, TargetName);
            _targetTree.MarkTargetAsExecuted(this);

            if (_args.TargetsToExecute != null)
            {
                if (!_args.TargetsToExecute.Contains(TargetName))
                {
                    throw new TaskExecutionException($"Target {TargetName} is not on the TargetsToExecute list", 3);
                }
            }

            int taskGroupsCount = _taskGroups.Count;
            List <System.Threading.Tasks.Task> tasks = new List <System.Threading.Tasks.Task>();

            for (int i = 0; i < taskGroupsCount; i++)
            {
                int tasksCount = _taskGroups[i].Tasks.Count;
                try
                {
                    for (int j = 0; j < tasksCount; j++)
                    {
                        var task = (TaskHelp)_taskGroups[i].Tasks[j].task;
                        context.LogInfo($"Executing task {task.TaskName}");
                        if (_taskGroups[i].Tasks[j].taskExecutionMode == TaskExecutionMode.Synchronous)
                        {
                            _taskGroups[i].Tasks[j].task.ExecuteVoid(context);
                        }
                        else
                        {
                            tasks.Add(_taskGroups[i].Tasks[j].task.ExecuteVoidAsync(context));
                            if (j + 1 < tasksCount)
                            {
                                if (_taskGroups[i].Tasks[j + 1].taskExecutionMode != TaskExecutionMode.Synchronous)
                                {
                                    continue;
                                }
                                if (tasks.Count <= 0)
                                {
                                    continue;
                                }
                                Task.WaitAll(tasks.ToArray());
                                tasks = new List <Task>();
                            }
                            else if (i + 1 < taskGroupsCount)
                            {
                                if (_taskGroups[i + 1].Tasks[0].taskExecutionMode != TaskExecutionMode.Synchronous)
                                {
                                    continue;
                                }
                                if (tasks.Count <= 0)
                                {
                                    continue;
                                }
                                Task.WaitAll(tasks.ToArray());
                                tasks = new List <Task>();
                            }
                            else if (tasksCount > 0)
                            {
                                Task.WaitAll(tasks.ToArray());
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _taskGroups[i].OnErrorAction?.Invoke(context, e);
                    throw;
                }
                finally
                {
                    _taskGroups[i].FinallyAction?.Invoke(context);
                }
            }

            return(0);
        }
예제 #24
0
        public void EnsureDependenciesExecuted(ITaskContextInternal taskContext, string targetName)
        {
            if (_args.NoDependencies)
            {
                taskContext.LogInfo("Skipping target dependencies.");
                return;
            }

            ITargetInternal target = _targets[targetName];
            int             n      = target.Dependencies.Count;
            List <Task>     tasks  = new List <Task>();

            for (int i = 0; i < n; i++)
            {
                var dependantTargetName = target.Dependencies.Keys.ElementAt(i);
                var executionMode       = target.Dependencies.Values.ElementAt(i);
                if (_executedTargets.Contains(dependantTargetName))
                {
                    continue;
                }

                if (_args.TargetsToExecute != null)
                {
                    if (!_args.TargetsToExecute.Contains(dependantTargetName))
                    {
                        throw new TaskExecutionException($"Target {dependantTargetName} is not on the TargetsToExecute list", 3);
                    }

                    DependenciesExecutedCount++;
                }

                if (executionMode == TaskExecutionMode.Synchronous)
                {
                    RunTarget(taskContext, dependantTargetName);
                }
                else
                {
                    tasks.Add(RunTargetAsync(taskContext, dependantTargetName));
                    if (i + 1 < n)
                    {
                        if (target.Dependencies.Values.ElementAt(i + 1) != TaskExecutionMode.Synchronous)
                        {
                            continue;
                        }
                        if (tasks.Count <= 0)
                        {
                            continue;
                        }

                        Task.WaitAll(tasks.ToArray());
                        tasks = new List <Task>();
                    }
                    else
                    {
                        if (tasks.Count > 0)
                        {
                            Task.WaitAll(tasks.ToArray());
                        }
                    }
                }
            }
        }
예제 #25
0
        protected override BuildVersion DoExecute(ITaskContextInternal context)
        {
            string productRootDir = context.Properties.Get <string>(BuildProps.ProductRootDir, ".");
            string productId      = context.Properties.Get <string>(BuildProps.ProductId, null);

            if (productId != null)
            {
                _projectVersionFiles.Add($"{productId}.ProjectVersion.txt");
                _projectVersionFiles.Add($"{productId}.ProjectVersion.md");
            }

            _projectVersionFiles.AddRange(_defaultprojectVersionFiles);
            string projectVersionFilePath = null;

            foreach (var projectVersionFile in _projectVersionFiles)
            {
                var filePath = Path.Combine(productRootDir, projectVersionFile);
                if (File.Exists(filePath))
                {
                    projectVersionFilePath = filePath;
                    break;
                }
            }

            if (projectVersionFilePath == null)
            {
                string defaultLocations = string.Empty;
                foreach (var projectVersionFile in _projectVersionFiles)
                {
                    defaultLocations = $"{Path.Combine(productRootDir, projectVersionFile)}{Environment.NewLine}";
                }

                throw new InvalidOperationException($"Project version file is missing. Set 'ProjectVersionFileName' or use one of the default locations: {Environment.NewLine}{defaultLocations}");
            }

            string  versionQuality = null;
            Version version        = null;

            context.LogInfo($"Fetching version from file: {projectVersionFilePath}");
            using (Stream stream = File.Open(projectVersionFilePath, FileMode.Open))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string line;
                    bool   versionFound = false;

                    while ((line = reader.ReadLine()) != null)
                    {
                        try
                        {
                            if (_prefixToRemove != null && line.StartsWith(_prefixToRemove))
                            {
                                line = line.Substring(_prefixToRemove.Length);
                            }

                            line = line.Trim();

                            if (_allowSuffix)
                            {
                                var index = line.IndexOf(' ');
                                if (index > 0)
                                {
                                    line = line.Remove(index);
                                }
                            }

                            if (line.Contains("-"))
                            {
                                var splitedVersion = line.Split('-');
                                if (splitedVersion.Length > 2)
                                {
                                    throw new TaskExecutionException("Only one dash is allowed for version quality.", 6);
                                }

                                version        = new Version(splitedVersion[0].Trim());
                                versionQuality = splitedVersion[1].Trim();
                            }
                            else
                            {
                                version = new Version(line);
                            }

                            versionFound = true;

                            break;
                        }
                        catch (Exception)
                        {
                        }
                    }

                    if (!versionFound)
                    {
                        throw new TaskExecutionException($"Version information not found in file '{projectVersionFilePath}' File should contaion line with version e.g. '1.0.0.0'", -53);
                    }
                }
            }

            if (!_doNotSaveVersionToSession)
            {
                context.SetBuildVersion(version);
                context.SetBuildVersionQuality(versionQuality);
            }

            var buildVersion = new BuildVersion()
            {
                Version        = version,
                VersionQuality = versionQuality
            };

            DoLogInfo($"Project version fetched: {buildVersion.Version}");
            return(buildVersion);
        }
        protected override int DoExecute(ITaskContextInternal context)
        {
            FullPath packagesDir = new FullPath(context.Properties.Get(BuildProps.ProductRootDir, "."));

            packagesDir = packagesDir.CombineWith(context.Properties.Get <string>(DotNetBuildProps.BuildDir));

            FileFullPath destNuspecFile = packagesDir.AddFileName("{0}.nuspec", _packageId);

            DoLogInfo($"Preparing the {destNuspecFile} file");

            new ReplaceTokensTask(_nuspecFileName)
            .Replace("version", context.Properties.GetBuildVersion().BuildVersionWithQuality(3))
            .UseToken("$")
            .ToDestination(destNuspecFile.ToString())
            .ExecuteVoid(context);

            // package it
            DoLogInfo("Creating a NuGet package file");
            string           nugetWorkingDir = destNuspecFile.Directory.ToString();
            NuGetCmdLineTask nugetTask       = new NuGetCmdLineTask("pack", nugetWorkingDir)
            {
                Verbosity = NuGetCmdLineTask.NuGetVerbosity.Detailed
            };

            nugetTask.WithArguments(destNuspecFile.FileName);

            if (BasePath != null)
            {
                nugetTask.WithArguments("-BasePath", BasePath);
            }

            nugetTask.ExecuteVoid(context);

            string nupkgFileName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}.{1}.nupkg",
                _packageId,
                context.Properties.GetBuildVersion().BuildVersionWithQuality(3));

            DoLogInfo($"NuGet package file {nupkgFileName} created");

            // do not push new packages from a local build
            if (context.BuildServers().IsLocalBuild&& _skipPushOnLocalBuild)
            {
                context.LogInfo("pushing package on local build is disabled in build script...Skiping.");
                return(1);
            }

            if (_apiKeyFunc == null)
            {
                throw new InvalidOperationException("NuGet API key was not provided");
            }

            string apiKey = _apiKeyFunc(context);

            if (apiKey == null)
            {
                return(1);
            }

            // publish the package file
            DoLogInfo("Pushing the NuGet package to the repository");

            nugetTask = new NuGetCmdLineTask("push", nugetWorkingDir)
            {
                Verbosity = NuGetCmdLineTask.NuGetVerbosity.Detailed,
                ApiKey    = apiKey
            };

            if (_nuGetServerUrl != null)
            {
                nugetTask.WithArguments("-Source", _nuGetServerUrl);
            }

            nugetTask
            .WithArguments(nupkgFileName)
            .ExecuteVoid(context);

            return(0);
        }