示例#1
0
        protected override string GenerateCommandLineCommands()
        {
            var args = new ProcessArgumentBuilder ();

            args.Add ("-v");
            args.Add ("--force");
            args.Add ("--sign");
            args.AddQuoted (SigningKey);

            if (!string.IsNullOrEmpty (Keychain)) {
                args.Add ("--keychain");
                args.AddQuoted (Path.GetFullPath (Keychain));
            }

            if (!string.IsNullOrEmpty (ResourceRules)) {
                args.Add ("--resource-rules");
                args.AddQuoted (Path.GetFullPath (ResourceRules));
            }

            if (!string.IsNullOrEmpty (Entitlements)) {
                args.Add ("--entitlements");
                args.AddQuoted (Path.GetFullPath (Entitlements));
            }

            if (!string.IsNullOrEmpty (ExtraArgs))
                args.Add (ExtraArgs);

            args.AddQuoted (Path.GetFullPath (Resource));

            return args.ToString ();
        }
示例#2
0
		public static BuildResult CompileXibFiles (IProgressMonitor monitor, IEnumerable<ProjectFile> files,
		                                           FilePath outputRoot)
		{
			var result = new BuildResult ();
			var ibfiles = GetIBFilePairs (files, outputRoot).Where (NeedsBuilding).ToList ();
			
			if (ibfiles.Count > 0) {
				monitor.BeginTask (GettextCatalog.GetString ("Compiling interface definitions"), 0);	
				foreach (var file in ibfiles) {
					file.EnsureOutputDirectory ();
					var args = new ProcessArgumentBuilder ();
					args.AddQuoted (file.Input);
					args.Add ("--compile");
					args.AddQuoted (file.Output);
					var psi = new ProcessStartInfo ("ibtool", args.ToString ());
					monitor.Log.WriteLine (psi.FileName + " " + psi.Arguments);
					psi.WorkingDirectory = outputRoot;
					string errorOutput;
					int code;
					try {
					code = ExecuteCommand (monitor, psi, out errorOutput);
					} catch (System.ComponentModel.Win32Exception ex) {
						LoggingService.LogError ("Error running ibtool", ex);
						result.AddError (null, 0, 0, null, "ibtool not found. Please ensure the Apple SDK is installed.");
						return result;
					}
					if (code != 0) {
						//FIXME: parse the plist that ibtool returns
						result.AddError (null, 0, 0, null, "ibtool returned error code " + code);
					}
				}
				monitor.EndTask ();
			}
			return result;
		}
示例#3
0
        public void BuildArguments(ICakeContext context, ProcessArgumentBuilder builder)
        {
            if (NoGraphics)
            {
                builder.Append("-nographics");
            }

            builder.Append(PlatformTarget == UnityPlatformTarget.x64 ? "-buildWindows64Player" : "-buildWindowsPlayer");
            builder.AppendQuoted(_outputPath.MakeAbsolute(context.Environment).FullPath);
        }
示例#4
0
        protected override string GenerateCommandLineCommands()
        {
            var args = new ProcessArgumentBuilder ();

            args.Add ("-rsrc");

            args.AddQuoted (Source.ItemSpec);
            args.AddQuoted (Destination.ItemSpec);

            return args.ToString ();
        }
        public void Test_With_No_Arguments(Type escapeHandlerType, string sigil)
        {
            // Arrange
            var escapeHandler = Activator.CreateInstance(escapeHandlerType, new object[] { sigil }) as IArgumentEscapeHandler;
            var builder = new ProcessArgumentBuilder(escapeHandler);

            // Act
            var result = builder.Build();

            // Assert
            Assert.Equal("", result);
        }
            public void Should_Make_Project_Path_Absolute()
            {
                // Given
                var context = UnityPlatformFixture.CreateContext();
                var builder = new ProcessArgumentBuilder();
                var platform = new WindowsPlatform("Project/Game.exe");

                // When
                platform.BuildArguments(context, builder);

                // Then
                Assert.Equal("-buildWindowsPlayer \"/Working/Project/Game.exe\"", builder.Render());
            }
            public void Should_Use_64_Bit_Platform_If_Specified()
            {
                // Given
                var context = UnityPlatformFixture.CreateContext();
                var builder = new ProcessArgumentBuilder();
                var platform = new WindowsPlatform("C:/Project/Game.exe") { PlatformTarget = UnityPlatformTarget.x64 };

                // When
                platform.BuildArguments(context, builder);

                // Then
                Assert.Equal("-buildWindows64Player \"C:/Project/Game.exe\"", builder.Render());
            }
            public void Should_Add_NoGraphics_Switch_If_Specified()
            {
                // Given
                var context = UnityPlatformFixture.CreateContext();
                var builder = new ProcessArgumentBuilder();
                var platform = new WindowsPlatform("C:/Project/Game.exe");
                platform.NoGraphics = true;

                // When
                platform.BuildArguments(context, builder);

                // Then
                Assert.Equal("-nographics -buildWindowsPlayer \"C:/Project/Game.exe\"", builder.Render());
            }
        public void Test_Multiple_Arguments(string argumentValueSeparator, string sigil, string firstArgument, string secondArgument,
            string firstArgumentExpectedOutput, string secondArgumentExpectedOutput, Type escapeHandlerType)
        {
            // Arrange
            var s = sigil;
            var escapeHandler = Activator.CreateInstance(escapeHandlerType, new object[] { sigil }) as IArgumentEscapeHandler;
            var builder = new ProcessArgumentBuilder(escapeHandler, argumentValueSeparator);
            builder.AddOption($"{s}help");
            builder.AddNamedArgument($"{s}f", firstArgument);
            builder.AddNamedArgument($"{s}o", secondArgument, "=");

            // Act
            var result = builder.Build();

            // Assert
            Assert.Equal($"{s}help {s}f{argumentValueSeparator}{firstArgumentExpectedOutput} {s}o={secondArgumentExpectedOutput}", result);
        }
示例#10
0
            private void ExecuteProcess(FilePath filePath, ProcessArgumentBuilder arguments, int timeout = 60000)
            {
                try
                {
                    filePath = filePath.MakeAbsolute(_Environment.WorkingDirectory);

                    _Runner.Start(filePath, new ProcessSettings()
                            {
                                Arguments = arguments
                            })
                            .WaitForExit(timeout);
                }
                catch (Exception ex)
                {
                    if (!(ex is TimeoutException)) throw;

                    _Log.Warning("Process timed out!");
                }
            }
示例#11
0
        protected override string GenerateCommandLineCommands()
        {
            var args = new ProcessArgumentBuilder ();

            if (Recursive)
                args.Add ("-r");

            if (Symlinks)
                args.Add ("-y");

            args.AddQuoted (OutputFile.GetMetadata ("FullPath"));

            var root = WorkingDirectory.GetMetadata ("FullPath");
            for (int i = 0; i < Sources.Length; i++) {
                var relative = PathUtils.AbsoluteToRelative (root, Sources[i].GetMetadata ("FullPath"));
                args.AddQuoted (relative);
            }

            return args.ToString ();
        }
 protected abstract void AppendCommandLineArguments(IDictionary <string, string> environment, ProcessArgumentBuilder args, ITaskItem[] items);
示例#13
0
 /// <summary>
 /// Runs the tool using a custom tool path and the specified settings.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="arguments">The arguments.</param>
 /// <returns>The process that the tool is running under.</returns>
 protected IProcess RunProcess(TSettings settings, ProcessArgumentBuilder arguments)
 {
     return(RunProcess(settings, arguments, null));
 }
