/// <summary>
        /// Creates the process info.	
        /// </summary>
        /// <param name="p4">The p4.</param>
        /// <param name="extraArguments">The extra arguments.</param>
        /// <returns></returns>
        /// <remarks></remarks>
		public ProcessInfo CreateProcessInfo(P4 p4, string extraArguments)
		{
			ProcessInfo processInfo = new ProcessInfo(p4.Executable, BuildCommonArguments(p4) + extraArguments);
			processInfo.TimeOut = 0; // Don't time out - this should be configurable
            processInfo.WorkingDirectory = p4.WorkingDirectory;
			return processInfo;
		}
Beispiel #2
0
 public ProcessInfo CreateHistoryProcessInfo(DateTime from, DateTime to)
 {
     string fromDate = from.ToString(DATETIME_FORMAT);
     string args = CreateHistoryArguments(fromDate);
     Log.Debug(string.Format("cleartool commandline: {0} {1}", Executable, args));
     ProcessInfo processInfo = new ProcessInfo(Executable, args);
     return processInfo;
 }
Beispiel #3
0
        private ProcessInfo NewProcessInfo(string outputFile, IIntegrationResult result)
        {
            string args = new NUnitArgument(Assemblies, outputFile).ToString();
            Log.Debug(string.Format("Running unit tests: {0} {1}", NUnitPath, args));

            ProcessInfo info = new ProcessInfo(NUnitPath, args, result.WorkingDirectory);
            info.TimeOut = Timeout * 1000;
            return info;
        }
        /// <summary>
        ///     Replaces all ASCII bell characters (0x07) (^G) with a space
        ///     character.  Certain ccm.exe commands emit a bell, which cannot
        ///     be disabled.  The CCNET XML parser disallows this reserved character.
        /// </summary>
        /// <param name="processInfo">The process to run.</param>
        /// <returns>
        ///     Sanitized standard output and input.
        /// </returns>
        public override ProcessResult Execute(ProcessInfo processInfo)
        {
            char bell = (char) 0x07;
            char empty = ' ';

            ProcessResult retVal = base.Execute(processInfo);
            string standardOutput = retVal.StandardOutput.Replace(bell, empty);
            string standardError = retVal.StandardError.Replace(bell, empty);
            return new ProcessResult(standardOutput, standardError, retVal.ExitCode, retVal.TimedOut);
        }
Beispiel #5
0
 protected ProcessResult AttemptToExecute(ProcessInfo info)
 {
     try
     {
         return executor.Execute(info);
     }
     catch (Exception e)
     {
         throw new BuilderException(this, string.Format("Unable to execute: {0}\n{1}", info, e), e);
     }
 }
Beispiel #6
0
        public static ProcessResult RunSvnProcess(SvnOptions svnLoginOptions, ProcessArgumentBuilder argBuilder)
        {
            argBuilder.AddArgument("--non-interactive");
            argBuilder.AddArgument("--no-auth-cache");

            ProcessInfo info = new ProcessInfo("svn.exe", argBuilder.ToString());

            ProcessExecutor executor = new ProcessExecutor();
            ProcessResult result = executor.Execute(info);
            return result;
        }
		public void ExecuteNUnitConsoleAndRetrieveResultsFromFile()
		{
		    string args = string.Format(@"/xml={0} /nologo foo.dll", GeneratePath("{0}", task.OutputFile));
		    ProcessInfo info = new ProcessInfo(NUnitConsolePath, args, WORKING_DIRECTORY);
			info.TimeOut = NUnitTask.DefaultTimeout * 1000;
			executorMock.ExpectAndReturn("Execute", new ProcessResult("", String.Empty, 0, false), new object[] { info });

			task.Run(result);

			Assert.AreEqual("foo", result.TaskOutput);
			executorMock.Verify();
		}
