コード例 #1
0
ファイル: Vault3.cs プロジェクト: vardars/ci-factory
        public override void GetSource(IIntegrationResult result)
        {
            if (!_shim.AutoGetSource) return;

            _labelApplied = false;

            if (StringUtil.IsBlank(_shim.WorkingDirectory) && !(!_shim.ApplyLabel && _shim.UseVaultWorkingDirectory && !_shim.CleanCopy))
            {
                _shim.WorkingDirectory = GetVaultWorkingFolder(result);
                if (StringUtil.IsBlank(_shim.WorkingDirectory))
                    throw new VaultException(
                        string.Format("Vault user {0} has no working folder set for {1} in repository {2} and no working directory has been specified.",
                                      _shim.Username, _shim.Folder, _shim.Repository));
            }

            if (_shim.ApplyLabel)
            {
                Log.Info(string.Format("Applying label \"{0}\" to {1} in repository {2}.", result.Label, _shim.Folder, _shim.Repository));
                Execute(LabelProcessInfo(result));
                _labelApplied = true;
            }

            if (_shim.CleanCopy && !StringUtil.IsBlank(this._shim.WorkingDirectory))
            {
                Log.Debug("Cleaning out source folder: " + result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
                new IoService().EmptyDirectoryIncludingReadOnlyObjects(result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
            }

            Log.Info("Getting source from Vault");
            Execute(GetSourceProcessInfo(result, _shim.ApplyLabel));
        }
コード例 #2
0
ファイル: Vault3.cs プロジェクト: vardars/ci-factory
 public override Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
 {
     _labelApplied = false;
     Log.Info(string.Format("Checking for modifications to {0} in Vault Repository \"{1}\" between {2} and {3}", _shim.Folder, _shim.Repository, from.StartTime, to.StartTime));
     ProcessResult result = ExecuteWithRetries(ForHistoryProcessInfo(from, to));
     return ParseModifications(result, from.StartTime, to.StartTime);
 }
コード例 #3
0
        public void Run(IIntegrationResult result)
        {
            if (IntegrationStatus != result.Status) return;

            ICruiseManager manager = (ICruiseManager) remotingService.Connect(typeof(ICruiseManager), ServerUri);
            manager.ForceBuild(Project);
        }
コード例 #4
0
 /// <summary>
 /// Convert the build results into XML.
 /// </summary>
 /// <param name="result">The build results.</param>
 /// <returns>The XML results.</returns>
 private static string ToXml(IIntegrationResult result)
 {
     StringWriter xmlResultString = new StringWriter();
     XmlIntegrationResultWriter writer = new XmlIntegrationResultWriter(xmlResultString);
     writer.Write(result);
     return xmlResultString.ToString();
 }
コード例 #5
0
 public void LabelSourceControl(IIntegrationResult result)
 {
     foreach (ISourceControl sourceControl in SourceControls)
     {
         sourceControl.LabelSourceControl(result);
     }
 }
コード例 #6
0
        /// <summary>
        /// Generates parameter values from the incoming request values.
        /// </summary>
        /// <param name="result">The result.</param>
        public void GenerateSystemParameterValues(IIntegrationResult result)
        {
            var props = result.IntegrationProperties;
            foreach (var property in props.Keys)
            {
                // Generate the build value
                var key = string.Format("${0}", property);
                var value = (props[property] ?? string.Empty).ToString();
                result.IntegrationRequest.BuildValues[key] = value;

                // Add to the parameters
                var namedValue = new NameValuePair(key, value);
                if (result.Parameters.Contains(namedValue))
                {
                    // Replace an existing value
                    var index = result.Parameters.IndexOf(namedValue);
                    result.Parameters[index] = namedValue;
                }
                else
                {
                    // Add a new value
                    result.Parameters.Add(namedValue);
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Gets the modifications from the source control provider
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
		public Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
		{
            if (FailGetModifications)
            {
                throw new System.Exception("Failing GetModifications");
            }
            else if (AlwaysModified)
            {
                revisionNumber += 1;

                Modification[] mods = new Modification[1];
                Modification mod = new Modification();
                mod.FileName = "AlwaysModified";
                mod.FolderName = "NullSourceControl";
                mod.ModifiedTime = DateTime.Now;
                mod.UserName = "******";
                mod.Comment = "Making a change";
                mod.Type = "modified";


                if (string.Equals(ChangeNumberType, "guid", StringComparison.CurrentCultureIgnoreCase))
                { mod.ChangeNumber = Guid.NewGuid().ToString("N"); }

                if (string.Equals(ChangeNumberType, "integer", StringComparison.CurrentCultureIgnoreCase))
                { mod.ChangeNumber = revisionNumber.ToString(); }
                
                mods[0] = mod;
                return mods;
            }
            else
            {
                return new Modification[0];
            }
		}
コード例 #8
0
        /// <summary>
        /// Gets the modifications from the source control provider
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
		public Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
		{
            if (FailGetModifications)
            {
                throw new System.Exception("Failing GetModifications");
            }
            else if (AlwaysModified)
            {
                Modification[] mods = new Modification[1];
                Modification mod = new Modification();
                mod.FileName = "AlwaysModified";
                mod.FolderName = "NullSourceControl";
                mod.ModifiedTime = DateTime.Now;
                mod.UserName = "******";
                mod.ChangeNumber = Guid.NewGuid().ToString("N");
                mod.Comment = "Making a change";
                mod.Type = "modified";
                mods[0] = mod;
                return mods;
            }
            else
            {
                return new Modification[0];
            }
		}
コード例 #9
0
ファイル: Vault317.cs プロジェクト: vardars/ci-factory
        public override void GetSource(IIntegrationResult result)
        {
            if (!_shim.AutoGetSource) return;
            Debug.Assert(_folderVersion > 0, "_folderVersion <= 0 when attempting to get source.  This shouldn't happen.");

            if (_shim.CleanCopy)
            {
                string cleanCopyWorkingFolder = null;
                if (StringUtil.IsBlank(_shim.WorkingDirectory))
                {
                    cleanCopyWorkingFolder = GetVaultWorkingFolder(result);
                    if (StringUtil.IsBlank(cleanCopyWorkingFolder))
                        throw new VaultException(
                            string.Format("Vault user {0} has no working folder set for {1} in repository {2} and no working directory has been specified.",
                                          _shim.Username, _shim.Folder, _shim.Repository));
                }
                else
                    cleanCopyWorkingFolder = result.BaseFromWorkingDirectory(_shim.WorkingDirectory);

                Log.Debug("Cleaning out source folder: " + cleanCopyWorkingFolder);
                new IoService().EmptyDirectoryIncludingReadOnlyObjects(cleanCopyWorkingFolder);
            }

            Log.Info("Getting source from Vault");
            Execute(GetSourceProcessInfo(result));
        }
コード例 #10
0
		public void SetUp()
		{
			CreateProcessExecutorMock(NAntTask.defaultExecutable);
			builder = new NAntTask((ProcessExecutor) mockProcessExecutor.MockInstance);
			result = IntegrationResult();
			result.Label = "1.0";
		}
コード例 #11
0
 public void GetSource(IIntegrationResult result)
 {
     foreach (ISourceControl sourceControl in SourceControls)
     {
         sourceControl.GetSource(result);
     }
 }
コード例 #12
0
ファイル: Cvs.cs プロジェクト: vardars/ci-factory
 public override void GetSource(IIntegrationResult result)
 {
     if (AutoGetSource && !UseHistory)
     {
         UpdateSource(result, null);
     }
 }
コード例 #13
0
        public IIntegrationResult RunIntegration(IIntegrationResult result)
        {
            IIntegrationResult lastResult = resultManager.LastIntegrationResult;

            this.CreateDirectoryIfItDoesntExist(result.WorkingDirectory);
            this.CreateDirectoryIfItDoesntExist(result.ArtifactDirectory);
            result.MarkStartTime();
            bool IsRunable = false;
            try
            {
                result.Modifications = this.GetModifications(lastResult, result);
                IsRunable = this.IntegrationFilter.ShouldRunBuild(result);
                if (IsRunable)
                {
                    target.Activity = ProjectActivity.Building;
                    target.SourceControl.GetSource(result);
                    this.RunBuild(result);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                result.ExceptionResult = ex;
            }
            result.MarkEndTime();

            if (IsRunable)
                this.PostBuild(result);

            target.Activity = ProjectActivity.Sleeping;

            return result;
        }
コード例 #14
0
        public void Setup()
        {
            this.mocks = new MockRepository();

            mockery = new Mockery();
            targetMock = mockery.NewDynamicMock(typeof(IIntegrationRunnerTarget));
            resultManagerMock = mockery.NewDynamicMock(typeof(IIntegrationResultManager));
            quietPeriodMock = mockery.NewDynamicMock(typeof(IQuietPeriod));

            runner = new IntegrationRunner((IIntegrationResultManager)resultManagerMock.MockInstance,
                                           (IIntegrationRunnerTarget)targetMock.MockInstance,
                                           (IQuietPeriod)quietPeriodMock.MockInstance);


            request = ModificationExistRequest();
            endTime = new DateTime(2005, 2, 1);
            modifications = new Modification[] { new Modification() };

            resultMock = mockery.NewDynamicMock(typeof(IIntegrationResult));
            resultMock.SetupResult("WorkingDirectory", TempFileUtil.GetTempPath("workingDir"));
            resultMock.SetupResult("ArtifactDirectory", TempFileUtil.GetTempPath("artifactDir"));
            resultMock.SetupResult("BuildProgressInformation", new ThoughtWorks.CruiseControl.Core.Util.BuildProgressInformation("",string.Empty));
            resultMock.SetupResult("IntegrationProperties", new Dictionary<string, string>());
            result = (IIntegrationResult)resultMock.MockInstance;

            lastResultMock = mockery.NewDynamicMock(typeof(IIntegrationResult));
            lastResult = (IIntegrationResult)lastResultMock.MockInstance;
        }
コード例 #15
0
ファイル: MergeFilesTask.cs プロジェクト: vardars/ci-factory
 public void Run(IIntegrationResult result)
 {
     foreach (string mergeFile in MergeFiles)
     {
         string fullMergeFile = mergeFile;
         if (!Path.IsPathRooted(mergeFile))
         {
             fullMergeFile = Path.Combine(result.WorkingDirectory, mergeFile);
         }
         WildCardPath path = new WildCardPath(fullMergeFile);
         FileInfo[] files = path.GetFiles();
         foreach (FileInfo fileInfo in files)
         {
             Log.Info("Merging file: " + fileInfo);
             if (fileInfo.Exists)
             {
                 result.AddTaskResult((new FileTaskResult(fileInfo)));
             }
             else
             {
                 Log.Warning("File not Found: " + fileInfo);
             }
         }
     }
 }
コード例 #16
0
ファイル: Vault317.cs プロジェクト: derrills1/ccnet_gitmode
        public override void GetSource(IIntegrationResult result)
        {
            result.BuildProgressInformation.SignalStartRunTask("Getting source from Vault");

            if (!_shim.AutoGetSource) return;
            if (_folderVersion <= 0)
            {
                throw new CruiseControlException("_folderVersion <= 0 when attempting to get source.  This shouldn't happen.");
            }

            if (_shim.CleanCopy)
            {
                string cleanCopyWorkingFolder = null;
                if (string.IsNullOrEmpty(_shim.WorkingDirectory))
                {
                    cleanCopyWorkingFolder = GetVaultWorkingFolder(result);
                    if (string.IsNullOrEmpty(cleanCopyWorkingFolder))
                        throw new VaultException(
                            string.Format("Vault user {0} has no working folder set for {1} in repository {2} and no working directory has been specified.",
                                          _shim.Username, _shim.Folder, _shim.Repository));
                }
                else
                    cleanCopyWorkingFolder = result.BaseFromWorkingDirectory(_shim.WorkingDirectory);

                Log.Debug("Cleaning out source folder: " + cleanCopyWorkingFolder);
                fileDirectoryDeleter.DeleteIncludingReadOnlyObjects(cleanCopyWorkingFolder);
            }

            Log.Info("Getting source from Vault");
            Execute(GetSourceProcessInfo(result));
        }
コード例 #17
0
 public void LabelSourceControl(IIntegrationResult result)
 {
     var fileName = Path.Combine(
         Path.GetDirectoryName(this.FileName),
         DateTime.Now.ToString("yyyyMMddHHmmss") + ".label");
     File.WriteAllText(fileName, result.Label);
 }
コード例 #18
0
 public void Run(IIntegrationResult result)
 {
     XmlSerializer serializer = new XmlSerializer(typeof (Modification[]));
     StringWriter writer = new Utf8StringWriter();
     serializer.Serialize(writer, result.Modifications);
     fileSystem.Save(ModificationFile(result), writer.ToString());
 }
コード例 #19
0
 public override void GetSource(IIntegrationResult result)
 {
     if (!AutoGetSource) return;
     git_clean(result);
     if (git_log_local_hash(result) != null) git_reset(result);
     git_merge(result);
 }
コード例 #20
0
 public void GetSource(IIntegrationResult result)
 {
     if (FailGetSource)
     {
         throw new System.Exception("Failing getting the source");
     }
 }
コード例 #21
0
        /// <summary>
        /// Labels the source control.	
        /// </summary>
        /// <param name="result">The result.</param>
        /// <remarks></remarks>
		public void LabelSourceControl(IIntegrationResult result) 
		{
            if (FailLabelSourceControl)
            {
                throw new System.Exception("Failing label source control");
            }
		}
コード例 #22
0
 /// <summary>
 ///     Appends a text string to the task_description attribute to each task in
 ///     the current selection set.
 /// </summary>
 /// <param name="connection">CM Synergy connection parameters.</param>
 /// <param name="project">Properties of the integration testing project.</param>
 /// <param name="result">The change set for the current integration run</param>
 /// <returns>A non-null initialized process structure.</returns>
 public static ProcessInfo AddLabelToTaskComment(SynergyConnectionInfo connection, SynergyProjectInfo project, IIntegrationResult result)
 {
     const string template = @"task /modify /description ""Integrated Successfully with CruiseControl.NET project '{0}' build '{1}' on {2}"" ""{3}""";
     string tasks = GetTaskList(result.Modifications);
     string arguments = String.Format(template, result.ProjectName, result.Label, result.StartTime, tasks);
     return CreateProcessInfo(connection, arguments);
 }
コード例 #23
0
ファイル: Vault3.cs プロジェクト: kascomp/CruiseControl.NET
		/// <summary>
		/// This is called by IntegrationRunner when the build is complete.  To ensure we're building with the labelled code,
		/// we labelled just before we retrieved the sourece.  So here, we remove that label if the build failed.
		/// </summary>
		/// <param name="result"></param>
		public override void LabelSourceControl(IIntegrationResult result)
		{
			if (! _shim.ApplyLabel) return;

			if (_shim.AutoGetSource)
			{
				if (result.Status != IntegrationStatus.Success)
				{
					// Make sure we only remove the label if we actually applied it.  It's possible that the integration 
					// failed because the label already exists.  In this case, we certainly don't want to remove it.
					if (_labelApplied)
					{
						Log.Info(string.Format(
							CultureInfo.CurrentCulture, "Integration failed.  Removing label \"{0}\" from {1} in repository {2}.", result.Label, _shim.Folder, _shim.Repository));
						Execute(RemoveLabelProcessInfo(result));
					}
					else
						Log.Debug(string.Format(
							CultureInfo.CurrentCulture, "Integration failed, but a label was never successfully applied to {0} in repository {1}, so skipping removal.",
							_shim.Folder, _shim.Repository));
				}
			}
			else
			{
				Log.Info(string.Format(System.Globalization.CultureInfo.CurrentCulture,"Applying label \"{0}\" to {1} in repository {2}.", result.Label, _shim.Folder, _shim.Repository));
				Execute(LabelProcessInfo(result));
			}
		}
コード例 #24
0
        internal static VersionInformation BuildVersion(string gitRevision, int gitCheckinCount, int major, int minor, IIntegrationResult resultFromLastBuild, bool incrementOnFailure)
        {
            var result = new VersionInformation();
            var hashes = gitRevision.Split('\n');
            result.GitCommitHash = hashes[0].Trim();
            result.GitParentHash = hashes[1].Trim();
            result.GitTreeHash = hashes[2].Trim();
            result.GitCheckinCount = gitCheckinCount;

            // major.minor.revision.rebuild
            const string format = "{0}.{1}.{2}.{3}";

            var rebuildNumber = 1;
            var previousVersion = resultFromLastBuild.LastSuccessfulIntegrationLabel;
            var parts = previousVersion.Split('.');

            int previousRebuildNumber = 0;
            int previousRevision = 0;
            if (parts.Length == 4)
            {
                int.TryParse(parts[3], out previousRebuildNumber);
                int.TryParse(parts[2], out previousRevision);
            }

            if (((resultFromLastBuild.LastIntegrationStatus == IntegrationStatus.Success) || incrementOnFailure) && (gitCheckinCount == previousRevision))
            {
                rebuildNumber = previousRebuildNumber + 1;
            }

            result.BuildCycleNumber = rebuildNumber;
            var assemblySafeLabel = string.Format(format, major, minor, gitCheckinCount, rebuildNumber);
            result.AssemblySafeLabel = assemblySafeLabel;

            return result;
        }
        public void Run(IIntegrationResult result)
        {
            if (IntegrationStatus != result.Status && !IgnoreIntegrationStatus) return;

            if (IgnoreIntegrationStatus && result.Status == IntegrationStatus.Cancelled) return;

            result.BuildProgressInformation.SignalStartRunTask("Running for build publisher");

            var logger = Logger ?? new DefaultLogger();
            var loggedIn = false;
            logger.Debug("Generating client for url '{0}'", ServerUri);
            var client = factory.GenerateClient(ServerUri);
            if ((SecurityCredentials != null) && (SecurityCredentials.Length > 0))
            {
                logger.Debug("Logging in");
                client.Login(new List<NameValuePair>(SecurityCredentials));
                loggedIn = true;
            }

            ProjectIntegratorState remoteProjectStatus = ProjectIntegratorState.Unknown;

            foreach (var projectStatus in client.GetProjectStatus())
                if (projectStatus.Name == Project) remoteProjectStatus = projectStatus.Status;

            if (remoteProjectStatus != ProjectIntegratorState.Running) return;

            logger.Info("Sending ForceBuild request to '{0}' on '{1}'", Project, ServerUri);
            client.ForceBuild(Project, new List<NameValuePair>(Parameters ?? new NameValuePair[0]));
            if (loggedIn)
            {
                logger.Debug("Logging out");
                client.Logout();
            }
        }
コード例 #26
0
        public bool ShouldRunBuild(IIntegrationResult result)
        {
            this.Result = result;
            bool IsRunnable;

            if (result.BuildCondition != BuildCondition.ForceBuild)
            {
                IsRunnable = this.CheckIfRunnable(this.Triggered);
                if (!IsRunnable)
                {
                    Log.Info("Trigger blocked by integration filter.");
                    return false;
                }
            }

            if (result.BuildCondition == BuildCondition.ForceBuild)
            {
                IsRunnable = this.CheckIfRunnable(this.Forced);
                if (!IsRunnable)
                {
                    Log.Info("Force blocked by integration filter.");
                    return false;
                }
            }

            return true;
        }
コード例 #27
0
 public override Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
 {
     var processResult = this.ExecuteCommand(to, "list");
     var modifications = this.ParseModifications(processResult, 
         from.StartTime, to.StartTime);
     return modifications;
 }
コード例 #28
0
        /// <summary>
        ///     Used to add the current selection set to the shared task folder.
        /// </summary>
        /// <exception cref="CruiseControlException">
        ///     If <pararef name="result"/ >.Modifications is null or empty.
        /// </exception>
        /// <param name="connection">CM Synergy connection parameters.</param>
        /// <param name="project">Properties of the integration testing project.</param>
        /// <param name="result">The integration result for this build</param>
        /// <returns>A non-null initialized process structure.</returns>
        public static ProcessInfo AddTasksToFolder(SynergyConnectionInfo connection, SynergyProjectInfo project, IIntegrationResult result)
        {
            const string template = @"folder /modify /add_tasks ""{0}"" /y ""{1}""";
            string tasks = GetTaskList(result.Modifications);
            string arguments = String.Format(template, tasks, project.TaskFolder);

            return CreateProcessInfo(connection, arguments);
        }
コード例 #29
0
 protected override bool Evaluate(IIntegrationResult result)
 {
     DateTime current = getEvaluationTime(result);
     current = DatetimeFunctions.getTimeInTimeZone(TimeZone, current);
     if (evalWeekDay(current))
         return evalTimeperiod(current);
     return false;
 }
コード例 #30
0
 /// <summary>
 /// Performs the actual evaluation.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <returns>
 /// <c>true</c> if the condition is true; <c>false</c> otherwise.
 /// </returns>
 protected override bool Evaluate(IIntegrationResult result)
 {
     var folderName = result.BaseFromWorkingDirectory(this.FolderName);
     this.LogDescriptionOrMessage("Checking for folder '" + folderName + "'");
     var fileSystem = this.FileSystem ?? new SystemIoFileSystem();
     var exists = fileSystem.DirectoryExists(folderName);
     return exists;
 }
コード例 #31
0
        /// <summary>
        /// Tries to run.
        /// </summary>
        /// <param name="info">The info.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        protected ProcessResult TryToRun(ProcessInfo info, IIntegrationResult result)
        {
            buildProgressInformation = result.BuildProgressInformation;

            try
            {
                // enable Stdout monitoring
                executor.ProcessOutput += ProcessExecutor_ProcessOutput;

                return(executor.Execute(info));
            }
            catch (IOException e)
            {
                throw new BuilderException(
                          this,
                          string.Format(System.Globalization.CultureInfo.CurrentCulture, "Unable to execute: {0} {1}\n{2}", info.FileName, info.PublicArguments, e), e);
            }
            finally
            {
                // remove Stdout monitoring
                executor.ProcessOutput -= ProcessExecutor_ProcessOutput;
            }
        }
コード例 #32
0
        private static string GetPropertyArgs(IIntegrationResult result)
        {
            ProcessArgumentBuilder builder = new ProcessArgumentBuilder();

            builder.Append("/p:");

            int count = 0;
            // We have to sort this alphabetically, else the unit tests
            // that expect args in a certain order are unpredictable
            IDictionary properties = result.IntegrationProperties;

            foreach (string key in properties.Keys)
            {
                if (count > 0)
                {
                    builder.Append(";");
                }
                builder.Append(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}={1}", key, StringUtil.StripThenEncodeParameterArgument(StringUtil.IntegrationPropertyToString(result.IntegrationProperties[key]))));
                count++;
            }

            return(builder.ToString());
        }
コード例 #33
0
        private ProcessInfo GetSourceProcessInfo(IIntegrationResult result)
        {
            var builder = new PrivateArguments();

            builder.Add("getversion ", _folderVersion.ToString(CultureInfo.CurrentCulture));
            builder.Add(null, _shim.Folder, true);

            if (!string.IsNullOrEmpty(_shim.WorkingDirectory))
            {
                builder.Add(null, result.BaseFromWorkingDirectory(_shim.WorkingDirectory), true);
                if (_shim.UseVaultWorkingDirectory)
                {
                    builder.Add("-useworkingfolder");
                }
            }

            builder.Add("-merge ", "overwrite");
            builder.Add("-makewritable");
            builder.Add("-backup ", "no");
            builder.Add("-setfiletime ", _shim.setFileTime);
            AddCommonOptionalArguments(builder);
            return(ProcessInfoFor(builder, result));
        }
コード例 #34
0
        public bool ShouldRunBuild(IIntegrationResult result)
        {
            Log.Info(string.Format("{0}.{1}:Begin", System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name, System.Reflection.MethodBase.GetCurrentMethod().Name));
            this.Result = result;
            bool IsRunnable;

            IsRunnable = this.CheckIfRunnable(this.Allowed, true);
            Log.Info(string.Format("{0}.{1}:IsRunnable={1}", System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name, System.Reflection.MethodBase.GetCurrentMethod().Name, IsRunnable.ToString()));
            if (!IsRunnable)
            {
                return(false);
            }

            IsRunnable = this.CheckIfRunnable(this.Blocked, false);
            Log.Info(string.Format("{0}.{1}:IsRunnable={1}", System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name, System.Reflection.MethodBase.GetCurrentMethod().Name, IsRunnable.ToString()));
            if (!IsRunnable)
            {
                return(false);
            }

            Log.Info(string.Format("{0}.{1}:IsRunnable={1}", System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name, System.Reflection.MethodBase.GetCurrentMethod().Name, IsRunnable.ToString()));
            return(true);
        }
コード例 #35
0
        /// <summary>
        /// Stores a snapshot of a project build.
        /// </summary>
        /// <param name="result">The result that the snapshot is for.</param>
        /// <param name="snapshot">The project snapshot.</param>
        public void StoreProjectSnapshot(IIntegrationResult result, ItemStatus snapshot)
        {
            var dirPath = this.RootFolder(result.ArtifactDirectory, this.SnapshotsFolder);

            Log.Info("Writing snapshot (XML) to [" + dirPath + "]");

            var logFile  = new LogFile(result);
            var filePath = Path.ChangeExtension(
                Path.Combine(dirPath, logFile.Filename),
                "snapshot");

            this.FileSystem.EnsureFolderExists(filePath);
            Log.Debug("Creating new snapshot (XML) [" + filePath + "]");
            using (var stream = this.FileSystem.OpenOutputStream(filePath))
            {
                using (var writer = new StreamWriter(stream))
                {
                    Log.Debug("Writing snapshot (XML)");
                    writer.Write(snapshot.ToString());
                    Log.Debug("Snapshot (XML) written");
                }
            }
        }
コード例 #36
0
        /// <summary>
        /// Labelling in Perforce requires 2 activities. First you create a 'label specification' which is the name of the label, and what
        /// part of the source repository it is associated with. Secondly you actually populate the label with files and associated
        /// revisions by performing a 'label sync'. We take the versioned file set as being the versions that are currently
        /// checked out on the client (In theory this could be refined by using the timeStamp, but it would be better
        /// to wait until CCNet has proper support for atomic-commit change groups, and use that instead)
        /// </summary>
        public override void LabelSourceControl(IIntegrationResult result)
        {
            if (ApplyLabel && result.Succeeded)
            {
                if (result.Label == null || result.Label.Length == 0)
                {
                    throw new ApplicationException("Internal Exception - Invalid (null or empty) label passed");
                }

                try
                {
                    int.Parse(result.Label, CultureInfo.CurrentCulture);
                    throw new CruiseControlException("Perforce cannot handle purely numeric labels - you must use a label prefix for your project");
                }
                catch (FormatException)
                {}
                ProcessInfo process = CreateLabelSpecificationProcess(result.Label);
                Execute(process, "LabelSourceControl");

                process = CreateLabelSyncProcess(result.Label);
                Execute(process, "LabelSourceControl");
            }
        }
コード例 #37
0
        public void ExecutableOutputShouldBeBuildResults()
        {
            ExecutableTask xmlTestTask = new ExecutableTask((ProcessExecutor)mockProcessExecutor.MockInstance);

            xmlTestTask.Executable = DefaultExecutable;
            xmlTestTask.BuildArgs  = DefaultArgs;
            ExpectToExecuteArguments(DefaultArgs);

            IIntegrationResult result = IntegrationResult();

            xmlTestTask.Run(result);

            Assert.IsTrue(result.Succeeded);
            Assert.AreEqual(IntegrationStatus.Success, result.Status);

            // TODO: The following only works correctly when ProcessResultOutput is a single non-empty line.
            // That is always the case, courtesy of our superclass' initialization.  If that should ever
            // change, this test needs to be adjusted accordingly.
            Assert.AreEqual(System.Environment.NewLine + "<buildresults>" + System.Environment.NewLine + "  <message>"
                            + ProcessResultOutput + "</message>" + System.Environment.NewLine + "</buildresults>"
                            + System.Environment.NewLine, result.TaskOutput);
            Verify();
        }
コード例 #38
0
        /// <summary>
        /// Gets the source.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <remarks></remarks>
        public override void GetSource(IIntegrationResult result)
        {
            result.BuildProgressInformation.SignalStartRunTask("Getting source from BitKeeper");

            if (!AutoGetSource)
            {
                return;
            }

            // Get the latest source
            ProcessInfo info = NewProcessInfo(BuildGetSourceArguments(), result);

            Log.Info(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Getting source from BitKeeper: {0} {1}", info.FileName, info.PublicArguments));
            Execute(info);

            // Push any pending labels that failed to push due to remote side having additional revisions
            Execute(NewProcessInfo(BuildPushProcessArgs(), result));

            if (!(CloneTo != null && CloneTo.Length == 0))
            {
                CloneSource(result);
            }
        }
コード例 #39
0
        /// <summary>
        /// Gets the source.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <remarks></remarks>
        public override void GetSource(IIntegrationResult result)
        {
            result.BuildProgressInformation.SignalStartRunTask("Getting source from AlienBrain");

            if (AutoGetSource)
            {
                SelectBranch();

                if (result.Modifications.Length > 0)
                {
                    foreach (Modification m in result.Modifications)
                    {
                        ProcessInfo process = CreateGetProcess(m.FolderName + "/" + m.FileName);
                        Execute(process);
                    }
                }
                else
                {
                    ProcessInfo process = CreateGetProcess();
                    Execute(process);
                }
            }
        }
コード例 #40
0
        /// <summary>
        /// Get the list of modifications from the inner source control provider and filter it.
        /// </summary>
        /// <returns>The filtered modification list.</returns>
        /// <remarks>
        /// A modification survives filtering if it is accepted by the inclusion filters and not accepted
        /// by the exclusion filters.
        /// </remarks>
        public override Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
        {
            Modification[] allModifications      = _realScProvider.GetModifications(from, to);
            var            acceptedModifications = new List <Modification>();

            foreach (Modification modification in allModifications)
            {
                if (IsAcceptedByInclusionFilters(modification) &&
                    (!IsAcceptedByExclusionFilters(modification)))
                {
                    Log.Debug(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Modification {0} was accepted by the filter specification.",
                                            modification));
                    acceptedModifications.Add(modification);
                }
                else
                {
                    Log.Debug(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Modification {0} was not accepted by the filter specification.",
                                            modification));
                }
            }

            return(acceptedModifications.ToArray());
        }
コード例 #41
0
        private ProcessResult ExecuteCommand(IIntegrationResult result,
                                             string command, params string[] args)
        {
            var buffer = new PrivateArguments(command);

            buffer.Add(this.Source);
            foreach (var arg in args)
            {
                buffer.Add(string.Empty,
                           arg,
                           true);
            }

            var executable = string.IsNullOrEmpty(this.Executable) ?
                             "GetMyCode" : this.Executable;
            var processInfo = new ProcessInfo(
                result.BaseFromWorkingDirectory(executable),
                buffer,
                result.WorkingDirectory);
            var processResult = this.Execute(processInfo);

            return(processResult);
        }
コード例 #42
0
        public void ShouldSetOutputAndIntegrationStatusToFailedOnFailedBuild()
        {
            ProcessResult processResult = new ProcessResult(@"Documents\WindowsPowerShell\MyScript.ps1' is not recognized as a cmdlet", string.Empty, 1, false);
            ProcessInfo   info          = null;

            mockProcessExecutor.Setup(executor => executor.Execute(It.IsAny <ProcessInfo>())).
            Callback <ProcessInfo>(processInfo => info = processInfo).Returns(processResult).Verifiable();

            string path = Platform.IsWindows ? @"D:\CruiseControl" : @"/CruiseControl";

            mytask.Executable = POWERSHELL_PATH;
            mytask.Script     = "MyScript.ps1";
            mytask.ConfiguredScriptsDirectory = path;

            IIntegrationResult result = Integration("myProject", path, "myArtifactDirectory");

            mytask.Run(result);

            Assert.AreEqual(path, info.WorkingDirectory);

            Assert.AreEqual(IntegrationStatus.Failure, result.Status);
            CustomAssertion.AssertMatches(@"(\.|\n)*is not recognized as a cmdlet", result.TaskOutput);
        }
コード例 #43
0
        private ProcessInfo GetSourceProcessInfo(IIntegrationResult result)
        {
            ProcessArgumentBuilder builder = new ProcessArgumentBuilder();

            builder.AddArgument("getversion", _folderVersion.ToString());
            builder.AddArgument(_shim.Folder);

            if (!StringUtil.IsBlank(_shim.WorkingDirectory))
            {
                builder.AddArgument(result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
                if (_shim.UseVaultWorkingDirectory)
                {
                    builder.AppendArgument("-useworkingfolder");
                }
            }

            builder.AddArgument("-merge", "overwrite");
            builder.AppendArgument("-makewritable");
            builder.AddArgument("-backup", "no");
            builder.AddArgument("-setfiletime", _shim.setFileTime);
            AddCommonOptionalArguments(builder);
            return(ProcessInfoFor(builder.ToString(), result));
        }
コード例 #44
0
 /// <summary>
 /// This method exists only to allow the VssTest unit tests to supply an expected output filename.
 /// DO NOT use this method for normal processing, use <see cref="GetModifications(IIntegrationResult, IIntegrationResult)"/>
 /// instead
 /// </summary>
 public Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to, string tempOutputFileName)
 {
     try
     {
         Execute(CreateHistoryProcessInfo(from, to, tempOutputFileName));
         TextReader outputReader = new StreamReader(tempOutputFileName, Encoding.Default);
         try
         {
             // return ParseModifications(outputReader, from.StartTime, to.StartTime);
             Modification[] modifications = ParseModifications(outputReader, from.StartTime, to.StartTime);
             base.FillIssueUrl(modifications);
             return(modifications);
         }
         finally
         {
             outputReader.Close();
         }
     }
     finally
     {
         File.Delete(tempOutputFileName);
     }
 }
コード例 #45
0
        /// <summary>
        /// Generates the specified integration result.
        /// </summary>
        /// <param name="integrationResult">The integration result.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public override string Generate(IIntegrationResult integrationResult)
        {
            if (!string.IsNullOrEmpty(LabelPrefixFile))
            {
                ThoughtWorks.CruiseControl.Core.Util.Log.Debug("Reading prefix from file : " + LabelPrefixFile);
                LabelPrefix = GetPrefixFromFile();
            }

            IntegrationSummary lastIntegration = integrationResult.LastIntegration;

            if (integrationResult == null || lastIntegration.IsInitial())
            {
                return(LabelPrefix + InitialBuildLabel.ToString(LabelFormat, CultureInfo.CurrentCulture) + LabelPostfix);
            }
            else if (ShouldIncrementLabel(lastIntegration))
            {
                return(LabelPrefix + IncrementLabel(lastIntegration.Label) + LabelPostfix);
            }
            else
            {
                return(integrationResult.LastIntegration.Label);
            }
        }
コード例 #46
0
        private string Args(IIntegrationResult result)
        {
            ProcessArgumentBuilder builder = new ProcessArgumentBuilder();

            builder.AppendArgument("-nologo");
            builder.AppendArgument("-NoProfile");
            builder.AppendArgument("-NonInteractive");

            builder.AppendArgument("-file");

            if (!string.IsNullOrEmpty(Script))
            {
                if (Script.IndexOf(":") == 1) //drive letter specified, so it's not a relative path
                {
                    builder.AppendArgument(@"""" + Script + @"""");
                }
                else
                {
                    if (ConfiguredScriptsDirectory.EndsWith("\\"))
                    {
                        builder.AppendArgument(@"""" + ConfiguredScriptsDirectory + Script + @"""");
                    }
                    else
                    {
                        builder.AppendArgument(@"""" + ConfiguredScriptsDirectory + "\\" + Script + @"""");
                    }
                }
            }


            if (!string.IsNullOrEmpty(BuildArgs))
            {
                builder.AppendArgument(BuildArgs);
            }

            return(builder.ToString());
        }
コード例 #47
0
        /// <summary>
        /// Retrieve the arguments
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns>A <c>string</c> containing the arguments.</returns>
        protected override string GetProcessArguments(IIntegrationResult result)
        {
            ProcessArgumentBuilder buffer = new ProcessArgumentBuilder();

            buffer.AddArgument("/quiet");
            buffer.AddArgument("/severityThreshold:\"" + this.ReportingThreshold.ToString() + "\"");
            buffer.AddArgument("/out:\"" + result.BaseFromWorkingDirectory("codeitright.xml") + "\"");
            if (!string.IsNullOrEmpty(this.Solution))
            {
                buffer.AddArgument("/Solution:\"" + this.EnsurePathIsRooted(result, this.Solution) + "\"");
            }
            else if (!string.IsNullOrEmpty(this.Project))
            {
                buffer.AddArgument("/Project:\"" + this.EnsurePathIsRooted(result, this.Project) + "\"");
            }
            else
            {
                throw new CruiseControlException("Either a solution or a project must be specified for analysis.");
            }

            if (!string.IsNullOrEmpty(this.Xsl))
            {
                buffer.AddArgument("/outxsl:\"" + this.EnsurePathIsRooted(result, this.Xsl) + "\"");
            }

            if (!string.IsNullOrEmpty(this.CRData))
            {
                buffer.AddArgument("/crdata:\"" + this.EnsurePathIsRooted(result, this.CRData) + "\"");
            }

            if (!string.IsNullOrEmpty(this.Profile))
            {
                buffer.AddArgument("/profile:\"" + this.Profile + "\"");
            }

            return(buffer.ToString());
        }
コード例 #48
0
        /// <summary>
        /// Executes the specified result.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        protected override bool Execute(IIntegrationResult result)
        {
            result.BuildProgressInformation.SignalStartRunTask(!string.IsNullOrEmpty(Description) ? Description :
                                                               string.Format(System.Globalization.CultureInfo.CurrentCulture, "Executing MSBuild :BuildFile: {0}", ProjectFile));

            var           info          = CreateProcessInfo(result);
            ProcessResult processResult = TryToRun(info, result);

            string buildOutputFile = MsBuildOutputFile(result);

            if (File.Exists(buildOutputFile))
            {
                result.AddTaskResult(new FileTaskResult(buildOutputFile));
            }

            result.AddTaskResult(new ProcessTaskResult(processResult, true));

            if (processResult.TimedOut)
            {
                result.AddTaskResult(MakeTimeoutBuildResult(info));
            }

            return(processResult.Succeeded);
        }
コード例 #49
0
        protected void SetUp()
        {
            var shadowCopier = mocks.DynamicMock <IShadowCopier>();

            SetupResult.For(shadowCopier.RetrieveFilePath(defaultLogger)).Return(defaultLogger);

            var executionEnvironment = mocks.DynamicMock <IExecutionEnvironment>();

            SetupResult.For(executionEnvironment.IsRunningOnWindows).Return(true);
            SetupResult.For(executionEnvironment.RuntimeDirectory).Return(RuntimeEnvironment.GetRuntimeDirectory());

            mocks.ReplayAll();


            CreateProcessExecutorMock(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "MSBuild.exe"));
            task = new MsBuildTask((ProcessExecutor)mockProcessExecutor.MockInstance, executionEnvironment, shadowCopier);

            result                   = IntegrationResult();
            result.Label             = "1.0";
            result.ArtifactDirectory = DefaultWorkingDirectory;

            logfile = Path.Combine(result.ArtifactDirectory, MsBuildTask.LogFilename);
            TempFileUtil.DeleteTempFile(logfile);
        }
コード例 #50
0
ファイル: Svn.cs プロジェクト: xiaoyongaz/CruiseControl.NET
        /// <summary>
        /// Deletes any obstructions from the working directory.
        /// </summary>
        /// <param name="result">The current result.</param>
        private void DeleteObstructionsFromWorking(IIntegrationResult result)
        {
            // Check if there are any obstructions
            Log.Info("Retrieving obstructions");
            var obstructions = this.ListObstructions(result);

            if (obstructions.Count == 0)
            {
                Log.Info("No obstructions found");
            }
            else
            {
                // Delete the obstructions
                Log.Info(obstructions.Count.ToString(CultureInfo.CurrentCulture) + " obstruction(s) found - deleting");
                var basePath = Path.GetFullPath(result.BaseFromWorkingDirectory(this.WorkingDirectory));;
                foreach (var obstruction in obstructions)
                {
                    // Get the full path to the folder
                    var path = Path.Combine(basePath, obstruction);
                    Log.Info("Deleting folder " + path);
                    this.fileSystem.DeleteDirectory(path, true);
                }
            }
        }
コード例 #51
0
        /// <summary>
        ///     Adds tasks to a shared task folder, if configured, and creates a baseline
        ///     if requested by the configuration.
        /// </summary>
        /// <remarks>
        ///     <note type="implementnotes">
        ///         This method makes use of CM Synergy selection commands, in order to pipe the
        ///         results of one query to another command.  If the CM Synergy session is lost
        ///         during the course of execution in this method, the selection set is also lost.
        ///         An exception will be thrown when the next CM Synergy command is executed,
        ///         because the selection set is empty. This should be a very rare case, and the
        ///         performance gains of piping resultsets are worthwhile.
        ///     </note>
        /// </remarks>
        /// <exception cref="CruiseControlException">
        ///     Thrown if an external process has reconfigured the project since
        ///     <see cref="GetModifications"/> was called.
        /// </exception>
        /// <param name="result">Not used.</param>
        /// <url>element://model:project::CCNet.Synergy.Plugin/design:view:::ow43bejw6wm4was_v</url>
        public void LabelSourceControl(IIntegrationResult result)
        {
            DateTime currentReconfigureTime = GetReconfigureTime();

            if (currentReconfigureTime != project.LastReconfigureTime)
            {
                string message = String.Format(@"Invalid project state.  Cannot add tasks to shared folder '{0}' because " + @"the integration project '{1}' was internally reconfigured at '{2}' " + @"and externally reconfigured at '{3}'.  Projects cannot be reconfigured " + @"during an integration run.", project.TaskFolder, project.ProjectSpecification, project.LastReconfigureTime, currentReconfigureTime);
                throw(new CruiseControlException(message));
            }

            /* Populate the query selection set with a list of ALL tasks
             * not in the manual folder. This includes all tasks for this integration,
             * and any prior failed integrations.
             * We find these by passing the the maximum range of dates to GetModifications */
            result.Modifications = GetModifications(DateTime.MinValue);

            // skip this step if a build was forced, and no changes were found
            if (null != result.Modifications && result.Modifications.Length > 0)
            {
                // comment those tasks with the "label", for both shared folders and baselines
                command.Execute(SynergyCommandBuilder.AddLabelToTaskComment(connection, project, result));

                // append tasks to the shared folder, if one was specified
                if (SynergyProjectInfo.DefaultTaskFolder != project.TaskFolder)
                {
                    // append those tasks in the selection set to the shared build folder
                    command.Execute(SynergyCommandBuilder.AddTasksToFolder(connection, project, result));
                }
            }

            // create a baseline, if requested
            if (project.BaseliningEnabled)
            {
                command.Execute(SynergyCommandBuilder.CreateBaseline(connection, project, result));
            }
        }
コード例 #52
0
        /// <summary>
        /// Generate a label string from the last change number.
        /// If there is no valid change number (e.g. for a forced build without modifications),
        /// then the last integration label is used.
        /// </summary>
        /// <param name="resultFromThisBuild">IntegrationResult object for the current build</param>
        /// <returns>the new label</returns>
        public override string Generate(IIntegrationResult resultFromThisBuild)
        {
            int changeNumber = 0;

            if (int.TryParse(resultFromThisBuild.LastChangeNumber, out changeNumber))
            {
                Log.Debug(
                    string.Format(System.Globalization.CultureInfo.CurrentCulture, "LastChangeNumber retrieved - {0}",
                                  changeNumber));
            }
            else
            {
                Log.Debug("LastChangeNumber defaulted to 0");
            }

            IntegrationSummary lastIntegration = resultFromThisBuild.LastIntegration;

            string firstSuffix = AllowDuplicateSubsequentLabels ? string.Empty : "." + INITIAL_SUFFIX_NUMBER.ToString(CultureInfo.CurrentCulture);

            if (changeNumber != 0)
            {
                return(LabelPrefix + changeNumber + firstSuffix);
            }
            else if (lastIntegration.IsInitial() || lastIntegration.Label == null)
            {
                return(LabelPrefix + "unknown" + firstSuffix);
            }
            else if (!AllowDuplicateSubsequentLabels)
            {
                return(IncrementLabel(lastIntegration.Label));
            }
            else
            {
                return(lastIntegration.Label);
            }
        }
コード例 #53
0
        private FileStream GetFileStream(IIntegrationResult result)
        {
            int numTries = 0;

            while (true)
            {
                ++numTries;
                try
                {
                    return(new FileStream(hostsPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 4096));
                }
                catch (Exception ex)
                {
                    result.AddTaskResult($"파일 열기를 실패 했습니다. 시도 : {numTries}, 사유 : {ex.ToString()}");
                    if (numTries > 10)
                    {
                        result.AddTaskResult($"파일 열기를 중단합니다. 최대 허용횟수 10을 초과하였습니다.");
                        return(null);
                    }

                    Thread.Sleep(1000);
                }
            }
        }
コード例 #54
0
        public override void GetSource(IIntegrationResult result)
        {
            if (!_shim.AutoGetSource)
            {
                return;
            }

            _labelApplied = false;

            if (StringUtil.IsBlank(_shim.WorkingDirectory) && !(!_shim.ApplyLabel && _shim.UseVaultWorkingDirectory && !_shim.CleanCopy))
            {
                _shim.WorkingDirectory = GetVaultWorkingFolder(result);
                if (StringUtil.IsBlank(_shim.WorkingDirectory))
                {
                    throw new VaultException(
                              string.Format("Vault user {0} has no working folder set for {1} in repository {2} and no working directory has been specified.",
                                            _shim.Username, _shim.Folder, _shim.Repository));
                }
            }

            if (_shim.ApplyLabel)
            {
                Log.Info(string.Format("Applying label \"{0}\" to {1} in repository {2}.", result.Label, _shim.Folder, _shim.Repository));
                Execute(LabelProcessInfo(result), result.ProjectName);
                _labelApplied = true;
            }

            if (_shim.CleanCopy && !StringUtil.IsBlank(this._shim.WorkingDirectory))
            {
                Log.Debug("Cleaning out source folder: " + result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
                new IoService().EmptyDirectoryIncludingReadOnlyObjects(result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
            }

            Log.Info("Getting source from Vault");
            Execute(GetSourceProcessInfo(result, _shim.ApplyLabel), result.ProjectName);
        }
コード例 #55
0
        private ProcessInfo GetSourceProcessInfo(IIntegrationResult result, bool getByLabel)
        {
            ProcessArgumentBuilder builder = new ProcessArgumentBuilder();

            if (getByLabel)
            {
                builder.AddArgument("getlabel", _shim.Folder);
                builder.AddArgument(result.Label);
                if (_shim.UseVaultWorkingDirectory)
                {
                    builder.AddArgument("-labelworkingfolder", result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
                }
                else
                {
                    builder.AddArgument("-destpath", result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
                }
            }
            else
            {
                builder.AddArgument("get", _shim.Folder);
                if (_shim.UseVaultWorkingDirectory)
                {
                    builder.AppendArgument("-performdeletions removeworkingcopy");
                }
                else
                {
                    builder.AddArgument("-destpath", result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
                }
            }

            builder.AddArgument("-merge", "overwrite");
            builder.AppendArgument("-makewritable");
            builder.AddArgument("-setfiletime", _shim.setFileTime);
            AddCommonOptionalArguments(builder);
            return(ProcessInfoFor(builder.ToString(), result));
        }
コード例 #56
0
        public void SuccessfulIntegrationShouldClearFailedUsersOnNextIntegration()
        {
            IIntegrationResult result1 = IntegrationResultMother.CreateFailed();

            result1.FailureUsers.Add("user1");
            ExpectToLoadState(result1);

            IIntegrationResult result2 = manager.StartNewIntegration(ModificationExistRequest());

            Assert.AreEqual(1, result2.FailureUsers.Count);

            Modification modification = new Modification();

            modification.UserName = "******";
            result2.Modifications = new Modification[] { modification };
            result2.Status        = IntegrationStatus.Success;
            mockStateManager.Expect("SaveState", result2);
            manager.FinishIntegration();
            Assert.AreEqual(1, result2.FailureUsers.Count);

            IIntegrationResult result3 = manager.StartNewIntegration(ModificationExistRequest());

            Assert.AreEqual(0, result3.FailureUsers.Count);
        }
コード例 #57
0
ファイル: Git.cs プロジェクト: robrich/CruiseControl.NET
        /// <summary>
        /// Get the hash of the latest commit in the local repository
        /// </summary>
        /// <param name="result">IIntegrationResult of the current build.</param>
        private string GitLogLocalHash(IIntegrationResult result)
        {
            ProcessArgumentBuilder buffer = new ProcessArgumentBuilder();

            buffer.AddArgument("log");
            buffer.AddArgument("--date-order");
            buffer.AddArgument("-1");
            buffer.AddArgument("--pretty=format:\"%H\"");

            string hash = null;

            try
            {
                hash = Execute(NewProcessInfo(buffer.ToString(), result)).StandardOutput.Trim();
            }
            catch (CruiseControlException ex)
            {
                if (!ex.Message.Contains("fatal: bad default revision 'HEAD'"))
                {
                    throw;
                }
            }
            return(hash);
        }
コード例 #58
0
        private void KeepMaximumXHistoryDataEntries(IIntegrationResult result, int entriesToKeep)
        {
            string historyXml = ModificationHistoryPublisher.LoadHistory(result.ArtifactDirectory);

            if (historyXml.Length == 0)
            {
                return;
            }

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(historyXml);

            //if (doc.FirstChild.ChildNodes.Count == 0)
            int nodeCount = doc.FirstChild.ChildNodes.Count;

            if (nodeCount <= entriesToKeep)
            {
                return;
            }


            StringWriter cleanedHistory = new StringWriter();

            for (int i = nodeCount - entriesToKeep; i < nodeCount; i++)
            {
                cleanedHistory.WriteLine(doc.FirstChild.ChildNodes[i].OuterXml);
            }

            StreamWriter historyWriter = new StreamWriter(
                Path.Combine(result.ArtifactDirectory,
                             ModificationHistoryPublisher.DataHistoryFileName));

            historyWriter.WriteLine(cleanedHistory.ToString());
            historyWriter.Close();
        }
コード例 #59
0
        /// <summary>
        /// Gets the source.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <remarks></remarks>
        public override void GetSource(IIntegrationResult result)
        {
            if (!_shim.AutoGetSource)
            {
                return;
            }

            _labelApplied = false;

            if (string.IsNullOrEmpty(_shim.WorkingDirectory) && !(!_shim.ApplyLabel && _shim.UseVaultWorkingDirectory && !_shim.CleanCopy))
            {
                _shim.WorkingDirectory = GetVaultWorkingFolder(result);
                if (string.IsNullOrEmpty(_shim.WorkingDirectory))
                {
                    throw new VaultException(
                              string.Format(System.Globalization.CultureInfo.CurrentCulture, "Vault user {0} has no working folder set for {1} in repository {2} and no working directory has been specified.",
                                            _shim.Username, _shim.Folder, _shim.Repository));
                }
            }

            if (_shim.ApplyLabel)
            {
                Log.Info(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Applying label \"{0}\" to {1} in repository {2}.", result.Label, _shim.Folder, _shim.Repository));
                Execute(LabelProcessInfo(result));
                _labelApplied = true;
            }

            if (_shim.CleanCopy && !string.IsNullOrEmpty(this._shim.WorkingDirectory))
            {
                Log.Debug("Cleaning out source folder: " + result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
                fileDirectoryDeleter.DeleteIncludingReadOnlyObjects(result.BaseFromWorkingDirectory(_shim.WorkingDirectory));
            }

            Log.Info("Getting source from Vault");
            Execute(GetSourceProcessInfo(result, _shim.ApplyLabel));
        }
コード例 #60
0
        private Modification[] GetModificationsUsingHistory(IIntegrationResult from, IIntegrationResult to)
        {
            Log.Debug("Using cvs history command");
            string[] dirs = GetDirectoriesContainingChanges(from);

            // Get list of target files to run 'cvs log' against
            // Loop through file list update the directory then run the 'cvs log'
            ArrayList mods = new ArrayList();

            foreach (string dir in dirs)
            {
                string reportDir = Path.Combine(WorkingDirectory, dir);
                Log.Info(String.Format("Checking directory {0} for modifications.", reportDir));
                Modification[] modifications = GetModifications(reportDir, from, to);
                mods.AddRange(modifications);

                // Update the source if there are modifications or the user explicity states to.
                if (modifications.Length > 0)
                {
                    UpdateSource(from, dir);
                }
            }
            return((Modification[])mods.ToArray(typeof(Modification)));
        }