示例#14
0
		static bool BuildPackage (IProgressMonitor monitor, MonoMacProject project,
			ConfigurationSelector conf, MonoMacPackagingSettings settings, FilePath target)
		{
			string bundleKey = settings.BundleSigningKey;
			string packageKey = settings.PackageSigningKey;
			
			if (settings.SignBundle || settings.SignPackage) {
				var identities = Keychain.GetAllSigningIdentities ();
				
				if (string.IsNullOrEmpty (bundleKey)) {
					bundleKey = identities.FirstOrDefault (k => k.StartsWith (MonoMacPackagingSettingsWidget.APPLICATION_PREFIX));
					if (string.IsNullOrEmpty (bundleKey)) {
						monitor.ReportError ("Did not find default app signing key", null);
						return false;
					} else if (!identities.Any (k => k == bundleKey)) {
						monitor.ReportError ("Did not find app signing key in keychain", null);
						return false;
					}
				}
				
				if (string.IsNullOrEmpty (packageKey)) {
					packageKey = identities.FirstOrDefault (k => k.StartsWith (MonoMacPackagingSettingsWidget.INSTALLER_PREFIX));
					if (string.IsNullOrEmpty (packageKey)) {
						monitor.ReportError ("Did not find default package signing key", null);
						return false;
					} else if (!identities.Any (k => k == packageKey)) {
						monitor.ReportError ("Did not find package signing key in keychain", null);
						return false;
					}
				}
			}
			
			if (project.NeedsBuilding (conf)) {
				BuildResult res = project.Build (monitor, conf);
				if (res.ErrorCount > 0) {
					foreach (BuildError e in res.Errors)
						monitor.ReportError (e.ToString (), null);
					monitor.ReportError (GettextCatalog.GetString ("The project failed to build."), null);
					return false;
				}
			}
			
			var cfg = (MonoMacProjectConfiguration) project.GetConfiguration (conf);
			
			FilePath tempDir = "/tmp/monomac-build-" + DateTime.Now.Ticks;
			FilePath workingApp = tempDir.Combine (cfg.AppDirectory.FileName);
			
			try {
				monitor.BeginTask (GettextCatalog.GetString ("Creating app bundle"), 0);
				var files = Directory.GetFiles (cfg.AppDirectory, "*", SearchOption.AllDirectories);
				HashSet<string> createdDirs = new HashSet<string> ();
				foreach (FilePath f in files) {
					var rel = f.ToRelative (cfg.AppDirectory);
					var parentDir = rel.ParentDirectory;
					if (settings.IncludeMono) {
						if (parentDir.IsNullOrEmpty || parentDir == "." || parentDir == "Contents/MacOS")
							continue;
						var ext = rel.Extension;
						if (ext == ".mdb" || ext == ".exe" || ext == ".dll")
							continue;
					}
					if (monitor.IsCancelRequested)
						return false;
					if (createdDirs.Add (parentDir))
						Directory.CreateDirectory (workingApp.Combine (parentDir));
					monitor.Log.WriteLine (rel);
					File.Copy (f, workingApp.Combine (rel));
				}
				monitor.EndTask ();
				
				if (settings.IncludeMono) {
					monitor.BeginTask (GettextCatalog.GetString ("Merging Mono into app bundle"), 0);
					
					var args = new ProcessArgumentBuilder ();
					args.Add ("-o");
					args.AddQuoted (tempDir);
					args.Add ("-n");
					args.AddQuoted (cfg.AppName);
					
					var assemblies = project.GetReferencedAssemblies (conf, true);
					foreach (var a in assemblies) {
						args.Add ("-a");
						args.AddQuoted (a);
					}
					args.AddQuoted (cfg.CompiledOutputName);
					
					string mmpPath = Mono.Addins.AddinManager.CurrentAddin.GetFilePath ("mmp");
					var psi = new ProcessStartInfo (mmpPath, args.ToString ());
					monitor.Log.WriteLine ("mmp " + psi.Arguments);
					
					string err;
					if (MacBuildUtilities.ExecuteCommand (monitor, psi, out err) != 0) {
						monitor.Log.WriteLine (err);
						monitor.ReportError ("Merging Mono failed", null);
						return false;
					}
					
					var plistFile = workingApp.Combine ("Contents", "Info.plist");
					var plistDoc = new PlistDocument ();
					plistDoc.LoadFromXmlFile (plistFile);
					((PlistDictionary)plistDoc.Root)["MonoBundleExecutable"] = cfg.CompiledOutputName.FileName;
					plistDoc.WriteToFile (plistFile);
					
					monitor.EndTask ();
				}
				
				//TODO: verify bundle details if for app store?
					
				if (settings.SignBundle) {
					monitor.BeginTask (GettextCatalog.GetString ("Signing app bundle"), 0);
					
					var args = new ProcessArgumentBuilder ();
					args.Add ("-v", "-f", "-s");
					args.AddQuoted (bundleKey, workingApp);
					
					var psi = new ProcessStartInfo ("codesign", args.ToString ());
					monitor.Log.WriteLine ("codesign " + psi.Arguments);
					
					string err;
					if (MacBuildUtilities.ExecuteCommand (monitor, psi, out err) != 0) {
						monitor.Log.WriteLine (err);
						monitor.ReportError ("Signing failed", null);
						return false;
					}
					
					monitor.EndTask ();
				}
				
				if (settings.CreatePackage) {
					monitor.BeginTask (GettextCatalog.GetString ("Creating installer"), 0);
					
					var args = new ProcessArgumentBuilder ();
					args.Add ("--component");
					args.AddQuoted (workingApp);
					args.Add ("/Applications", "--sign");
					args.AddQuoted (packageKey);
					if (!settings.ProductDefinition.IsNullOrEmpty) {
						args.Add ("--product");
						args.AddQuoted (settings.ProductDefinition);
					}
					args.AddQuoted (target);
					
					var psi = new ProcessStartInfo ("productbuild", args.ToString ());
					monitor.Log.WriteLine ("productbuild " + psi.Arguments);
					
					string err;
					if (MacBuildUtilities.ExecuteCommand (monitor, psi, out err) != 0) {
						monitor.Log.WriteLine (err);
						monitor.ReportError ("Package creation failed", null);
						return false;
					}
					monitor.EndTask ();
				} else {
					Directory.Move (workingApp, target);
				}
			} finally {
				try {
					if (Directory.Exists (tempDir))
						Directory.Delete (tempDir, true);
				} catch (Exception ex) {
					LoggingService.LogError ("Error removing temp directory", ex);
				}
			}
			
			return true;
		}
示例#15
0
        private ProcessArgumentBuilder GetArguments(FilePath packageFilePath, ChocolateyPushSettings settings)
        {
            var builder = new ProcessArgumentBuilder();

            builder.Append("push");

            builder.Append(packageFilePath.MakeAbsolute(_environment).FullPath);

            if (settings.Source != null)
            {
                builder.Append("-s");
                builder.Append(settings.Source);
            }

            if (settings.Timeout != null)
            {
                builder.Append("-t");
                builder.Append(Convert.ToInt32(settings.Timeout.Value.TotalSeconds).ToString(CultureInfo.InvariantCulture));
            }

            if (settings.ApiKey != null)
            {
                builder.Append("-k");
                builder.AppendSecret(settings.ApiKey);
            }

            // Debug
            if (settings.Debug)
            {
                builder.Append("-d");
            }

            // Verbose
            if (settings.Verbose)
            {
                builder.Append("-v");
            }

            // Always say yes, so as to not show interactive prompt
            builder.Append("-y");

            // Force
            if (settings.Force)
            {
                builder.Append("-f");
            }

            // Noop
            if (settings.Noop)
            {
                builder.Append("--noop");
            }

            // Limit Output
            if (settings.LimitOutput)
            {
                builder.Append("-r");
            }

            // Execution Timeout
            if (settings.ExecutionTimeout != 0)
            {
                builder.Append("--execution-timeout");
                builder.Append(settings.ExecutionTimeout.ToString(CultureInfo.InvariantCulture));
            }

            // Cache Location
            if (!string.IsNullOrWhiteSpace(settings.CacheLocation))
            {
                builder.Append("-c");
                builder.Append(settings.CacheLocation);
            }

            // Allow Unofficial
            if (settings.AllowUnofficial)
            {
                builder.Append("--allowunofficial");
            }

            return(builder);
        }
		void StartLogTracking ()
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-v time");
			foreach (string tag in excludedLogTags)
				args.Add (tag + ":S");

			trackLogOp = new AdbTrackLogOperation (device, ProcessLogLine, args.ToString ());
			trackLogOp.Completed += delegate (IAsyncOperation op) {
				if (!op.Success) {
					SetCompleted (false);
				}
			};
		}
示例#17
0
		public InstallPackageOperation Install (AndroidDevice device, string package, TextWriter outputLog, TextWriter errorLog)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-s", device.ID, "install");
			args.AddQuoted (package);
			
			var errorCapture = new StringWriter ();
			var errorWriter = TeeTextWriter.ForNonNull (errorCapture, errorCapture);
			return new InstallPackageOperation (StartProcess (AdbExe, args.ToString (), outputLog, errorWriter), errorCapture);
		}
示例#18
0
 private void AppendQuoted(ProcessArgumentBuilder builder, string key, string value)
 {
     builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "-{0}:{1}", key, value));
 }
		static void AddExtraArgs (ProcessArgumentBuilder args, string extraArgs, IPhoneProject proj,
			IPhoneProjectConfiguration conf)
		{
			if (!string.IsNullOrEmpty (extraArgs)) {
				var customTags = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase) {
					{ "projectdir",   ProcessArgumentBuilder.EscapeQuotes (proj.BaseDirectory) },
					{ "solutiondir",  ProcessArgumentBuilder.EscapeQuotes (proj.ParentSolution.BaseDirectory) },
					{ "appbundledir", ProcessArgumentBuilder.EscapeQuotes (conf.AppDirectory) },
					{ "targetpath",   ProcessArgumentBuilder.EscapeQuotes (conf.CompiledOutputName) },
					{ "targetdir",    ProcessArgumentBuilder.EscapeQuotes (conf.CompiledOutputName.ParentDirectory) },
					{ "targetname",   ProcessArgumentBuilder.EscapeQuotes (conf.CompiledOutputName.FileName) },
					{ "targetext",    ProcessArgumentBuilder.EscapeQuotes (conf.CompiledOutputName.Extension) },
				};
				args.Add (StringParserService.Parse (extraArgs, customTags));
			}
		}
示例#20
0
        private ProcessArgumentBuilder GetArguments(FilePath filePath, NuGetPackSettings settings)
        {
            var builder = new ProcessArgumentBuilder();

            builder.Append("pack");

            // Version
            if (!string.IsNullOrWhiteSpace(settings.Version))
            {
                builder.Append("-Version");
                builder.AppendQuoted(settings.Version);
            }

            // Version suffix
            if (!string.IsNullOrWhiteSpace(settings.Suffix))
            {
                builder.Append("-Suffix");
                builder.AppendQuoted(settings.Suffix);
            }

            // Base path
            if (settings.BasePath != null)
            {
                builder.Append("-BasePath");
                builder.AppendQuoted(settings.BasePath.MakeAbsolute(_environment).FullPath);
            }

            // Output directory
            if (settings.OutputDirectory != null)
            {
                builder.Append("-OutputDirectory");
                builder.AppendQuoted(settings.OutputDirectory.MakeAbsolute(_environment).FullPath);
            }

            // Nuspec file
            builder.AppendQuoted(filePath.MakeAbsolute(_environment).FullPath);

            // No package analysis?
            if (settings.NoPackageAnalysis)
            {
                builder.Append("-NoPackageAnalysis");
            }

            // IncludeReferencedProjects?
            if (settings.IncludeReferencedProjects)
            {
                builder.Append("-IncludeReferencedProjects");
            }

            // Symbols?
            if (settings.Symbols)
            {
                builder.Append("-Symbols");
            }

            // Verbosity
            if (settings.Verbosity != null)
            {
                builder.Append("-Verbosity");
                builder.Append(settings.Verbosity.Value.ToString().ToLowerInvariant());
            }

            // MSBuildVersion?
            if (settings.MSBuildVersion.HasValue)
            {
                builder.Append("-MSBuildVersion");
                builder.Append(settings.MSBuildVersion.Value.ToString("D"));
            }

            // Use the tool folder
            if (settings.OutputToToolFolder)
            {
                builder.Append("-Tool");
            }

            // Properties
            if (settings.Properties != null && settings.Properties.Count > 0)
            {
                if (settings.Properties.Values.Any(string.IsNullOrWhiteSpace))
                {
                    throw new CakeException("Properties values can not be null or empty.");
                }

                if (settings.Properties.Keys.Any(string.IsNullOrWhiteSpace))
                {
                    throw new CakeException("Properties keys can not be null or empty.");
                }
                builder.Append("-Properties");
                builder.AppendQuoted(string.Join(";",
                                                 settings.Properties.Select(property => string.Concat(property.Key, "=", property.Value))));
            }

            return(builder);
        }