Beispiel #8
0
        /// <summary>
        /// Deletes a directory on Windows with a commandline call.
        /// 
        /// Reason:
        /// .NET only supports filenames up to 260 characters long for backwards compability
        /// read more at: http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx
        /// this is a Windows only limitation
        /// </summary>
        /// <param name="path">Path to delete.</param>
        static void DeleteDirectoryWithLongPath(string path)
        {
            Log.Info("[IoService] Try running 'cmd.exe /C RD /S /Q' to delete '{0}'", path);

            // call a commandline delete as fallback
            var executor = new ProcessExecutor();
            var processInfo = new ProcessInfo("cmd.exe",
                string.Concat("/C RD /S /Q ", StringUtil.AutoDoubleQuoteString(path)));

            var pr = executor.Execute(processInfo);
            if (pr.Failed)
                throw new CruiseControlException(string.Format("Unable to delete path '{0}'.", path));
        }
		public void ShouldGetSourceIfAutoGetSourceTrue()
		{
			DynamicMock executor = new DynamicMock(typeof(ProcessExecutor));
			AccuRev accurev = new AccuRev((ProcessExecutor) executor.MockInstance);
			accurev.AutoGetSource = true;

			ProcessInfo expectedProcessRequest = new ProcessInfo("accurev.exe", "update");
			expectedProcessRequest.TimeOut = Timeout.DefaultTimeout.Millis;

			executor.ExpectAndReturn("Execute", new ProcessResult("foo", null, 0, false), expectedProcessRequest);
			accurev.GetSource(new IntegrationResult());
			executor.Verify();
		}
 public IHgResult Execute(HgArguments hgArguments)
 {
     if (hgArguments == null)
     {
         throw new ArgumentNullException("hgArguments");
     }
     _processExecutor.ProcessOutput += HandleProcessOutput;
     try
     {
         var processInfo = new ProcessInfo("hg", hgArguments.ToString());
         var result = _processExecutor.Execute(processInfo);
         return new CruiseControlHgResult(result);
     }
     finally
     {
         _processExecutor.ProcessOutput -= HandleProcessOutput;
     }
 }
		public void ShouldDeleteClientSpecAndWorkingDirectoryOnPurge()
		{
			// Setup
			DynamicMock p4Mock = new DynamicMock(typeof(P4));
			P4 p4 = (P4) p4Mock.MockInstance;
			p4.Client = "myClient";

			ProcessInfo processInfo = new ProcessInfo("deleteclient");
			processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", processInfo, p4, "client -d myClient");
			processExecutorMock.ExpectAndReturn("Execute", new ProcessResult("", "", 0, false), processInfo);

			Assert.IsTrue(Directory.Exists(tempDirPath));

			// Execute
			p4Purger.Purge(p4, tempDirPath);

			// Verify
			Assert.IsFalse(Directory.Exists(tempDirPath));
			VerifyAll();
		}
        protected ProcessResult Execute(ProcessInfo processInfo)
        {
            processInfo.TimeOut = Timeout.Millis;
            ProcessResult result = executor.Execute(processInfo);

            if (result.TimedOut)
            {
                throw new CruiseControlException("Source control operation has timed out.");
            }
            else if (result.Failed)
            {
                throw new CruiseControlException(string.Format("Source control operation failed: {0}. Process command: {1} {2}",
                                                               result.StandardError, processInfo.FileName, processInfo.Arguments));
            }
            else if (result.HasErrorOutput)
            {
                Log.Warning(string.Format("Source control wrote output to stderr: {0}", result.StandardError));
            }
            return result;
        }
        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;
        }
        public override ProcessResult Execute(ProcessInfo processInfo)
        {
            if (processInfo == null)
            {
                throw new ArgumentNullException("processInfo");
            }

            var complete = false;

            var process = processInfo.CreateProcess();
            var outputBuilder = new StringBuilder();
            var errorBuilder = new StringBuilder();
            process.EnableRaisingEvents = true;
            process.Exited += (sender, args) => { complete = true; };
            process.Start();
            while (!complete)
            {
                outputBuilder.Append(process.StandardOutput.ReadToEnd());
                errorBuilder.Append(process.StandardError.ReadToEnd());
            }
            return new ProcessResult(outputBuilder.ToString(), errorBuilder.ToString(), process.ExitCode, false);
        }
        public void CreatesAClientWithConstructedClientNameIfOneNotSpecifiedAndSavesClientNameInConfig()
        {
            // Setup
            P4 p4 = new P4();
            p4.View = "//mydepot/...";
            string projectName = "myProject";

            string expectedClientName = string.Format("CCNet-{0}-{1}", Dns.GetHostName(), projectName);

            ProcessInfo processInfo = new ProcessInfo("createclient");
            ProcessInfo processInfoWithStdInContent = new ProcessInfo("createclient");
            processInfoWithStdInContent.StandardInputContent = string.Format("Client: {0}\n\nRoot:   c:\\my\\working\\dir\n\nView:\n //mydepot/... //{0}/mydepot/...\n", expectedClientName);

            processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", processInfo, p4, "client -i");
            processExecutorMock.ExpectAndReturn("Execute", new ProcessResult("", "", 0, false), processInfoWithStdInContent);

            // Execute
            p4Initializer.Initialize(p4, projectName, @"c:\my\working\dir");

            // Verify
            Assert.AreEqual(expectedClientName, p4.Client);
            VerifyAll();
        }
        public void CreatesAClientWithGivenClientNameIfSpecified()
        {
            // Setup
            DynamicMock p4Mock = new DynamicMock(typeof(P4));
            P4 p4 = (P4) p4Mock.MockInstance;
            p4.Client = "myClient";

            p4Mock.SetupResult("ViewForSpecifications", new string[] { "//mydepot/...", "//myotherdepot/..." });

            ProcessInfo processInfo = new ProcessInfo("createclient");
            ProcessInfo processInfoWithStdInContent = new ProcessInfo("createclient");
            processInfoWithStdInContent.StandardInputContent = "Client: myClient\n\nRoot:   c:\\my\\working\\dir\n\nView:\n //mydepot/... //myClient/mydepot/...\n //myotherdepot/... //myClient/myotherdepot/...\n";

            processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", processInfo, p4, "client -i");
            processExecutorMock.ExpectAndReturn("Execute", new ProcessResult("", "", 0, false), processInfoWithStdInContent);

            // Execute
            p4Initializer.Initialize(p4, "myProject", @"c:\my\working\dir");

            // Verify
            p4Mock.Verify();
            VerifyAll();
        }