示例#21
0
        private static void AddCommonParameters(string name, string source, NuGetSourcesSettings settings, ProcessArgumentBuilder builder)
        {
            builder.Append("-Name");
            builder.AppendQuoted(name);

            builder.Append("-Source");
            if (settings.IsSensitiveSource)
            {
                // Sensitive information in source.
                builder.AppendQuotedSecret(source);
            }
            else
            {
                builder.AppendQuoted(source);
            }

            // Verbosity?
            if (settings.Verbosity.HasValue)
            {
                builder.Append("-Verbosity");
                builder.Append(settings.Verbosity.Value.ToString().ToLowerInvariant());
            }

            builder.Append("-NonInteractive");
        }
示例#22
0
		public IProcessAsyncOperation StartActivity (AndroidDevice device, string activity,
			ProcessEventHandler outputLog, ProcessEventHandler errorLog)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-s", device.ID, "shell", "am", "start", "-a", "android.intent.action.MAIN", "-n");
			args.AddQuoted (activity);
			
			return StartProcess (AdbExe, args.ToString (), outputLog, errorLog);
		}
示例#23
0
		public IProcessAsyncOperation SetProperty (AndroidDevice device, string property, string value, TextWriter outputLog, TextWriter errorLog)
		{
			if (property == null)
				throw new ArgumentNullException ("property");
			if (value == null)
				throw new ArgumentNullException ("value");
			
			var args = new ProcessArgumentBuilder ();
			args.Add ("-s", device.ID, "shell", "setprop");
			args.AddQuoted (property, value);
			
			return StartProcess (AdbExe, args.ToString (), outputLog, errorLog);
		}
示例#24
0
		public IProcessAsyncOperation AlignPackage (string srcApk, string destApk, TextWriter outputLog, TextWriter errorLog)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-f");
			args.Add ("4");
			args.AddQuoted (srcApk);
			args.AddQuoted (destApk);

			return StartProcess (ZipAlignExe, args.ToString (), outputLog, errorLog);
		}
示例#25
0
        private ProcessArgumentBuilder GetArguments(IEnumerable <FilePath> assemblyPaths, NUnit3Settings settings)
        {
            var builder = new ProcessArgumentBuilder();

            // Add the assemblies to build.
            foreach (var assemblyPath in assemblyPaths)
            {
                builder.AppendQuoted(assemblyPath.MakeAbsolute(_environment).FullPath);
            }

            if (settings.Test != null)
            {
                builder.Append("--test=" + settings.Test);
            }

            if (settings.TestList != null)
            {
                builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "--testlist={0}", settings.TestList.MakeAbsolute(_environment).FullPath));
            }

            if (settings.Where != null)
            {
                builder.Append("--where \"" + settings.Where + "\"");
            }

            if (settings.Timeout.HasValue)
            {
                builder.Append("--timeout=" + settings.Timeout.Value);
            }

            if (settings.Seed.HasValue)
            {
                builder.Append("--seed=" + settings.Seed.Value);
            }

            if (settings.Workers.HasValue)
            {
                builder.Append("--workers=" + settings.Workers.Value);
            }

            if (settings.StopOnError)
            {
                builder.Append("--stoponerror");
            }

            if (settings.Work != null)
            {
                builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "--work={0}", settings.Work.MakeAbsolute(_environment).FullPath));
            }

            if (settings.OutputFile != null)
            {
                builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "--out={0}", settings.OutputFile.MakeAbsolute(_environment).FullPath));
            }

            #pragma warning disable 0618
            if (settings.ErrorOutputFile != null)
            {
                builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "--err={0}", settings.ErrorOutputFile.MakeAbsolute(_environment).FullPath));
            }

            if (settings.Full)
            {
                builder.Append("--full");
            }
            #pragma warning restore 0618

            if (HasResults(settings) && settings.NoResults)
            {
                throw new ArgumentException(
                          GetToolName() + ": You can't specify both a results file and set NoResults to true.");
            }

            if (HasResults(settings))
            {
                foreach (var result in settings.Results)
                {
                    var resultString = new StringBuilder(result.FileName.MakeAbsolute(_environment).FullPath);
                    if (result.Format != null)
                    {
                        resultString.AppendFormat(";format={0}", result.Format);
                    }
                    if (result.Transform != null)
                    {
                        resultString.AppendFormat(";transform={0}", result.Transform.MakeAbsolute(_environment).FullPath);
                    }
                    builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "--result={0}", resultString));
                }
            }
            else if (settings.NoResults)
            {
                builder.AppendQuoted("--noresult");
            }

            if (settings.Labels != NUnit3Labels.Off)
            {
                builder.Append("--labels=" + settings.Labels);
            }

            if (settings.TeamCity)
            {
                builder.Append("--teamcity");
            }

            if (settings.NoHeader)
            {
                builder.Append("--noheader");
            }

            if (settings.NoColor)
            {
                builder.Append("--nocolor");
            }

            #pragma warning disable 0618
            if (settings.Verbose)
            {
                builder.Append("--verbose");
            }
            #pragma warning restore 0618

            if (settings.Configuration != null)
            {
                builder.AppendQuoted("--config=" + settings.Configuration);
            }

            if (settings.Framework != null)
            {
                builder.AppendQuoted("--framework=" + settings.Framework);
            }

            if (settings.X86)
            {
                builder.Append("--x86");
            }

            if (settings.DisposeRunners)
            {
                builder.Append("--dispose-runners");
            }

            if (settings.ShadowCopy)
            {
                builder.Append("--shadowcopy");
            }

            if (settings.Agents.HasValue)
            {
                builder.Append("--agents=" + settings.Agents.Value);
            }

            // don't include the default value
            if (settings.Process != NUnit3ProcessOption.Multiple)
            {
                builder.Append("--process=" + settings.Process);
            }

            if (settings.AppDomainUsage != NUnit3AppDomainUsage.Default)
            {
                builder.Append("--domain=" + settings.AppDomainUsage);
            }

            if (settings.TraceLevel.HasValue)
            {
                builder.Append("--trace=" + settings.TraceLevel.Value.GetArgumentValue());
            }

            if (settings.Params != null && settings.Params.Count > 0)
            {
                foreach (var param in settings.Params)
                {
                    builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "--params={0}={1}", param.Key, param.Value));
                }
            }

            return(builder);
        }
示例#26
0
        /// <summary>
        /// Runs the tool using a custom tool path and the specified settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="processSettings">The process settings</param>
        /// <returns>The process that the tool is running under.</returns>
        protected IProcess RunProcess(
            TSettings settings,
            ProcessArgumentBuilder arguments,
            ProcessSettings processSettings)
        {
            if (arguments == null && (processSettings?.Arguments == null))
            {
                throw new ArgumentNullException(nameof(arguments));
            }

            // Should we customize the arguments?
            if (settings.ArgumentCustomization != null)
            {
                arguments = settings.ArgumentCustomization(arguments);
            }

            // Get the tool name.
            var toolName = GetToolName();

            // Get the tool path.
            var toolPath = GetToolPath(settings);

            if (toolPath == null || !_fileSystem.Exist(toolPath))
            {
                const string message = "{0}: Could not locate executable.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Get the working directory.
            var workingDirectory = GetWorkingDirectory(settings);

            if (workingDirectory == null)
            {
                const string message = "{0}: Could not resolve working directory.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Create the process start info.
            var info = processSettings ?? new ProcessSettings();

            if (info.Arguments == null)
            {
                info.Arguments = arguments;
            }
            if (info.WorkingDirectory == null)
            {
                info.WorkingDirectory = workingDirectory.MakeAbsolute(_environment).FullPath;
            }
            if (info.EnvironmentVariables == null)
            {
                info.EnvironmentVariables = GetEnvironmentVariables(settings);
            }

            // Run the process.
            var process = _processRunner.Start(toolPath, info);

            if (process == null)
            {
                const string message = "{0}: Process was not started.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }
            return(process);
        }
示例#27
0
        protected override string GenerateCommandLineCommands()
        {
            var args = new ProcessArgumentBuilder();
            TargetArchitecture architectures;
            bool msym;

            if (string.IsNullOrEmpty(Architectures) || !Enum.TryParse(Architectures, out architectures))
            {
                architectures = TargetArchitecture.Default;
            }

            if (architectures == TargetArchitecture.ARMv6)
            {
                Log.LogError("Target architecture ARMv6 is no longer supported in Xamarin.iOS. Please select a supported architecture.");
                return(null);
            }

            if (!string.IsNullOrEmpty(IntermediateOutputPath))
            {
                Directory.CreateDirectory(IntermediateOutputPath);

                args.AddQuoted("--cache=" + Path.GetFullPath(IntermediateOutputPath));
            }

            args.AddQuoted((SdkIsSimulator ? "--sim=" : "--dev=") + Path.GetFullPath(AppBundleDir));

            if (AppleSdkSettings.XcodeVersion.Major >= 5 && IPhoneSdks.MonoTouch.Version.CompareTo(new IPhoneSdkVersion(6, 3, 7)) < 0)
            {
                args.Add("--compiler=clang");
            }

            args.AddQuoted("--executable=" + ExecutableName);

            if (IsAppExtension)
            {
                args.Add("--extension");
            }

            if (Debug)
            {
                if (FastDev && !SdkIsSimulator)
                {
                    args.Add("--fastdev");
                }

                args.Add("--debug");
            }

            if (Profiling)
            {
                args.Add("--profiling");
            }

            if (LinkerDumpDependencies)
            {
                args.Add("--linkerdumpdependencies");
            }

            if (EnableSGenConc)
            {
                args.Add("--sgen-conc");
            }

            switch (LinkMode.ToLowerInvariant())
            {
            case "sdkonly": args.Add("--linksdkonly"); break;

            case "none":    args.Add("--nolink"); break;
            }

            if (!string.IsNullOrEmpty(I18n))
            {
                args.AddQuotedFormat("--i18n=" + I18n);
            }

            args.AddQuoted("--sdkroot=" + SdkRoot);

            args.AddQuoted("--sdk=" + SdkVersion);

            if (!minimumOSVersion.IsUseDefault)
            {
                args.AddQuoted("--targetver=" + minimumOSVersion.ToString());
            }

            if (UseFloat32 /* We want to compile 32-bit floating point code to use 32-bit floating point operations */)
            {
                args.Add("--aot-options=-O=float32");
            }
            else
            {
                args.Add("--aot-options=-O=-float32");
            }

            if (!EnableGenericValueTypeSharing)
            {
                args.Add("--gsharedvt=false");
            }

            if (LinkDescriptions != null)
            {
                foreach (var desc in LinkDescriptions)
                {
                    args.AddQuoted(string.Format("--xml={0}", desc.ItemSpec));
                }
            }

            if (EnableBitcode)
            {
                switch (Framework)
                {
                case PlatformFramework.WatchOS:
                    args.Add("--bitcode=full");
                    break;

                case PlatformFramework.TVOS:
                    args.Add("--bitcode=asmonly");
                    break;

                default:
                    throw new InvalidOperationException(string.Format("Bitcode is currently not supported on {0}.", Framework));
                }
            }

            if (!string.IsNullOrEmpty(HttpClientHandler))
            {
                args.Add(string.Format("--http-message-handler={0}", HttpClientHandler));
            }

            string thumb = UseThumb && UseLlvm ? "+thumb2" : "";
            string llvm  = UseLlvm ? "+llvm" : "";
            string abi   = "";

            if (SdkIsSimulator)
            {
                if (architectures.HasFlag(TargetArchitecture.i386))
                {
                    abi += (abi.Length > 0 ? "," : "") + "i386";
                }

                if (architectures.HasFlag(TargetArchitecture.x86_64))
                {
                    abi += (abi.Length > 0 ? "," : "") + "x86_64";
                }

                if (string.IsNullOrEmpty(abi))
                {
                    architectures = TargetArchitecture.i386;
                    abi           = "i386";
                }
            }
            else
            {
                if (architectures == TargetArchitecture.Default)
                {
                    architectures = TargetArchitecture.ARMv7;
                }

                if (architectures.HasFlag(TargetArchitecture.ARMv7))
                {
                    abi += (abi.Length > 0 ? "," : "") + "armv7" + llvm + thumb;
                }

                if (architectures.HasFlag(TargetArchitecture.ARMv7s))
                {
                    abi += (abi.Length > 0 ? "," : "") + "armv7s" + llvm + thumb;
                }

                if (architectures.HasFlag(TargetArchitecture.ARM64))
                {
                    // Note: ARM64 does not have thumb.
                    abi += (abi.Length > 0 ? "," : "") + "arm64" + llvm;
                }

                if (architectures.HasFlag(TargetArchitecture.ARMv7k))
                {
                    abi += (abi.Length > 0 ? "," : "") + "armv7k" + llvm;
                }

                if (string.IsNullOrEmpty(abi))
                {
                    abi = "armv7" + llvm + thumb;
                }
            }

            // Output the CompiledArchitectures
            CompiledArchitectures = architectures.ToString();

            args.Add("--abi=" + abi);

            // output symbols to preserve when stripping
            args.AddQuoted("--symbollist=" + Path.GetFullPath(SymbolsList));

            // don't have mtouch generate the dsyms...
            args.Add("--dsym=no");

            if (!string.IsNullOrEmpty(ArchiveSymbols) && bool.TryParse(ArchiveSymbols.Trim(), out msym))
            {
                args.Add("--msym=" + (msym ? "yes" : "no"));
            }

            var gcc = new GccOptions();

            if (!string.IsNullOrEmpty(ExtraArgs))
            {
                var    extraArgs = ProcessArgumentBuilder.Parse(ExtraArgs);
                var    target    = MainAssembly.ItemSpec;
                string projectDir;

                if (ProjectDir.StartsWith("~/", StringComparison.Ordinal))
                {
                    // Note: Since the Visual Studio plugin doesn't know the user's home directory on the Mac build host,
                    // it simply uses paths relative to "~/". Expand these paths to their full path equivalents.
                    var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

                    projectDir = Path.Combine(home, ProjectDir.Substring(2));
                }
                else
                {
                    projectDir = ProjectDir;
                }

                var customTags = new Dictionary <string, string> (StringComparer.OrdinalIgnoreCase)
                {
                    { "projectdir", projectDir },
                    // Apparently msbuild doesn't propagate the solution path, so we can't get it.
                    // { "solutiondir",  proj.ParentSolution != null ? proj.ParentSolution.BaseDirectory : proj.BaseDirectory },
                    { "appbundledir", AppBundleDir },
                    { "targetpath", Path.Combine(Path.GetDirectoryName(target), Path.GetFileName(target)) },
                    { "targetdir", Path.GetDirectoryName(target) },
                    { "targetname", Path.GetFileName(target) },
                    { "targetext", Path.GetExtension(target) },
                };

                for (int i = 0; i < extraArgs.Length; i++)
                {
                    var argument   = extraArgs[i];
                    int startIndex = 0;

                    while (argument.Length > startIndex && argument[startIndex] == '-')
                    {
                        startIndex++;
                    }

                    int endIndex = startIndex;
                    while (endIndex < argument.Length && argument[endIndex] != '=')
                    {
                        endIndex++;
                    }

                    int length = endIndex - startIndex;

                    if (length == 9 && string.CompareOrdinal(argument, startIndex, "gcc_flags", 0, 9) == 0)
                    {
                        // user-defined -gcc_flags argument
                        string flags = null;

                        if (endIndex < extraArgs[i].Length)
                        {
                            flags = Unquote(argument, endIndex + 1);
                        }
                        else if (i + 1 < extraArgs.Length)
                        {
                            flags = extraArgs[++i];
                        }

                        if (!string.IsNullOrEmpty(flags))
                        {
                            var gccArgs = ProcessArgumentBuilder.Parse(flags);

                            for (int j = 0; j < gccArgs.Length; j++)
                            {
                                gcc.Arguments.Add(StringParserService.Parse(gccArgs[j], customTags));
                            }
                        }
                    }
                    else
                    {
                        // other user-defined mtouch arguments
                        args.AddQuoted(StringParserService.Parse(argument, customTags));
                    }
                }
            }

            BuildNativeReferenceFlags(gcc);
            BuildEntitlementFlags(gcc);

            foreach (var framework in gcc.Frameworks)
            {
                args.AddQuoted("--framework=" + framework);
            }

            foreach (var framework in gcc.WeakFrameworks)
            {
                args.AddQuoted("--weak-framework=" + framework);
            }

            if (gcc.Cxx)
            {
                args.Add("--cxx");
            }

            if (gcc.Arguments.Length > 0)
            {
                args.Add("--gcc_flags");
                args.AddQuoted(gcc.Arguments.ToString());
            }

            foreach (var asm in References)
            {
                if (IsFrameworkItem(asm))
                {
                    args.AddQuoted("-r=" + ResolveFrameworkFile(asm.ItemSpec));
                }
                else
                {
                    args.AddQuoted("-r=" + Path.GetFullPath(asm.ItemSpec));
                }
            }

            foreach (var ext in AppExtensionReferences)
            {
                args.AddQuoted("--app-extension=" + Path.GetFullPath(ext.ItemSpec));
            }

            args.Add("--target-framework=" + TargetFrameworkIdentifier + "," + TargetFrameworkVersion);

            args.AddQuoted("--root-assembly=" + Path.GetFullPath(MainAssembly.ItemSpec));

            // We give the priority to the ExtraArgs to set the mtouch verbosity.
            if (string.IsNullOrEmpty(ExtraArgs) || (!string.IsNullOrEmpty(ExtraArgs) && !ExtraArgs.Contains("-q") && !ExtraArgs.Contains("-v")))
            {
                args.Add(GetVerbosityLevel(Verbosity));
            }

            if (!string.IsNullOrWhiteSpace(License))
            {
                args.Add(string.Format("--license={0}", License));
            }

            return(args.ToString());
        }
示例#28
0
        private ProcessArgumentBuilder GetArguments(
            DotCoverContext context,
            DotCoverAnalyseSettings settings,
            FilePath outputPath)
        {
            var builder = new ProcessArgumentBuilder();

            builder.Append("Analyse");

            // The target application to call.
            builder.AppendSwitch("/TargetExecutable", "=", context.FilePath.FullPath.Quote());

            // The arguments to the target application.
            var arguments = context.Settings?.Arguments?.Render();

            if (!string.IsNullOrWhiteSpace(arguments))
            {
                arguments = arguments.Replace("\"", "\\\"");
                builder.AppendSwitch("/TargetArguments", "=", arguments.Quote());
            }

            // Set the output file.
            outputPath = outputPath.MakeAbsolute(_environment);
            builder.AppendSwitch("/Output", "=", outputPath.FullPath.Quote());

            // Set the report type, don't include the default value
            if (settings.ReportType != DotCoverReportType.XML)
            {
                builder.AppendSwitch("/ReportType", "=", settings.ReportType.ToString());
            }

            // TargetWorkingDir
            if (settings.TargetWorkingDir != null)
            {
                builder.AppendSwitch("/TargetWorkingDir", "=", settings.TargetWorkingDir.MakeAbsolute(_environment).FullPath.Quote());
            }

            // Scope
            if (settings.Scope.Count > 0)
            {
                var scope = string.Join(";", settings.Scope);
                builder.AppendSwitch("/Scope", "=", scope.Quote());
            }

            // Filters
            if (settings.Filters.Count > 0)
            {
                var filters = string.Join(";", settings.Filters);
                builder.AppendSwitch("/Filters", "=", filters.Quote());
            }

            // Filters
            if (settings.AttributeFilters.Count > 0)
            {
                var attributeFilters = string.Join(";", settings.AttributeFilters);
                builder.AppendSwitch("/AttributeFilters", "=", attributeFilters.Quote());
            }

            // DisableDefaultFilters
            if (settings.DisableDefaultFilters)
            {
                builder.Append("/DisableDefaultFilters");
            }

            return(builder);
        }
		static BuildResult SignAppBundle (IProgressMonitor monitor, IPhoneProject proj, IPhoneProjectConfiguration conf,
		                           X509Certificate2 key, string resRules, string xcent)
		{
			monitor.BeginTask (GettextCatalog.GetString ("Signing application"), 0);
			
			var args = new ProcessArgumentBuilder ();
			args.Add ("-v", "-f", "-s");
			args.AddQuoted (Keychain.GetCertificateCommonName (key));
			args.AddQuotedFormat ("--resource-rules={0}", resRules);
			args.Add ("--entitlements");
			args.AddQuoted (xcent);
			args.AddQuoted (conf.AppDirectory);
			
			AddExtraArgs (args, conf.CodesignExtraArgs, proj, conf);
				
			int signResultCode;
			var psi = new ProcessStartInfo ("codesign") {
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardOutput = true,
				Arguments = args.ToString (),
			};
			
			monitor.Log.WriteLine ("codesign " + psi.Arguments);
			psi.EnvironmentVariables.Add ("CODESIGN_ALLOCATE",
				"/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate");
			string output;
			if ((signResultCode = MacBuildUtilities.ExecuteCommand (monitor, psi, out output)) != 0) {
				monitor.Log.WriteLine (output);
				return BuildError (string.Format ("Code signing failed with error code {0}. See output for details.", signResultCode));
			}
			monitor.EndTask ();
			
			return null;
		}
示例#30
0
        private ProcessArgumentBuilder GetArguments(FilePath codeCoverageReportFilePath, CoverallsNetReportType reportType, CoverallsNetSettings settings)
        {
            var builder = new ProcessArgumentBuilder();

            builder.Append(GetReportType(reportType));
            builder.Append("--input");
            builder.AppendQuoted(codeCoverageReportFilePath.MakeAbsolute(_environment).FullPath);

            if (settings.OutputFilePath != null)
            {
                builder.Append("--output");
                builder.AppendQuoted(settings.OutputFilePath.MakeAbsolute(_environment).FullPath);
            }

            if (settings.UseRelativePaths)
            {
                builder.Append("--useRelativePaths");
            }

            if (settings.BaseFilePath != null)
            {
                builder.Append("--basePath");
                builder.AppendQuoted(settings.BaseFilePath.MakeAbsolute(_environment).FullPath);
            }

            if (!string.IsNullOrWhiteSpace(settings.RepoToken))
            {
                builder.Append("--repoToken");
                builder.AppendQuotedSecret(settings.RepoToken);
            }

            if (!string.IsNullOrWhiteSpace(settings.RepoTokenVariable))
            {
                builder.Append("--repoTokenVariable");
                builder.AppendQuoted(settings.RepoTokenVariable);
            }

            if (!string.IsNullOrWhiteSpace(settings.CommitId))
            {
                builder.Append("--commitId");
                builder.AppendQuoted(settings.CommitId);
            }

            if (!string.IsNullOrWhiteSpace(settings.CommitBranch))
            {
                builder.Append("--commitBranch");
                builder.AppendQuoted(settings.CommitBranch);
            }

            if (!string.IsNullOrWhiteSpace(settings.CommitAuthor))
            {
                builder.Append("--commitAuthor");
                builder.AppendQuoted(settings.CommitAuthor);
            }

            if (!string.IsNullOrWhiteSpace(settings.CommitEmail))
            {
                builder.Append("--commitEmail");
                builder.AppendQuoted(settings.CommitEmail);
            }

            if (!string.IsNullOrWhiteSpace(settings.CommitMessage))
            {
                builder.Append("--commitMessage");
                builder.AppendQuoted(settings.CommitMessage);
            }

            if (!string.IsNullOrEmpty(settings.JobId))
            {
                builder.Append("--jobId");
                builder.Append(settings.JobId);
            }

            if (!string.IsNullOrWhiteSpace(settings.ServiceName))
            {
                builder.Append("--serviceName");
                builder.AppendQuoted(settings.ServiceName);
            }

            if (settings.TreatUploadErrorsAsWarnings)
            {
                builder.Append("--treatUploadErrorsAsWarnings");
            }

            return(builder);
        }
示例#31
0
		public StartAvdOperation StartAvd (AndroidVirtualDevice avd)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-partition-size", "512", "-avd");
			args.AddQuoted (avd.Name);
			args.Add ("-prop");
			args.AddQuoted ("monodroid.avdname=" + avd.Name);

			var error = new StringWriter ();
			var process = StartProcess (EmulatorExe, args.ToString (), null, error);
			return new StartAvdOperation (process, error);
		}
示例#32
0
        /// <summary>
        /// Adds MSBuild arguments
        /// </summary>
        /// <param name="builder">Argument builder.</param>
        /// <param name="settings">MSBuild settings to add.</param>
        /// <param name="environment">The environment.</param>
        /// <exception cref="InvalidOperationException">Throws if 10 or more file loggers specified.</exception>
        public static void AppendMSBuildSettings(this ProcessArgumentBuilder builder, DotNetCoreMSBuildSettings settings, ICakeEnvironment environment)
        {
            // Got any targets?
            if (settings.Targets.Any())
            {
                if (settings.Targets.All(string.IsNullOrWhiteSpace))
                {
                    throw new ArgumentException("Specify the name of the target", nameof(settings.Targets));
                }

                builder.AppendMSBuildSwitch("target", string.Join(";", settings.Targets));
            }

            // Got any properties?
            foreach (var property in settings.Properties)
            {
                if (property.Value == null || property.Value.All(string.IsNullOrWhiteSpace))
                {
                    throw new ArgumentException("A property must have at least one non-empty value", nameof(settings.Properties));
                }

                foreach (var value in property.Value)
                {
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        continue;
                    }

                    builder.AppendMSBuildSwitch("property", $"{property.Key}={value.EscapeMSBuildPropertySpecialCharacters()}");
                }
            }

            // Set the maximum number of processors?
            if (settings.MaxCpuCount.HasValue)
            {
                builder.AppendMSBuildSwitchWithOptionalValue("maxcpucount", settings.MaxCpuCount.Value, maxCpuCount => maxCpuCount > 0);
            }

            // use different version of msbuild?
            if (settings.ToolVersion.HasValue)
            {
                builder.AppendMSBuildSwitch("toolsversion", GetToolVersionValue(settings.ToolVersion.Value));
            }

            // configure console logger?
            if (!settings.DisableConsoleLogger && settings.ConsoleLoggerSettings != null)
            {
                var arguments = GetLoggerSettings(settings.ConsoleLoggerSettings);

                if (arguments.Any())
                {
                    builder.AppendMSBuildSwitch("consoleloggerparameters", arguments);
                }
            }

            // disable console logger?
            if (settings.DisableConsoleLogger)
            {
                builder.AppendMSBuildSwitch("noconsolelogger");
            }

            // Got any file loggers?
            if (settings.FileLoggers.Any())
            {
                if (settings.FileLoggers.Count >= 10)
                {
                    throw new InvalidOperationException("Too Many FileLoggers");
                }

                var arguments = settings
                                .FileLoggers
                                .Select((logger, index) => GetLoggerArgument(index, logger, environment))
                                .Where(arg => !string.IsNullOrEmpty(arg));

                foreach (var argument in arguments)
                {
                    builder.Append(argument);
                }
            }

            // Got any distributed loggers?
            foreach (var distributedLogger in settings.DistributedLoggers)
            {
                builder.AppendMSBuildSwitch("distributedlogger", $"{GetLoggerValue(distributedLogger.CentralLogger)}*{GetLoggerValue(distributedLogger.ForwardingLogger)}");
            }

            // use a file logger for each node?
            if (settings.DistributedFileLogger)
            {
                builder.AppendMSBuildSwitch("distributedFileLogger");
            }

            // Got any loggers?
            foreach (var logger in settings.Loggers)
            {
                builder.AppendMSBuildSwitch("logger", GetLoggerValue(logger));
            }

            var showWarningsAsError    = settings.TreatAllWarningsAs == MSBuildTreatAllWarningsAs.Error || settings.WarningCodesAsError.Any();
            var showWarningsAsMessages = settings.TreatAllWarningsAs == MSBuildTreatAllWarningsAs.Message || settings.WarningCodesAsMessage.Any();

            // Treat all or some warnings as errors?
            if (showWarningsAsError)
            {
                builder.AppendMSBuildSwitchWithOptionalValueIfNotEmpty("warnaserror", GetWarningCodes(settings.TreatAllWarningsAs == MSBuildTreatAllWarningsAs.Error, settings.WarningCodesAsError));
            }

            // Treat all or some warnings as messages?
            if (showWarningsAsMessages)
            {
                builder.AppendMSBuildSwitchWithOptionalValueIfNotEmpty("warnasmessage", GetWarningCodes(settings.TreatAllWarningsAs == MSBuildTreatAllWarningsAs.Message, settings.WarningCodesAsMessage));
            }

            // set project file extensions to ignore when searching for project file
            if (settings.IgnoreProjectExtensions.Any())
            {
                builder.AppendMSBuildSwitch("ignoreprojectextensions", string.Join(",", settings.IgnoreProjectExtensions));
            }

            // detailed summary?
            if (settings.DetailedSummary)
            {
                builder.AppendMSBuildSwitch("detailedsummary");
            }

            // Include response files?
            foreach (var responseFile in settings.ResponseFiles)
            {
                builder.AppendSwitchQuoted("@", string.Empty, responseFile.MakeAbsolute(environment).FullPath);
            }

            // exclude auto response files?
            if (settings.ExcludeAutoResponseFiles)
            {
                builder.AppendMSBuildSwitch("noautoresponse");
            }

            // don't output MSBuild logo?
            if (settings.NoLogo)
            {
                builder.AppendMSBuildSwitch("nologo");
            }
        }
示例#33
0
		public IProcessAsyncOperation SignPackage (AndroidSigningOptions options, string unsignedApk,
			string signedApk, TextWriter outputLog, TextWriter errorLog)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-keystore");
			args.AddQuoted (options.KeyStore);
			args.Add ("-storepass");
			args.AddQuoted (options.StorePass);
			args.Add ("-keypass");
			args.AddQuoted (options.KeyPass);
			args.Add ("-signedjar");
			args.AddQuoted (signedApk, unsignedApk, options.KeyAlias);
			
			return StartProcess (JarsignerExe, args.ToString (), outputLog, errorLog);
		}