Beispiel #17
0
        public void GetModifications()
        {
            string changes = @"
            info: Change 3328 on 2002/10/31 by someone@somewhere 'Something important '
            info: Change 3327 on 2002/10/31 by someone@somewhere 'Joe's test '
            info: Change 332 on 2002/10/31 by someone@somewhere 'thingy'
            exit: 0
            ";

            P4 p4 = CreateP4();

            ProcessInfo info = new ProcessInfo("p4.exe");
            processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", info, p4, "changes -s submitted ViewData@0001/01/01:00:00:00");
            mockProcessExecutor.ExpectAndReturn("Execute", new ProcessResult(changes, "", 0, false), info);
            processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", info, p4, "describe -s 3328 3327 332");
            mockProcessExecutor.ExpectAndReturn("Execute", new ProcessResult(P4Mother.P4_LOGFILE_CONTENT, "", 0, false), info);

            p4.View = "ViewData";
            p4.P4WebURLFormat = "http://*****:*****@md=d&amp;cd=//&amp;c=3IB@/{0}?ac=10";
            Modification[] result = p4.GetModifications(new IntegrationResult(), new IntegrationResult());

            VerifyAll();
            Assert.AreEqual(7, result.Length);
            Assert.AreEqual("http://*****:*****@md=d&amp;cd=//&amp;c=3IB@/3328?ac=10", result[0].Url);
            Assert.AreEqual("http://*****:*****@md=d&amp;cd=//&amp;c=3IB@/3327?ac=10", result[3].Url);
        }
 public override ProcessResult Execute(ProcessInfo processInfo)
 {
     return RemoteContext.GetRemoteContext().Controller.RemoteExecute(processInfo, OnProcessOutput);
 }
		private ProcessInfo NewProcessInfoFrom(IIntegrationResult result)
		{
            ProcessInfo info = new ProcessInfo(GetFBPath(), GetFBArgs());
			info.TimeOut = Timeout*1000;
            int idx = ProjectFile.LastIndexOf('\\');
            if (idx > -1)
              info.WorkingDirectory = ProjectFile.Remove(idx, ProjectFile.Length - idx); // Trim down proj. file to get working dir.

            // Add IntegrationProperties as environment variables
			foreach (string varName in result.IntegrationProperties.Keys)
			{
				object obj1 = result.IntegrationProperties[varName];
				if ((obj1 != null) && !info.EnvironmentVariables.ContainsKey(varName))
				{
				  info.EnvironmentVariables.Add(varName, StringUtil.StripThenEncodeParameterArgument(StringUtil.RemoveTrailingPathDelimeter(StringUtil.IntegrationPropertyToString(obj1))));
				}
			}           
			return info;
		}
        /// <summary>
        /// Attempts to execute.	
        /// </summary>
        /// <param name="info">The info.</param>
        /// <param name="projectName">Name of the project.</param>
        /// <returns></returns>
        /// <remarks></remarks>
		protected ProcessResult AttemptToExecute(ProcessInfo info, string projectName)
		{
			try
			{
				return _executor.Execute(info);
			}
			catch (Exception e)
			{
				throw new BuilderException(this, string.Format(System.Globalization.CultureInfo.CurrentCulture,"FBCMD unable to execute: {0}\n{1}", info, e), e);
			}
		}
Beispiel #21
0
 private ProcessInfo NewProcessInfo(string args, IIntegrationResult result)
 {
     ProcessInfo pi = new ProcessInfo(Executable, args, result.BaseFromWorkingDirectory(WorkingDirectory));
     // Needed to disable the pager for bk commands, which causes infinite hangs
     pi.EnvironmentVariables.Add("PAGER", "cat");
     return pi;
 }
Beispiel #22
0
        private ProcessInfo NewProcessInfoWith(PrivateArguments args, IIntegrationResult result)
        {
            string workingDirectory = result.BaseFromWorkingDirectory(WorkingDirectory);
            if (! Directory.Exists(workingDirectory)) Directory.CreateDirectory(workingDirectory);

            ProcessInfo processInfo = new ProcessInfo(Executable, args, workingDirectory);
            if (SsDir != null)
            {
                processInfo.EnvironmentVariables[SS_DIR_KEY] = SsDir;
            }
            return processInfo;
        }
		public void ShouldGetSourceIfAutoGetSourceTrue()
		{
			DynamicMock executor = new DynamicMock(typeof(ProcessExecutor));
            ExternalSourceControl externalSC = new ExternalSourceControl((ProcessExecutor)executor.MockInstance);
            externalSC.AutoGetSource = true;
		    externalSC.Executable = "banana.bat";
		    externalSC.ArgString = @"arg1 ""arg2 is longer"" arg3";

		    IntegrationResult intResult = new IntegrationResult();
            intResult.StartTime = new DateTime(1959,9,11,7,53,0);
		    intResult.WorkingDirectory = @"C:\SomeDir\Or\Other";
            intResult.ProjectName = "MyProject";

			ProcessInfo expectedProcessRequest = new ProcessInfo(
                "banana.bat", 
                @"GETSOURCE ""C:\SomeDir\Or\Other"" ""1959-09-11 07:53:00"" arg1 ""arg2 is longer"" arg3",
                @"C:\SomeDir\Or\Other"
                );
			expectedProcessRequest.TimeOut = Timeout.DefaultTimeout.Millis;

			executor.ExpectAndReturn("Execute", new ProcessResult("foo", null, 0, false), expectedProcessRequest);
            externalSC.GetSource(intResult);
			executor.Verify();
		}
Beispiel #24
0
 private void ExecuteWithLogging(ProcessInfo processInfo, string comment)
 {
     Log.Info(string.Format(comment + " : {0} {1}", processInfo.FileName, processInfo.PublicArguments));
     Execute(processInfo);
 }
		private void ValidateProcessInfo(ProcessInfo actual, string arguments)
		{
			Assert.IsNotNull(actual);
			Assert.AreEqual(connection.Executable, actual.FileName);
			Assert.AreEqual(connection.WorkingDirectory, actual.WorkingDirectory);
			Assert.AreEqual(arguments, actual.Arguments);
		}
Beispiel #26
0
        /// <summary>
        /// Set default environment variables for CVS
        /// </summary>
        /// <param name="pi">The command.</param>
        /// <param name="result">IntegrationResult for which the command is being run.</param>
        private void SetEnvironmentVariables(ProcessInfo pi, IIntegrationResult result)
        {
            if(executionEnvironment.IsRunningOnWindows)
            {
                var cvsHomePath = result.ArtifactDirectory.TrimEnd(Path.DirectorySeparatorChar);

                // set %HOME% env var (see http://jira.public.thoughtworks.org/browse/CCNET-1793)
                pi.EnvironmentVariables["HOME"] = cvsHomePath;

                //ensure %HOME%\.cvspass file exists (see http://jira.public.thoughtworks.org/browse/CCNET-1795)
                fileSystem.EnsureFileExists(Path.Combine(cvsHomePath, ".cvspass"));
                Log.Debug("[CVS] Set %HOME% environment variable to '{0}'.", cvsHomePath);
            }
        }
Beispiel #27
0
        private ProcessInfo NewProcessInfoWithArgs(IIntegrationResult result, string args)
        {
            var wd = result.BaseFromWorkingDirectory(WorkingDirectory);
            // ensure working directory exists
            fileSystem.EnsureFolderExists(wd);

            var pi = new ProcessInfo(Executable, args, wd);
            SetEnvironmentVariables(pi, result);
            return pi;
        }
Beispiel #28
0
        public void GetSourceIfGetSourceTrue()
        {
            P4 p4 = CreateP4();
            p4.View = "//depot/myproject/...";
            p4.AutoGetSource = true;

            DateTime modificationsToDate = new DateTime(2002, 10, 31, 5, 5, 0);
            ProcessInfo processInfo = new ProcessInfo("getSource");
            processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", processInfo, p4, "sync @2002/10/31:05:05:00");
            mockProcessExecutor.ExpectAndReturn("Execute", new ProcessResult("", "", 0, false), processInfo);
            p4.GetSource(IntegrationResultMother.CreateSuccessful(modificationsToDate));

            VerifyAll();
        }