示例#34
0
 private static void AppendMSBuildSwitch(this ProcessArgumentBuilder builder, string @switch)
 => builder.Append($"/{@switch}");
示例#35
0
        protected override string GenerateCommandLineCommands()
        {
            var args = new ProcessArgumentBuilder ();

            args.Add ("--compress");
            args.AddQuoted (InputScene);
            args.Add ("-o");
            args.AddQuoted (OutputScene);
            args.AddQuotedFormat ("--sdk-root={0}", SdkRoot);
            args.AddQuotedFormat ("--target-version-{0}={1}", OperatingSystem, SdkVersion);
            args.AddQuotedFormat ("--target-build-dir={0}", IntermediateOutputPath);

            return args.ToString ();
        }
示例#36
0
 private static void AppendMSBuildSwitchQuoted(this ProcessArgumentBuilder builder, string @switch, string value)
 => builder.AppendSwitchQuoted($"/{@switch}", ":", value);
 /// <summary>
 /// Returns the arguments of the concrete runner.
 /// </summary>
 /// <param name="builder">Argument builder instance.</param>
 /// <param name="configFile">The optional path to the docfx.json config file.</param>
 /// <param name="settings">The settings.</param>
 protected abstract void GetArguments(ProcessArgumentBuilder builder, FilePath configFile, T settings);