Beispiel #29
0
        public void LabelSourceControlIfApplyLabelTrueWithMultiLineViews()
        {
            P4 p4 = CreateP4();
            p4.View = "//depot/myproj/...,//myotherdepot/proj/...";
            p4.ApplyLabel = true;

            ProcessInfo labelSpecProcess = new ProcessInfo("spec");
            ProcessInfo labelSpecProcessWithStdInContent = new ProcessInfo("spec");
            labelSpecProcessWithStdInContent.StandardInputContent = "Label:	foo-123\n\nDescription:\n	Created by CCNet\n\nOptions:	unlocked\n\nView:\n //depot/myproj/...\n //myotherdepot/proj/...\n";
            ProcessInfo labelSyncProcess = new ProcessInfo("sync");

            processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", labelSpecProcess, p4, "label -i");
            mockProcessExecutor.ExpectAndReturn("Execute", new ProcessResult("", "", 0, false), labelSpecProcessWithStdInContent);
            processInfoCreatorMock.ExpectAndReturn("CreateProcessInfo", labelSyncProcess, p4, "labelsync -l foo-123");
            mockProcessExecutor.ExpectAndReturn("Execute", new ProcessResult("", "", 0, false), labelSyncProcess);

            // Execute
            p4.LabelSourceControl(IntegrationResultMother.CreateSuccessful("foo-123"));

            // Verify
            VerifyAll();
        }
		/// <summary>
		///     Executes a CM Synergy command.
		/// </summary>
		/// <exception cref="CruiseControlException">
		///     Thrown if the CM Synergy command exceeds the configured
		///     <see cref="ProcessInfo.TimeOut"/>, or if <paramref see="failOnError" />
		///     is <see langword="true"/> and the commands returns non-zero.
		/// </exception>
		/// <param name="processInfo">
		///     <see langword="true"/> if a <see cref="CruiseControlException"/>
		///     should be thrown if the CM Synergy command does not return
		///     <c>0</c>.
		/// </param>
		/// <param name="failOnError">
		///     Indicates if a <see cref="CruiseControlException"/> should be thrown
		///     if non-zero is returned by the command.
		/// </param>
		/// <returns>The result of the command.</returns>
		public ProcessResult Execute(ProcessInfo processInfo, bool failOnError)
		{
			// require an active session
			ValidateSession();

			/* If the work area path is known, use it instead of the working directory.
             * This should be OK, thanks to the ProcessInfo.RepathExecutableIfItIsInWorkingDirectory
             * implementation, which is called by the non-default ProcessInfo(string,string,string)
             * constructor that we use in SynergyCommandBuilder.CreateProcessInfo */
			if (null != project && null != project.WorkAreaPath && project.WorkAreaPath.Length > 0)
			{
				processInfo = new ProcessInfo(processInfo.FileName, processInfo.Arguments, project.WorkAreaPath);
			}

			// set the session id for ccm.exe to use
			processInfo.EnvironmentVariables[SessionToken] = connection.SessionId;
			// always use invariant (EN-US) date/time formats
			processInfo.EnvironmentVariables[DateTimeFormat] = DateTimeFormat;

			// convert from seconds to milliseconds
			processInfo.TimeOut = connection.Timeout*1000;

			ProcessResult result = executor.Execute(processInfo);
			if (result.TimedOut)
			{
				string message = String.Format(CultureInfo.CurrentCulture, @"Synergy source control operation has timed out after {0} seconds. Process command: ""{1}"" {2}", connection.Timeout, processInfo.FileName, processInfo.PublicArguments);
				throw(new CruiseControlException(message));
			}

			if (result.Failed && failOnError)
			{
				string message = string.Format(System.Globalization.CultureInfo.CurrentCulture,"Synergy source control operation failed.\r\n" + "Command: \"{0}\" {1}\r\n" + "Error Code: {2}\r\n" + "Errors:\r\n{3}\r\n{4}", processInfo.FileName, processInfo.PublicArguments, result.ExitCode, result.StandardError, result.StandardOutput);

				if (result.HasErrorOutput)
				{
					Log.Warning(string.Format(System.Globalization.CultureInfo.CurrentCulture,"Synergy wrote output to stderr: {0}", result.StandardError));
				}

				throw(new CruiseControlException(message));
			}
			return result;
		}