示例#38
0
        private ProcessArgumentBuilder GetArguments(FilePath path, DNURestoreSettings settings)
        {
            var builder = new ProcessArgumentBuilder();

            builder.Append("restore");

            // Specific project path?
            if (path != null)
            {
                builder.AppendQuoted(path.MakeAbsolute(_environment).FullPath);
            }

            // List of package sources
            if (settings.Sources != null && settings.Sources.Count > 0)
            {
                foreach (var source in settings.Sources)
                {
                    builder.Append("--source");
                    builder.AppendQuoted(source);
                }
            }

            // List of fallback package sources
            if (settings.FallbackSources != null && settings.FallbackSources.Count > 0)
            {
                foreach (var fallbacksource in settings.FallbackSources)
                {
                    builder.Append("--fallbacksource");
                    builder.AppendQuoted(fallbacksource);
                }
            }

            // Proxy
            if (settings.Proxy != null)
            {
                builder.Append("--proxy");
                builder.AppendQuoted(settings.Proxy);
            }

            // No Cache?
            if (settings.NoCache)
            {
                builder.Append("--no-cache");
            }

            // Packages
            if (settings.Packages != null)
            {
                builder.Append("--packages");
                builder.AppendQuoted(settings.Packages.MakeAbsolute(_environment).FullPath);
            }

            // Ignore failed sources?
            if (settings.IgnoreFailedSources)
            {
                builder.Append("--ignore-failed-sources");
            }

            // Quiet?
            if (settings.Quiet)
            {
                builder.Append("--quiet");
            }

            // Parallel?
            if (settings.Parallel)
            {
                builder.Append("--parallel");
            }

            // Locked?
            if (settings.Locked.HasValue)
            {
                switch (settings.Locked)
                {
                case DNULocked.Lock:
                    builder.Append("--lock");
                    break;

                case DNULocked.Unlock:
                    builder.Append("--unlock");
                    break;
                }
            }

            // List of runtime identifiers
            if (settings.Runtimes != null && settings.Runtimes.Count > 0)
            {
                foreach (var runtime in settings.Runtimes)
                {
                    builder.Append("--runtime");
                    builder.AppendQuoted(runtime);
                }
            }

            return(builder);
        }
        protected int Compile(ITaskItem[] items, ITaskItem output, ITaskItem manifest)
        {
            var environment = new Dictionary <string, string> ();
            var args        = new ProcessArgumentBuilder();

            if (!string.IsNullOrEmpty(SdkBinPath))
            {
                environment.Add("PATH", SdkBinPath);
            }

            if (!string.IsNullOrEmpty(SdkUsrPath))
            {
                environment.Add("XCODE_DEVELOPER_USR_PATH", SdkUsrPath);
            }

            args.Add("--errors", "--warnings", "--notices");
            args.Add("--output-format", "xml1");

            AppendCommandLineArguments(environment, args, items);

            if (Link)
            {
                args.Add("--link");
            }
            else if (UseCompilationDirectory)
            {
                args.Add("--compilation-directory");
            }
            else
            {
                args.Add("--compile");
            }

            args.AddQuoted(output.GetMetadata("FullPath"));

            foreach (var item in items)
            {
                args.AddQuoted(item.GetMetadata("FullPath"));
            }

            var startInfo = GetProcessStartInfo(environment, GetFullPathToTool(), args.ToString());

            try {
                Log.LogMessage(MessageImportance.Normal, "Tool {0} execution started with arguments: {1}", startInfo.FileName, startInfo.Arguments);

                using (var stdout = File.CreateText(manifest.ItemSpec)) {
                    var errors = new StringBuilder();
                    int exitCode;

                    using (var stderr = new StringWriter(errors)) {
                        var process = ProcessUtils.StartProcess(startInfo, stdout, stderr);

                        process.Wait();

                        exitCode = process.Result;
                    }

                    Log.LogMessage(MessageImportance.Low, "Tool {0} execution finished (exit code = {1}).", startInfo.FileName, exitCode);

                    if (exitCode != 0)
                    {
                        Log.LogError(null, null, null, items[0].ItemSpec, 0, 0, 0, 0, "{0}", errors);
                    }

                    return(exitCode);
                }
            } catch (Exception ex) {
                Log.LogError("Error executing tool '{0}': {1}", startInfo.FileName, ex.Message);
                File.Delete(manifest.ItemSpec);
                return(-1);
            }
        }
示例#40
0
 /// <summary>
 /// Quotes and appends the specified secret text to the argument builder.
 /// </summary>
 /// <param name="builder">The builder.</param>
 /// <param name="switch">The switch preceding the text.</param>
 /// <param name="text">The secret text to be quoted and appended.</param>
 /// <returns>The same <see cref="ProcessArgumentBuilder"/> instance so that multiple calls can be chained.</returns>
 public static ProcessArgumentBuilder AppendSwitchQuotedSecret(this ProcessArgumentBuilder builder, string @switch, string text)
 {
     return(AppendSwitchQuotedSecret(builder, @switch, " ", text));
 }
示例#41
0
 /// <summary>
 /// Runs the tool using the specified settings.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="arguments">The arguments.</param>
 protected void Run(TSettings settings, ProcessArgumentBuilder arguments)
 {
     Run(settings, arguments, null, null);
 }
示例#42
0
 /// <summary>
 /// Quotes and appends the specified secret text to the argument builder.
 /// </summary>
 /// <param name="builder">The builder.</param>
 /// <param name="switch">The switch preceding the text.</param>
 /// <param name="argument">The secret argument to be appended.</param>
 /// <returns>The same <see cref="ProcessArgumentBuilder"/> instance so that multiple calls can be chained.</returns>
 public static ProcessArgumentBuilder AppendQuotedSecret(this ProcessArgumentBuilder builder, string @switch, IProcessArgument argument)
 {
     return(AppendQuotedSecret(builder, @switch, " ", argument));
 }
示例#43
0
        void BuildNativeReferenceFlags(GccOptions gcc)
        {
            if (NativeReferences == null)
            {
                return;
            }

            foreach (var item in NativeReferences)
            {
                var value = item.GetMetadata("Kind");
                NativeReferenceKind kind;
                bool boolean;

                if (string.IsNullOrEmpty(value) || !Enum.TryParse(value, out kind))
                {
                    Log.LogWarning("Unknown native reference type for '{0}'.", item.ItemSpec);
                    continue;
                }

                if (kind == NativeReferenceKind.Static)
                {
                    var libName = Path.GetFileName(item.ItemSpec);

                    if (libName.EndsWith(".a", StringComparison.Ordinal))
                    {
                        libName = libName.Substring(0, libName.Length - 2);
                    }

                    if (libName.StartsWith("lib", StringComparison.Ordinal))
                    {
                        libName = libName.Substring(3);
                    }

                    if (!string.IsNullOrEmpty(Path.GetDirectoryName(item.ItemSpec)))
                    {
                        gcc.Arguments.AddQuoted("-L" + Path.GetDirectoryName(item.ItemSpec));
                    }

                    gcc.Arguments.AddQuoted("-l" + libName);

                    value = item.GetMetadata("ForceLoad");

                    if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out boolean) && boolean)
                    {
                        gcc.Arguments.Add("-force_load");
                        gcc.Arguments.AddQuoted(item.ItemSpec);
                    }

                    value = item.GetMetadata("IsCxx");

                    if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out boolean) && boolean)
                    {
                        gcc.Cxx = true;
                    }
                }
                else if (kind == NativeReferenceKind.Framework)
                {
                    gcc.Frameworks.Add(item.ItemSpec);
                }
                else
                {
                    Log.LogWarning("Dynamic native references are not supported: '{0}'", item.ItemSpec);
                    continue;
                }

                value = item.GetMetadata("NeedsGccExceptionHandling");
                if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out boolean) && boolean)
                {
                    if (!gcc.Arguments.Contains("-lgcc_eh"))
                    {
                        gcc.Arguments.Add("-lgcc_eh");
                    }
                }

                value = item.GetMetadata("WeakFrameworks");
                if (!string.IsNullOrEmpty(value))
                {
                    foreach (var framework in value.Split(' ', '\t'))
                    {
                        gcc.WeakFrameworks.Add(framework);
                    }
                }

                value = item.GetMetadata("Frameworks");
                if (!string.IsNullOrEmpty(value))
                {
                    foreach (var framework in value.Split(' ', '\t'))
                    {
                        gcc.Frameworks.Add(framework);
                    }
                }

                // Note: these get merged into gccArgs by our caller
                value = item.GetMetadata("LinkerFlags");
                if (!string.IsNullOrEmpty(value))
                {
                    var linkerFlags = ProcessArgumentBuilder.Parse(value);

                    foreach (var flag in linkerFlags)
                    {
                        gcc.Arguments.AddQuoted(flag);
                    }
                }
            }
        }
示例#44
0
        /// <summary>
        /// Formats, quotes and appends the specified text to the argument builder.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="format">A composite format string to be quoted and appended.</param>
        /// <param name="args">An object array that contains zero or more objects to format.</param>
        /// <returns>The same <see cref="ProcessArgumentBuilder"/> instance so that multiple calls can be chained.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="format" /> or <paramref name="args" /> is null. </exception>
        /// <exception cref="FormatException"><paramref name="format" /> is invalid.-or- The index of a format item is less than zero, or greater than or equal to the length of the <paramref name="args" /> array. </exception>
        public static ProcessArgumentBuilder AppendQuoted(this ProcessArgumentBuilder builder, string format, params object[] args)
        {
            var text = string.Format(CultureInfo.InvariantCulture, format, args);

            return(AppendQuoted(builder, text));
        }
示例#45
0
 public GccOptions()
 {
     Arguments      = new ProcessArgumentBuilder();
     WeakFrameworks = new HashSet <string> ();
     Frameworks     = new HashSet <string> ();
 }
        private static ProcessArgumentBuilder GetArguments(
            PackageReference definition,
            DotNetToolOperation operation,
            ICakeLog log,
            DirectoryPath toolDirectoryPath)
        {
            var arguments = new ProcessArgumentBuilder();

            arguments.Append("tool");
            arguments.Append(Enum.GetName(typeof(DotNetToolOperation), operation).ToLowerInvariant());
            arguments.AppendQuoted(definition.Package);

            if (definition.Parameters.ContainsKey("global"))
            {
                arguments.Append("--global");
            }
            else
            {
                arguments.Append("--tool-path");
                arguments.AppendQuoted(toolDirectoryPath.FullPath);
            }

            if (operation != DotNetToolOperation.Uninstall)
            {
                if (definition.Address != null)
                {
                    arguments.Append("--add-source");
                    arguments.AppendQuoted(definition.Address.AbsoluteUri);
                }

                // Version
                if (definition.Parameters.ContainsKey("version"))
                {
                    arguments.Append("--version");
                    arguments.Append(definition.Parameters["version"].First());
                }

                // Config File
                if (definition.Parameters.ContainsKey("configfile"))
                {
                    arguments.Append("--configfile");
                    arguments.AppendQuoted(definition.Parameters["configfile"].First());
                }

                // Whether to ignore failed sources
                if (definition.Parameters.ContainsKey("ignore-failed-sources"))
                {
                    arguments.Append("--ignore-failed-sources");
                }

                // Framework
                if (definition.Parameters.ContainsKey("framework"))
                {
                    arguments.Append("--framework");
                    arguments.Append(definition.Parameters["framework"].First());
                }

                switch (log.Verbosity)
                {
                case Verbosity.Quiet:
                    arguments.Append("--verbosity");
                    arguments.Append("quiet");
                    break;

                case Verbosity.Minimal:
                    arguments.Append("--verbosity");
                    arguments.Append("minimal");
                    break;

                case Verbosity.Normal:
                    arguments.Append("--verbosity");
                    arguments.Append("normal");
                    break;

                case Verbosity.Verbose:
                    arguments.Append("--verbosity");
                    arguments.Append("detailed");
                    break;

                case Verbosity.Diagnostic:
                    arguments.Append("--verbosity");
                    arguments.Append("diagnostic");
                    break;

                default:
                    arguments.Append("--verbosity");
                    arguments.Append("normal");
                    break;
                }
            }

            return(arguments);
        }
		static internal void AppendExtrasMtouchArgs (ProcessArgumentBuilder args, IPhoneSdkVersion sdkVersion, 
			IPhoneProject proj, IPhoneProjectConfiguration conf)
		{
			if (conf.MtouchDebug)
				args.Add ("-debug");
			
			switch (conf.MtouchLink) {
			case MtouchLinkMode.SdkOnly:
				args.Add ("-linksdkonly");
				break;
			case MtouchLinkMode.None:
				args.Add ("-nolink");
				break;
			case MtouchLinkMode.Full:
			default:
				break;
			}
			
			if (!string.IsNullOrEmpty (conf.MtouchI18n)) {
				args.AddQuotedFormat ("-i18n={0}", conf.MtouchI18n);
			}
			
			if (!sdkVersion.Equals (IPhoneSdkVersion.V3_0))
				args.AddQuotedFormat ("-sdk={0}", sdkVersion);
			
			if (conf.MtouchMinimumOSVersion != "3.0")
				args.AddQuotedFormat ("-targetver={0}", conf.MtouchMinimumOSVersion);
			
			
			AddExtraArgs (args, conf.MtouchExtraArgs, proj, conf);
		}
示例#48
0
            private ProcessArgumentBuilder GetInstallArguments(TopshelfSettings settings)
            {
                ProcessArgumentBuilder builder = new ProcessArgumentBuilder();

                if ((settings != null) && (settings.Arguments != null))
                {
                    builder = settings.Arguments;
                }

                builder.Append(new TextArgument("install"));



                if (settings != null)
                {
                    if (!string.IsNullOrWhiteSpace(settings.Username))
                    {
                        builder.Append(new TextArgument("-username"));
                        builder.Append(new QuotedArgument(new TextArgument(settings.Username)));
                    }

                    if (!string.IsNullOrWhiteSpace(settings.Password))
                    {
                        builder.Append(new TextArgument("-password"));
                        builder.Append(new QuotedArgument(new TextArgument(settings.Password)));
                    }

                    if (!string.IsNullOrWhiteSpace(settings.Instance))
                    {
                        builder.Append(new TextArgument("-instance"));
                        builder.Append(new QuotedArgument(new TextArgument(settings.Instance)));
                    }

                    builder.Append(settings.Autostart
                            ? new TextArgument("--autostart")
                            : new TextArgument("--manual"));

                    if (settings.Disabled)
                        builder.Append(new TextArgument("--disabled"));

                    if (settings.Delayed)
                        builder.Append(new TextArgument("--delayed"));

                    if (settings.LocalSystem)
                        builder.Append(new TextArgument("--localsystem"));

                    if (settings.LocalService)
                        builder.Append(new TextArgument("--localservice"));

                    if (settings.NetworkService)
                        builder.Append(new TextArgument("--networkservice"));

                    if (!string.IsNullOrWhiteSpace(settings.ServiceName))
                    {
                        builder.Append(new TextArgument("--servicename"));
                        builder.Append(new QuotedArgument(new TextArgument(settings.Description)));
                    }

                    if (!string.IsNullOrWhiteSpace(settings.Description))
                    {
                        builder.Append(new TextArgument("--description"));
                        builder.Append(new QuotedArgument(new TextArgument(settings.Description)));
                    }

                    if (!string.IsNullOrWhiteSpace(settings.DisplayName))
                    {
                        builder.Append(new TextArgument("--displayname"));
                        builder.Append(new QuotedArgument(new TextArgument(settings.DisplayName)));
                    }
                }

                return builder;
            }
        public void Test_That_Argument_Starting_With_Sigil_Is_Quoted(Type escapeHandlerType, string sigil)
        {
            // Arrange
            var escapeHandler = Activator.CreateInstance(escapeHandlerType, new object[] { sigil }) as IArgumentEscapeHandler;
            var builder = new ProcessArgumentBuilder(escapeHandler);
            builder.AddArgument($"{sigil}test");

            // Act
            var result = builder.Build();

            // Assert
            Assert.Equal($"\"{sigil}test\"", result);
        }
示例#50
0
 public static void DotNetCoreExecute(this ICakeContext context, FilePath assemblyPath, ProcessArgumentBuilder arguments)
 {
     context.DotNetCoreExecute(assemblyPath, arguments, null);
 }
示例#51
0
		//string dname = "CN=Android Debug,O=Android,C=US";
		public IProcessAsyncOperation Genkeypair (AndroidSigningOptions options, string dname,
			TextWriter outputLog, TextWriter errorLog)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-genkeypair");
			args.Add ("-alias");
			args.AddQuoted (options.KeyAlias);
			args.Add ("-dname");
			args.AddQuoted (dname);
			args.Add ("-storepass");
			args.AddQuoted (options.StorePass);
			args.Add ("-keypass");
			args.AddQuoted (options.KeyPass);
			args.Add ("-keystore");
			args.AddQuoted (options.KeyStore);
			
			return StartProcess (KeytoolExe, args.ToString (), outputLog, errorLog);
		}
示例#52
0
        public static void DotNetCoreExecute(this ICakeContext context, FilePath assemblyPath, ProcessArgumentBuilder arguments, DotNetCoreExecuteSettings settings)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (assemblyPath == null)
            {
                throw new ArgumentNullException(nameof(assemblyPath));
            }

            if (settings == null)
            {
                settings = new DotNetCoreExecuteSettings();
            }

            var executor = new DotNetCoreExecutor(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);

            executor.Execute(assemblyPath, arguments, settings);
        }
示例#53
0
		public IProcessAsyncOperation PullFile (AndroidDevice device, string source, string destination,
			TextWriter outputLog, TextWriter errorLog)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-s", device.ID, "pull");
			args.AddQuoted (source, destination);
			
			return StartProcess (AdbExe, args.ToString (), outputLog, errorLog);
		}
示例#54
0
 private void AppendUsernameAndPassword(ProcessArgumentBuilder builder)
 {
     builder.AppendIf(!StringUtil.IsBlank(Username), string.Format("-Y{0},{1}", Username, Password));
 }
示例#55
0
		public IProcessAsyncOperation Uninstall (AndroidDevice device, string package, TextWriter outputLog, TextWriter errorLog)
		{
			var args = new ProcessArgumentBuilder ();
			args.Add ("-s", device.ID, "uninstall");
			args.AddQuoted (package);
			
			return StartProcess (AdbExe, args.ToString (), outputLog, errorLog);
		}
示例#56
0
        private ProcessArgumentBuilder GetArguments(string apiKey, string source, ChocolateyApiKeySettings settings)
        {
            var builder = new ProcessArgumentBuilder();

            builder.Append("apikey");

            builder.Append("-s");
            builder.AppendQuoted(source);

            builder.Append("-k");
            builder.AppendQuoted(apiKey);

            // Debug
            if (settings.Debug)
            {
                builder.Append("-d");
            }

            // Verbose
            if (settings.Verbose)
            {
                builder.Append("-v");
            }

            // Always say yes, so as to not show interactive prompt
            builder.Append("-y");

            // Force
            if (settings.Force)
            {
                builder.Append("-f");
            }

            // Noop
            if (settings.Noop)
            {
                builder.Append("--noop");
            }

            // Limit Output
            if (settings.LimitOutput)
            {
                builder.Append("-r");
            }

            // Execution Timeout
            if (settings.ExecutionTimeout != 0)
            {
                builder.Append("--execution-timeout");
                builder.AppendQuoted(settings.ExecutionTimeout.ToString(CultureInfo.InvariantCulture));
            }

            // Cache Location
            if (!string.IsNullOrWhiteSpace(settings.CacheLocation))
            {
                builder.Append("-c");
                builder.AppendQuoted(settings.CacheLocation);
            }

            // Allow Unoffical
            if (settings.AllowUnoffical)
            {
                builder.Append("--allowunofficial");
            }

            return(builder);
        }
        public void Test_ToStringSafe(string argumentValueSeparator, string argumentValue, bool isSensitive, string expected, Type escapeHandlerType, string sigil)
        {
            // Arrange
            var escapeHandler = Activator.CreateInstance(escapeHandlerType, new object[] { sigil }) as IArgumentEscapeHandler;
            var builder = new ProcessArgumentBuilder(escapeHandler, argumentValueSeparator);
            builder.AddNamedArgument("-p", argumentValue, isSensitiveArgument: isSensitive);

            // Act
            var result = builder.BuildSafe(SAFE_PLACEHOLDER);

            // Assert
            Assert.Equal(expected, result);
        }
示例#58
0
        private ProcessArgumentBuilder GetArguments(IEnumerable <FilePath> assemblyPaths, NUnitSettings settings)
        {
            var builder = new ProcessArgumentBuilder();

            // Add the assemblies to build.
            foreach (var assemblyPath in assemblyPaths)
            {
                builder.AppendQuoted(assemblyPath.MakeAbsolute(_environment).FullPath);
            }

            if (settings.Framework != null)
            {
                builder.AppendQuoted("-framework:" + settings.Framework);
            }

            if (settings.Include != null)
            {
                builder.AppendQuoted("-include:" + settings.Include);
            }

            if (settings.Exclude != null)
            {
                builder.AppendQuoted("-exclude:" + settings.Exclude);
            }

            if (settings.Timeout.HasValue)
            {
                builder.Append("-timeout:" + settings.Timeout.Value);
            }

            // No shadow copy?
            if (!settings.ShadowCopy)
            {
                builder.Append("-noshadow");
            }

            if (settings.NoLogo)
            {
                builder.Append("-nologo");
            }

            if (settings.NoThread)
            {
                builder.Append("-nothread");
            }

            if (settings.StopOnError)
            {
                builder.Append("-stoponerror");
            }

            if (settings.Trace != null)
            {
                builder.Append("-trace:" + settings.Trace);
            }

            if (settings.Labels)
            {
                builder.Append("-labels");
            }

            if (settings.OutputFile != null)
            {
                builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "-output:{0}", settings.OutputFile.MakeAbsolute(_environment).FullPath));
            }

            if (settings.ErrorOutputFile != null)
            {
                builder.AppendQuoted(string.Format(CultureInfo.InvariantCulture, "-err:{0}", settings.ErrorOutputFile.MakeAbsolute(_environment).FullPath));
            }

            if (settings.ResultsFile != null && settings.NoResults)
            {
                throw new ArgumentException(
                          GetToolName() + ": You can't specify both a results file and set NoResults to true.");
            }

            if (settings.ResultsFile != null)
            {
                builder.AppendQuoted(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "-result:{0}", settings.ResultsFile.MakeAbsolute(_environment).FullPath));
            }
            else if (settings.NoResults)
            {
                builder.AppendQuoted("-noresult");
            }

            // don't include the default value
            if (settings.Process != NUnitProcessOption.Single)
            {
                builder.AppendQuoted("-process:" + settings.Process);
            }

            if (settings.UseSingleThreadedApartment)
            {
                builder.AppendQuoted("-apartment:STA");
            }

            if (settings.AppDomainUsage != NUnitAppDomainUsage.Default)
            {
                builder.AppendQuoted("-domain:" + settings.AppDomainUsage);
            }

            return(builder);
        }
示例#59
0
 public static void DotNetCoreRun(this ICakeContext context, string project, ProcessArgumentBuilder arguments)
 {
     context.DotNetCoreRun(project, arguments, null);
 }
		protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration)
		{
			IPhoneProject proj = item as IPhoneProject;
			if (proj == null || proj.CompileTarget != CompileTarget.Exe)
				return base.Build (monitor, item, configuration);
			
			//prebuild
			var conf = (IPhoneProjectConfiguration) proj.GetConfiguration (configuration);
			bool isDevice = conf.Platform == IPhoneProject.PLAT_IPHONE;
			
			if (IPhoneFramework.SimOnly && isDevice) {
				//if in the GUI, show a dialog too
				if (MonoDevelop.Ide.IdeApp.IsInitialized)
					Gtk.Application.Invoke (delegate { IPhoneFramework.ShowSimOnlyDialog (); } );
				return IPhoneFramework.GetSimOnlyError ();
			}
			
			var result = new BuildResult ();
			
			var sdkVersion = conf.MtouchSdkVersion.ResolveIfDefault ();
			
			if (!IPhoneFramework.SdkIsInstalled (sdkVersion)) {
				sdkVersion = IPhoneFramework.GetClosestInstalledSdk (sdkVersion);
				
				if (sdkVersion.IsUseDefault || !IPhoneFramework.SdkIsInstalled (sdkVersion)) {
					if (conf.MtouchSdkVersion.IsUseDefault)
						result.AddError (
							string.Format ("The Apple iPhone SDK is not installed."));
					else
						result.AddError (
							string.Format ("Apple iPhone SDK version '{0}' is not installed, and no newer version was found.",
							conf.MtouchSdkVersion));
					return result;
				}
					
				result.AddWarning (
					string.Format ("Apple iPhone SDK version '{0}' is not installed. Using newer version '{1}' instead'.",
					conf.MtouchSdkVersion, sdkVersion));
			}
			
			IPhoneAppIdentity identity = null;
			if (isDevice) {
				monitor.BeginTask (GettextCatalog.GetString ("Detecting signing identity..."), 0);
				if ((result = GetIdentity (monitor, proj, conf, out identity).Append (result)).ErrorCount > 0)
					return result;
				monitor.Log.WriteLine ("Provisioning profile: \"{0}\" ({1})", identity.Profile.Name, identity.Profile.Uuid);
				monitor.Log.WriteLine ("Signing Identity: \"{0}\"", Keychain.GetCertificateCommonName (identity.SigningKey));
				monitor.Log.WriteLine ("App ID: \"{0}\"", identity.AppID);
				monitor.EndTask ();
			} else {
				identity = new IPhoneAppIdentity () {
					BundleID = !string.IsNullOrEmpty (proj.BundleIdentifier)?
						proj.BundleIdentifier : GetDefaultBundleID (proj, null)
				};
			}
			
			result = base.Build (monitor, item, configuration).Append (result);
			if (result.ErrorCount > 0)
				return result;
			
			if (!Directory.Exists (conf.AppDirectory))
				Directory.CreateDirectory (conf.AppDirectory);
			
			var assemblyRefs = proj.GetReferencedAssemblies (configuration).Distinct ().ToList ();
			
			FilePath mtouchOutput = conf.NativeExe;
			if (new FilePair (conf.CompiledOutputName, mtouchOutput).NeedsBuilding ()) {
				BuildResult error;
				var mtouch = GetMTouch (proj, monitor, out error);
				if (error != null)
					return error.Append (result);
				
				var args = new ProcessArgumentBuilder ();
				//FIXME: make verbosity configurable?
				args.Add ("-v");
				
				args.Add ("--nomanifest", "--nosign");
					
				//FIXME: should we error out if the platform is invalid?
				if (conf.Platform == IPhoneProject.PLAT_IPHONE) {
					args.Add ("-dev");
					args.AddQuoted (conf.AppDirectory);
				} else {
					args.Add ("-sim");
					args.AddQuoted (conf.AppDirectory);
				}
				
				foreach (string asm in assemblyRefs)
					args.AddQuotedFormat ("-r={0}", asm);
				
				AppendExtrasMtouchArgs (args, sdkVersion, proj, conf);
				
				args.AddQuoted (conf.CompiledOutputName);
				
				mtouch.WorkingDirectory = conf.OutputDirectory;
				mtouch.Arguments = args.ToString ();
				
				monitor.BeginTask (GettextCatalog.GetString ("Compiling to native code"), 0);
				
				string output;
				int code;
				monitor.Log.WriteLine ("{0} {1}", mtouch.FileName, mtouch.Arguments);
				if ((code = MacBuildUtilities.ExecuteCommand (monitor, mtouch, out output)) != 0) {
					if (String.IsNullOrEmpty (output)) {
						result.AddError (null, 0, 0, code.ToString (), "mtouch failed with no output");
					} else {
						result.AddError (null, 0, 0, code.ToString (), "mtouch failed with the following message:\n" + output);
					}
					return result;
				}
				
				monitor.EndTask ();
			}
			
			if (result.Append (UnpackContent (monitor, conf, assemblyRefs)).ErrorCount > 0)
				return result;
			
			//create the info.plist, merging in the template if it exists
			var plistOut = conf.AppDirectory.Combine ("Info.plist");
			ProjectFile appInfoIn = proj.Files.GetFile (proj.BaseDirectory.Combine ("Info.plist"));
			if (new FilePair (proj.FileName, plistOut).NeedsBuilding () ||
			    	(appInfoIn != null && new FilePair (appInfoIn.FilePath, plistOut).NeedsBuilding ())) {
				try {
					monitor.BeginTask (GettextCatalog.GetString ("Updating application manifest"), 0);
					if (result.Append (UpdateInfoPlist (monitor, sdkVersion, proj, conf, identity, appInfoIn, plistOut)).ErrorCount > 0)
						return result;
				} finally {
					monitor.EndTask ();
				}
			}
			
			//create the Setting.bundle plist for debug settings, merging in the template if it exists
			try {
				monitor.BeginTask (GettextCatalog.GetString ("Updating debug settings manifest"), 0);
				var sbRootRel = Path.Combine ("Settings.bundle", "Root.plist");
				var sbRootOut = conf.AppDirectory.Combine (sbRootRel);
				var sbRootIn  = proj.Files.GetFile (proj.BaseDirectory.Combine (sbRootRel));
				if (result.Append (UpdateDebugSettingsPlist (monitor, conf, sbRootIn, sbRootOut)).ErrorCount > 0)
					return result;
			} finally {
				monitor.EndTask ();
			}
			
			try {
				if (result.Append (ProcessPackaging (monitor, sdkVersion, proj, conf, identity)).ErrorCount > 0)
					return result;
			} finally {
				//if packaging failed, make sure that it's marked as needing building
				if (result.ErrorCount > 0 && File.Exists (conf.AppDirectory.Combine ("PkgInfo")))
					File.Delete (conf.AppDirectory.Combine ("PkgInfo"));	
			}	
			
			//TODO: create/update the xcode project
			return result;
		}