/// <summary> /// Validate this instance. /// </summary> public static bool Validate() { bool validationStatus = true; Log(string.Format("Searching Validators for Target: {0}, Symbols: {1}", BuildTargets.ToString().ToUpper(), PlayerSettings.GetScriptingDefineSymbolsForGroup(UnityBuildTargetGroup))); // Loop through all validate methods and print results= if (null != ValidationItems) { Log(string.Format("Found {0} Validations", ValidationItems.Count)); foreach (var item in ValidationItems) { if (item.CanValidate) { validationStatus &= item.Validate(ValidationDelegateParameters); Log(string.Format("Executing `{0}` ... {1}", item.Name, validationStatus.ToString().ToUpper())); if (HALT_ON_FAILURE && false == validationStatus) { Log("STOPPING VALIDATIONS, PLEASE CHECK VALUES !!!"); return(validationStatus); } } } } if (true == validationStatus) { Log("All Validations PASSED"); } return(validationStatus); }
private static void TargetFetchBuildVersion(ITaskContext context) { Version version = BuildTargets.FetchBuildVersionFromFile(context); context.Properties.Set(BuildProps.BuildVersion, version); context.WriteInfo("The build version will be {0}", version); }
public override void Help() { WriteUsage("[target] [options] [project-path]"); WriteHead("Examples", 26); WriteRow("uno build android", "Build Android app, in current directory"); WriteRow("uno build ios --run", "Build & run iOS app, in current directory"); WriteRow("uno build native --debug", "Build & open Visual C++ or Xcode, if available"); WriteHead("Common options", 26); WriteRow("-c, --configuration=STRING", "Build configuration [Debug|Release]"); WriteRow("-t, --target=STRING", "Build target (see: Available build targets)"); WriteRow("-d, --debug", "Open IDE for debugging after successful build"); WriteRow("-r, --run", "Start the program after successful build"); WriteRow("-z, --clean", "Clean the output directory before building"); WriteRow("-v, -vv, -vvv", "Increment verbosity level"); WriteHead("Additional options", 26); WriteRow("-n, --native-args=STRING", "Arguments to native build command"); WriteRow("-a, --run-args=STRING", "Arguments to run command"); WriteRow("-m, --main=STRING", "Override application entrypoint"); WriteRow("-s, --set:NAME=STRING", "Override build system property"); WriteRow("-o, --out-dir=PATH", "Override output directory"); WriteRow("-b, --build-only", "Build only; don't run or open debugger"); WriteRow("-g, --gen-only", "Generate only; don't compile generated code."); WriteRow("-f, --force", "Build even if output is up-to-date"); WriteRow("-l, --libs", "Rebuild package library if necessary"); WriteRow("-p, --print-internals", "Print a list of build system properties"); WriteRow("-N, --no-native", "Disable native build step (faster)"); WriteRow("-P, --no-parallel", "Disable multi-threading (slower)"); WriteRow("-S, --no-strip", "Disable removal of unused code (slower)"); WriteHead("Compiler options", 26); WriteRow("-D, --define=STRING", "Add define, to enable a feature"); WriteRow("-U, --undefine=STRING", "Remove define, to disable a feature"); WriteRow("-E, --max-errors=NUMBER", "Set max error count (0 = disable)"); WriteRow("-W<0..3>", "Set warning level (0 = disable)"); WriteHead("C++ options", 26); WriteRow("-DREFLECTION", "Enable run-time type reflection"); WriteRow("-DSTACKTRACE", "Enable stack traces on Exception"); WriteRow("-DDEBUG_UNSAFE", "Enable C++ asserts in unsafe code"); WriteRow("-DDEBUG_NATIVE", "Disable C++ optimizations when debugging"); if (Log.EnableExperimental) { WriteRow("-DDEBUG_ARC<0..4>", "Log events from ARC/memory management"); WriteRow("-DDEBUG_DUMPS", "Dump GraphViz files to help identify cycles in memory"); WriteHead("GLSL options", 26); WriteRow("-DDUMP_SHADERS", "Dump shaders to build directory for inspection"); } WriteHead("Available build targets", 19); foreach (var c in BuildTargets.Enumerate(Log.EnableExperimental)) { WriteRow("* " + c.Identifier, c.Description); } }
public static CommandLineOptions From(string[] args) { var help = false; var verbose = false; var quiet = false; var commandOptions = new CommandLineOptions(); string targetName = null; var p = new OptionSet { { "h|?|help", "Show help", v => help = v != null }, { "r|reporter=", "Reporter type (not used)", v => Console.Error.WriteLine("WARNING: --reporter is deprecated and has no effect.") }, { "l|logfile=", "Write output to this file instead of stdout", v => commandOptions.LogFileName = v }, { "t|target=", "Build target. Supported: android, dotnet and native", v => targetName = v }, { "v|verbose", "Verbose, always prints output from compiler and debug_log", v => verbose = v != null }, { "q|quiet", "Quiet, only prints output from compiler and debug_log in case of errors.", v => quiet = v != null }, { "f|filter=", "Only run tests matching this string", v => commandOptions.Filter = Regex.Escape(v) }, { "e|regex-filter=", "Only run tests matching this regular expression", v => commandOptions.Filter = v }, { "o|timeout=", "Timeout for individual tests (in seconds)", (int v) => Console.Error.WriteLine("WARNING: --timeout is deprecated and has no effect.") }, { "startup-timeout=", "Timeout for connection from uno process (in seconds)", (int v) => Console.Error.WriteLine("WARNING: --startup-timeout is deprecated and has no effect.") }, { "trace", "Print trace information from unotest", v => { commandOptions.Trace = v != null; } }, { "only-build", "Don't run compiled program.", v => commandOptions.OnlyBuild = v != null }, { "allow-debugger", "Don't run compiled program, allow user to start it from a debugger.", v => Console.Error.WriteLine("WARNING: --allow-debugger is deprecated and has no effect.") }, { "d|debug", "Open IDE for debugging tests.", v => Console.Error.WriteLine("WARNING: --debug is deprecated and has no effect.") }, { "run-local", "Run the test directly (not used)", v => Console.Error.WriteLine("WARNING: --run-local is deprecated and has no effect.") }, { "no-uninstall", "Don't uninstall tests after running on device", v => commandOptions.NoUninstall = v != null }, { "D=|define=", "Add define, to enable a feature", commandOptions.Defines.Add }, { "U=|undefine=", "Remove define, to disable a feature", commandOptions.Undefines.Add }, { "output-dir=", "Override output directory", v => commandOptions.OutputDirectory = v }, { "libs", "Rebuild package library if necessary", v => commandOptions.Library = true }, }; try { var extra = p.Parse(args); commandOptions.Target = BuildTargets.Get(targetName, extra); commandOptions.Paths = extra; commandOptions.Verbose = verbose; if (verbose && quiet) { throw new ArgumentException("Cannot specify both -q and -v"); } } catch (OptionException e) { Console.WriteLine(e); PrintHelp(p); return(null); } if (help) { PrintHelp(p); return(null); } return(commandOptions); }
public override void Execute(IEnumerable <string> args) { string targetName = null; string outputDir = null; var configuration = BuildConfiguration.Debug; var nativeArgs = new List <string>(); var runArgs = new List <string>(); var build = false; var run = false; var input = new OptionSet { { "t=|target=", value => targetName = value }, { "c=|configuration=", value => configuration = value.ParseEnum <BuildConfiguration>("configuration") }, { "o=|out-dir|output-dir=", value => outputDir = value }, { "n=|native-args=", nativeArgs.Add }, { "a=|run-args=", runArgs.Add }, { "b|build", value => build = true }, { "d|debug", value => runArgs.Add("debug") }, { "r|run", value => run = true }, } .Parse(args); var target = BuildTargets.Get(targetName, input); var project = Project.Load(input.Path(".").GetProjectFile()); if (string.IsNullOrEmpty(outputDir)) { outputDir = project.GetOutputDirectory(configuration, target); } var file = new BuildFile(outputDir); if (!file.Exists) { throw new InvalidOperationException("Target was not built -- run 'uno build' first"); } if (build || nativeArgs.Count > 0) { if (!target.CanBuild(file)) { // If the build script is missing it's probably not needed Log.Warning("A build script was not found in " + outputDir.Quote()); } else if (!target.Build(Shell, file, string.Join(" ", nativeArgs))) { ExitCode = 1; return; } } if (run || runArgs.Count > 0) { if (!target.CanRun(file) || !target.Run(Shell, file, string.Join(" ", runArgs)).Result) { ExitCode = 1; } } }
TestOptions Parse(IEnumerable <string> args) { var verbose = Log.IsVerbose; var quiet = false; var options = new TestOptions(); string targetName = null; var p = new OptionSet { { "r|reporter=", v => Log.Warning("--reporter is deprecated and has no effect.") }, { "l|logfile=", v => options.LogFile = v }, { "t|target=", v => targetName = v }, { "v|verbose", v => verbose = v != null }, { "q|quiet", v => quiet = v != null }, { "f|filter=", v => options.Filter = Regex.Escape(v) }, { "e|regex-filter=", v => options.Filter = v }, { "timeout=", v => Log.Warning("--timeout is deprecated and has no effect.") }, { "startup-timeout=", v => Log.Warning("--startup-timeout is deprecated and has no effect.") }, { "trace", v => { options.Trace = v != null; } }, { "b|build-only|only-build", v => options.OnlyBuild = v != null }, { "g|gen-only", v => options.OnlyGenerate = v != null }, { "allow-debugger", v => Log.Warning("--allow-debugger is deprecated and has no effect.") }, { "d|debug", v => Log.Warning("--debug is deprecated and has no effect.") }, { "run-local", v => Log.Warning("--run-local is deprecated and has no effect.") }, { "no-uninstall", v => options.DontUninstall = v != null }, { "D=|define=", options.Defines.Add }, { "U=|undefine=", options.Undefines.Add }, { "o=|out-dir=|output-dir=", v => options.OutputDirectory = v }, { "libs", v => options.UpdateLibrary = true }, }; try { var extra = p.Parse(args); options.Target = BuildTargets.Get(targetName, extra); options.Paths = extra; options.Verbose = verbose; if (verbose && quiet) { throw new ArgumentException("Cannot specify both -q and -v"); } } catch (OptionException e) { Log.WriteErrorLine(e.ToString()); Help(); return(null); } return(options); }
public override void Execute(IEnumerable <string> args) { var recursive = false; string targetName = null; BuildConfiguration configuration = 0; var input = new OptionSet { { "t=|target=", value => targetName = value }, { "c=|configuration=", value => configuration = value.ParseEnum <BuildConfiguration>("configuration") }, { "r|recursive", value => recursive = true } }.Parse(args); var target = BuildTargets.Get(targetName, input, canReturnNull: true); var files = input.Paths(".").GetProjectFiles(recursive); new ProjectCleaner(Log, target, configuration) .Clean(files); }
public override void Help() { WriteUsage("[target] [options] [project-path ...]"); WriteHead("Examples", 28); WriteRow("uno clean", "Clean all build-files (in current directory)"); WriteRow("uno clean android -c Release", "Clean only Android files (Release configuration)"); WriteHead("Available options", 26); WriteRow("-t, --target=STRING", "Build target (see: Available build targets)"); WriteRow("-c, --configuration=STRING", "Build configuration [Debug|Release]"); WriteRow("-r, --recursive", "Look for project files recursively"); WriteHead("Available build targets", 19); foreach (var c in BuildTargets.Enumerate(Log.EnableExperimental)) { WriteRow("* " + c.Identifier.ToLowerInvariant()); } }
public override void Help() { WriteUsage("[target] [options] [paths-to-search]"); Log.Skip(); WriteLine("[paths-to-search] is a list of paths to unoprojs to run tests from, and/or"); WriteLine("directories in which to search for test projects."); Log.Skip(); WriteLine("When a directory is given, uno test searches recursively in that directory"); WriteLine("for projects named '*Test.unoproj'"); WriteHead("Examples"); WriteLine(" uno test"); WriteLine(" uno test path/projects"); WriteLine(" uno test path/projects/FooTest.unoproj path/projects/BarTest.unoproj"); WriteLine(" uno test path/projects path/other-projects/FooTest.unoproj"); WriteLine(" uno test native -v path/projects"); WriteHead("Available options", 26); WriteRow("-l, --logfile=PATH", "Write output to this file instead of stdout"); WriteRow("-t, --target=STRING", "Build target (see: Available build targets)"); WriteRow("-v, --verbose", "Verbose, always prints output from compiler and app"); WriteRow("-q, --quiet", "Quiet, only prints output from compiler and app in case of errors"); WriteRow("-f, --filter=", "Only run tests matching this string"); WriteRow("-e, --regex-filter=STRING", "Only run tests matching this regular expression"); WriteRow(" --trace", "Print trace information from unotest"); WriteRow("-b, --build-only", "Don't run tests; only build"); WriteRow("-g, --gen-only", "Don't run tests; only generate code"); WriteRow(" --no-uninstall", "Don't uninstall tests after running on device"); WriteRow("-D, --define=STRING", "Add define, to enable a feature"); WriteRow("-U, --undefine=STRING", "Remove define, to disable a feature"); WriteRow("-o, --out-dir=PATH", "Override output directory"); WriteHead("Available build targets", 19); foreach (var c in BuildTargets.Enumerate(false)) { WriteRow("* " + c.Identifier, c.Description); } }
public MainWindow() { InitializeComponent(); State = new AppState(this); BuildService = new BuildService(this, this); Title = DefaultTitle; DataContext = this; NonActiveWindowTitleBrush = WindowTitleBrush; TextEditor.TextArea.TextView.LinkTextForegroundBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#99DAF9")); TreeView.SelectedItemChanged += UpdateSelection; DisasmBox.SelectionChanged += UpdateSelection; DisasmBox.SelectedItem = Disassemblers.First(); VisibilityBox.SelectionChanged += UpdateSelection; VisibilityBox.SelectedItem = VisibilityModes[1]; SizeChanged += (s, e) => State.UpdateSize(); Closing += (s, e) => State.UpdateSize(); Closed += (s, e) => Dispose(); TreeView.ContextMenuOpening += (s, e) => TreeView.ContextMenu = GetContextMenu(TreeView.GetContainerAtPoint <TreeViewItem>(Mouse.GetPosition(TreeView))?.DataContext as ILItem); TreeView.MouseDoubleClick += (s, e) => DoubleClick(TreeView.SelectedItem as ILItem); TextEditor.ContextMenuOpening += (s, e) => TextEditor.ContextMenu = GetContextMenu(TreeView.SelectedItem as ILItem); MainMenu.Visibility = Visibility.Collapsed; KeyUp += (s, e) => { if (e.Key == Key.System) { MainMenu.Visibility = MainMenu.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed; } }; File_Open = new Command( x => { string filename; if (TryOpenProject(out filename)) { BuildService.StartBuild(new[] { filename }); } }); File_Close = new Command( x => Close()); Build_BuildTarget = new Command( x => BuildService.StartBuild()); Build_CleanProject = new Command( x => BuildService.StartClean()); Build_Cancel = new Command( x => BuildService.Cancel(), x => BuildService.IsBuilding); foreach (var target in BuildTargets.Enumerate()) { var targetItem = new MenuItem { Header = target.Identifier }; targetItem.Click += (s, e) => BuildService.StartBuild(target); Build_BuildItem.Items.Add(targetItem); } State.Load(); new DispatcherTimer( TimeSpan.FromSeconds(1.0 / 12.0), DispatcherPriority.ApplicationIdle, FlushLog, Application.Current.Dispatcher) .Start(); FindBox.TextChanged += (s, e) => { if (_completionWindow == null) { _completionWindow = new CompletionWindow(TextEditor.TextArea); _completionWindow.Show(); _completionWindow.Closed += delegate { _completionWindow = null; }; } }; }
internal void Validate(string optionsName) { if (string.IsNullOrWhiteSpace(BuildConfiguration)) { throw new OptionValidationException("Configuration cannot be null or empty.", optionsName, "Configuration"); } if (!Directory.Exists(SolutionDir)) { throw new OptionValidationException( string.Format("The solution directory '{0}' could not be found.", SolutionDir), optionsName, "SolutionDir"); } if (!Directory.Exists(ProjectDir)) { throw new OptionValidationException( string.Format("The project directory '{0}' could not be found.", ProjectDir), optionsName, "ProjectDir"); } if (!File.Exists(ProjectFilePath)) { throw new OptionValidationException( string.Format("The project file '{0}' could not be found.", ProjectFilePath), optionsName, "ProjectFileName"); } if (MsBuildExePathResolver == null) { throw new OptionCannotBeNullException(optionsName, "MsBuildExePathResolver"); } if (BuildTargets == null) { throw new OptionCannotBeNullException(optionsName, "BuildTargets"); } if (BuildTargets.Any(string.IsNullOrWhiteSpace)) { throw new OptionValidationException("Cannot contain build targets that are null or empty.", optionsName, "BuildTargets"); } if (string.IsNullOrWhiteSpace(BuildConfiguration)) { throw new OptionCannotBeNullOrEmptyException(optionsName, "BuildConfiguration"); } if (MsBuildToolsVersion == null) { throw new OptionCannotBeNullException(optionsName, "MsBuildToolsVersion"); } if (AdditionalMsBuildFileLoggers != null && AdditionalMsBuildFileLoggers.Count() > 7) { throw new OptionValidationException("It is not possible to supply more than 7 additional file loggers " + "(since MSBuild only supports 9 in total and 2 are already used internally).", optionsName, "AdditionalMsBuildFileLoggers"); } }
public static CommandLineOptions From(string[] args) { var help = false; var verbose = false; var quiet = false; var commandOptions = new CommandLineOptions { Reporter = "console", TestTimeout = TimeSpan.FromSeconds(10), StartupTimeout = TimeSpan.FromMinutes(1), }; string targetName = null; var p = new OptionSet { { "h|?|help", "Show help", v => help = v != null }, { "r|reporter=", "Reporter type. teamcity|console", v => commandOptions.Reporter = v }, { "l|logfile=", "Write output to this file instead of stdout", v => commandOptions.LogFileName = v }, { "t|target=", "Build target. Currently supports DotNet|Android|CMake", v => targetName = v }, { "v|verbose", "Verbose, always prints output from compiler and debug_log", v => verbose = v != null }, { "q|quiet", "Quiet, only prints output from compiler and debug_log in case of errors.", v => quiet = v != null }, { "f|filter=", "Only run tests matching this string", v => commandOptions.Filter = Regex.Escape(v) }, { "e|regex-filter=", "Only run tests matching this regular expression", v => commandOptions.Filter = v }, { "o|timeout=", "Timeout for individual tests (in seconds)", (int v) => { commandOptions.TestTimeout = TimeSpan.FromSeconds(v); } }, { "startup-timeout=", "Timeout for connection from uno process (in seconds)", (int v) => { commandOptions.StartupTimeout = TimeSpan.FromSeconds(v); } }, { "trace", "Print trace information from unotest", v => { commandOptions.Trace = v != null; } }, { "allow-debugger", "Don't run compiled program, allow user to start it from a debugger.", v => commandOptions.AllowDebugger = v != null }, { "d|debug", "Open IDE for debugging tests.", v => commandOptions.OpenDebugger = v != null }, { "run-local", "Run the test directly, without using HTTP", v => commandOptions.RunLocal = v != null }, { "no-uninstall", "Don't uninstall tests after running on device", v => commandOptions.NoUninstall = v != null }, { "D=|define=", "Add define, to enable a feature", commandOptions.Defines.Add }, { "U=|undefine=", "Remove define, to disable a feature", commandOptions.Undefines.Add }, { "output-dir=", "Override output directory", v => commandOptions.OutputDirectory = v }, { "libs", "Rebuild package library if necessary", v => commandOptions.Library = true }, }; try { var extra = p.Parse(args); commandOptions.Target = BuildTargets.Get(targetName, extra, DefaultTarget); commandOptions.Paths = extra; commandOptions.Verbose = verbose; if (verbose && quiet) { throw new ArgumentException("Cannot specify both -q and -v"); } if (commandOptions.AllowDebugger || commandOptions.OpenDebugger) { commandOptions.StartupTimeout = TimeSpan.FromDays(1); commandOptions.TestTimeout = TimeSpan.FromDays(1); } } catch (OptionException e) { Console.WriteLine(e); PrintHelp(p); return(null); } if (help) { PrintHelp(p); return(null); } return(commandOptions); }
public static int Main(string[] args) { TargetTree targetTree = new TargetTree(); BuildTargets.FillBuildTargets(targetTree); int testsRunCounter = 0; targetTree.AddTarget("rebuild") .SetAsDefault() .SetDescription("Rebuilds the whole project") .DependsOn("compile", "fxcop", "tests", "package"); targetTree.GetTarget("fetch.build.version") .Do(TargetFetchBuildVersion); targetTree.AddTarget("tests") .SetDescription("Runs unit tests") .Do(r => { BuildTargets.TargetRunTests(r, "Detergent.Tests", null, ref testsRunCounter); }).DependsOn("load.solution"); targetTree.AddTarget("package") .SetDescription("Packages the build") .Do(TargetPackage).DependsOn("load.solution", "fetch.build.version"); targetTree.AddTarget("nuget") .SetDescription("Produces NuGet packages for reusable components and publishes them to the NuGet server") .Do(c => { TargetNuGet(c, "Detergent"); }).DependsOn("fetch.build.version"); using (TaskSession session = new TaskSession(new SimpleTaskContextProperties(), args, targetTree)) { BuildTargets.FillDefaultProperties(session); session.Start(BuildTargets.OnBuildFinished); session.AddLogger(new MulticoloredConsoleLogger(Console.Out)); //session.Properties.Set(BuildProps.TargetDotNetVersion, "v4.0.30319"); //session.Properties.Set(BuildProps.TargetDotNetVersionForGallio, "v4.0.30319"); session.Properties.Set(BuildProps.CompanyName, CompanyName); session.Properties.Set(BuildProps.CompanyCopyright, CompanyCopyright); session.Properties.Set(BuildProps.GallioEchoPath, "lib/Gallio-3.2.750/bin/Gallio.Echo.exe"); session.Properties.Set(BuildProps.ProductId, "Detergent"); session.Properties.Set(BuildProps.ProductName, "Detergent"); session.Properties.Set(BuildProps.SolutionFileName, "Detergent.2010.sln"); session.Properties.Set(BuildProps.VersionControlSystem, VersionControlSystem.Subversion); try { // actual run if (args.Length == 0) { targetTree.RunTarget(session, targetTree.DefaultTarget.TargetName); } else { string targetName = args[0]; if (false == targetTree.HasTarget(targetName)) { session.WriteError("ERROR: The target '{0}' does not exist", targetName); targetTree.RunTarget(session, "help"); return(2); } targetTree.RunTarget(session, args[0]); } session.Complete(); return(0); } catch (TaskExecutionException) { return(1); } catch (Exception ex) { Console.WriteLine(ex); return(1); } } }
public static ProjectDetails LoadProjectDetails(string projectFile, string configuration) { var key = Tuple.Create(projectFile, configuration); ProjectDetails details; if (_allProjects.TryGetValue(key, out details)) { if (!details.HasChanged()) { if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { _log.Debug($"Using cached project file details for [{projectFile}]"); } return(details); } else { if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { _log.Debug($"Reloading project file details [{projectFile}] as one of its imports has been modified."); } } } if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { _log.Debug($"Loading project file [{projectFile}]"); } details = new ProjectDetails(); var properties = new Dictionary <string, string>(ImmutableDictionary <string, string> .Empty); properties["DesignTimeBuild"] = "true"; // this will tell msbuild to not build the dependent projects properties["BuildingInsideVisualStudio"] = "true"; // this will force CoreCompile task to execute even if all inputs and outputs are up to date properties["BuildingInsideUnoSourceGenerator"] = "true"; // this will force prevent the task to run recursively properties["Configuration"] = configuration; properties["UseHostCompilerIfAvailable"] = "true"; properties["UseSharedCompilation"] = "true"; // Platform is intentionally kept as not defined, to avoid having // dependent projects being loaded with a platform they don't support. // properties["Platform"] = _platform; var xmlReader = XmlReader.Create(projectFile); var collection = new Microsoft.Build.Evaluation.ProjectCollection(); collection.RegisterLogger(new Microsoft.Build.Logging.ConsoleLogger() { Verbosity = LoggerVerbosity.Normal }); collection.OnlyLogCriticalEvents = false; var xml = Microsoft.Build.Construction.ProjectRootElement.Create(xmlReader, collection); // When constructing a project from an XmlReader, MSBuild cannot determine the project file path. Setting the // path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work. xml.FullPath = Path.GetFullPath(projectFile); var loadedProject = new Microsoft.Build.Evaluation.Project( xml, properties, toolsVersion: null, projectCollection: collection ); var buildTargets = new BuildTargets(loadedProject, "Compile"); // don't execute anything after CoreCompile target, since we've // already done everything we need to compute compiler inputs by then. buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: false); details.Configuration = configuration; details.LoadedProject = loadedProject; // create a project instance to be executed by build engine. // The executed project will hold the final model of the project after execution via msbuild. details.ExecutedProject = loadedProject.CreateProjectInstance(); var hostServices = new Microsoft.Build.Execution.HostServices(); // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task. hostServices.RegisterHostObject(loadedProject.FullPath, "CoreCompile", "Csc", null); var buildParameters = new Microsoft.Build.Execution.BuildParameters(loadedProject.ProjectCollection); // This allows for the loggers to buildParameters.Loggers = collection.Loggers; var buildRequestData = new Microsoft.Build.Execution.BuildRequestData(details.ExecutedProject, buildTargets.Targets, hostServices); var result = BuildAsync(buildParameters, buildRequestData); if (result.Exception == null) { ValidateOutputPath(details.ExecutedProject); var projectFilePath = Path.GetFullPath(Path.GetDirectoryName(projectFile)); details.References = details.ExecutedProject.GetItems("ReferencePath").Select(r => r.EvaluatedInclude).ToArray(); if (details.References.None()) { LogFailedTargets(projectFile, result); return(details); } } else { LogFailedTargets(projectFile, result); } _allProjects.TryAdd(key, details); details.BuildImportsMap(); return(details); }
public static int Main(string[] args) { TargetTree targetTree = new TargetTree(); BuildTargets.FillBuildTargets(targetTree); targetTree.GetTarget("fetch.build.version") .Do(TargetFetchBuildVersion); targetTree.AddTarget("rebuild") .SetDescription("Compiles the code and runs tests.") .SetAsDefault().DependsOn("compile", "fxcop", "unit.tests", "package"); targetTree.AddTarget("tests") .SetDescription("Runs tests on the project") .Do(r => { int testCounter = 0; BuildTargets.TargetRunTests(r, "GroundTruth.Tests", null, ref testCounter); }).DependsOn("load.solution"); targetTree.AddTarget("package") .SetDescription("Packages all the build products into ZIP files.") .Do(TargetPackage) .SetAsDefault().DependsOn("load.solution"); //runner.AddTarget ("package.source") // .SetDescription ("Packages the souce code into ZIP file") // .Do (TargetPackageSource).DependsOn ("load.solution"); using (TaskSession session = new TaskSession(new SimpleTaskContextProperties(), args, targetTree)) { BuildTargets.FillDefaultProperties(session); session.Start(BuildTargets.OnBuildFinished); session.AddLogger(new MulticoloredConsoleLogger(Console.Out)); session.Properties.Set(BuildProps.CompanyName, "igorbrejc.net"); session.Properties.Set(BuildProps.CompanyCopyright, "Copyright (C) 2008-2012 Igor Brejc."); session.Properties.Set(BuildProps.ProductId, "GroundTruth"); session.Properties.Set(BuildProps.ProductName, "GroundTruth"); session.Properties.Set(BuildProps.SolutionFileName, "GroundTruth.sln"); session.Properties.Set(BuildProps.VersionControlSystem, VersionControlSystem.Mercurial); try { // actual run if (args.Length == 0) { targetTree.RunTarget(session, targetTree.DefaultTarget.TargetName); } else { string targetName = args[0]; if (false == targetTree.HasTarget(targetName)) { session.WriteError("ERROR: The target '{0}' does not exist", targetName); targetTree.RunTarget(session, "help"); return(2); } targetTree.RunTarget(session, args[0]); } session.Complete(); return(0); } catch (TaskExecutionException) { return(1); } catch (Exception ex) { Console.WriteLine(ex); return(1); } } }
private void BuildTargetsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { settingsService.Set(project.BuildTargetsKey(), BuildTargets.ToList()); }
public static BuildArguments Parse(IEnumerable <string> args, Log log = null) { if (log == null) { log = Log; } string targetName = null; var options = new BuildOptions { PackageTarget = BuildTargets.Package }; var nativeArgs = new List <string>(); var runArgs = new List <string>(); var run = false; var input = new OptionSet { { "t=|target=", value => targetName = value }, { "c=|configuration=", value => options.Configuration = value.ParseEnum <BuildConfiguration>("configuration") }, { "s=|set=", value => value.ParseProperty("s|set", options.Settings) }, { "p|print-internals", value => options.PrintInternals = true }, { "o=|out-dir|output-dir=", value => options.OutputDirectory = value }, { "m=|main=|main-class=", value => options.MainClass = value }, { "n=|native-args=", nativeArgs.Add }, { "a=|run-args=", runArgs.Add }, { "test-server-url=", value => options.TestServerUrl = value }, { "P|no-parallel", value => options.Parallel = false }, { "N|q|no-native", value => options.Native = false }, { "S|e|no-strip", value => options.Strip = false }, { "E=|max-errors=", value => Log.MaxErrorCount = value.ParseInt("E") }, { "W=", value => options.WarningLevel = value.ParseInt("W") }, { "O=", value => options.OptimizeLevel = value.ParseInt("O") }, { "D=|define=", options.Defines.Add }, { "U=|undefine=", options.Undefines.Add }, { "release", value => options.Configuration = BuildConfiguration.Release }, { "test", value => options.Test = true }, { "z|clean", value => options.Clean = true }, { "d|debug", value => runArgs.Add("debug") }, { "r|run", value => run = true }, { "l|libs", value => options.Library = true }, { "f|force", value => options.Force = true }, { "cd=", value => Directory.SetCurrentDirectory(value.ParseString("cd")) }, { "v", value => log.Level++ }, { "x", value => Log.EnableExperimental = true } }.Parse(args); var target = BuildTargets.Get(targetName, input); var project = input.Path(".").GetProjectFile(); options.NativeArguments = string.Join(" ", nativeArgs); options.RunArguments = string.Join(" ", runArgs); if (runArgs.Count > 0 && runArgs[0] == "debug") { options.Native = false; // disable native build options.Defines.Add("DEBUG_NATIVE"); // disable native optimizations (debug build) } return(new BuildArguments { Log = log, Options = options, Target = target, ProjectFile = project, Run = run || runArgs.Count > 0, }); }
public static ProjectDetails LoadProjectDetails(BuildEnvironment environment) { var key = Tuple.Create(environment.ProjectFile, environment.Configuration); ProjectDetails details; if (_allProjects.TryGetValue(key, out details)) { if (!details.HasChanged()) { if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { _log.LogDebug($"Using cached project file details for [{environment.ProjectFile}]"); } return(details); } else { if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { _log.LogDebug($"Reloading project file details [{environment.ProjectFile}] as one of its imports has been modified."); } } } if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { _log.LogDebug($"Loading project file [{environment.ProjectFile}]"); } details = new ProjectDetails(); var properties = new Dictionary <string, string>(ImmutableDictionary <string, string> .Empty) { ["DesignTimeBuild"] = "true", // this will tell msbuild to not build the dependent projects ["BuildingInsideVisualStudio"] = "true", // this will force CoreCompile task to execute even if all inputs and outputs are up to date ["BuildingInsideUnoSourceGenerator"] = "true", // this will force prevent the task to run recursively ["Configuration"] = environment.Configuration, ["UseHostCompilerIfAvailable"] = "true", ["UseSharedCompilation"] = "true", ["VisualStudioVersion"] = environment.VisualStudioVersion, // Force the intermediate path to be different from the VS default path // so that the generated files don't mess up the file count for incremental builds. ["IntermediateOutputPath"] = Path.Combine(environment.OutputPath, "obj") + Path.DirectorySeparatorChar }; // Target framework is required for the MSBuild 15.0 Cross Compilation. // Loading a project without the target framework results in an empty project, which interatively // sets the TargetFramework property. if (environment.TargetFramework.HasValue()) { properties["TargetFramework"] = environment.TargetFramework; } // TargetFrameworkRootPath is used by VS4Mac to determine the // location of frameworks like Xamarin.iOS. if (environment.TargetFrameworkRootPath.HasValue()) { properties["TargetFrameworkRootPath"] = environment.TargetFrameworkRootPath; } // Platform is intentionally kept as not defined, to avoid having // dependent projects being loaded with a platform they don't support. // properties["Platform"] = _platform; var xmlReader = XmlReader.Create(environment.ProjectFile); var collection = new Microsoft.Build.Evaluation.ProjectCollection(); // Change this logger details to troubleshoot project loading details. collection.RegisterLogger(new Microsoft.Build.Logging.ConsoleLogger() { Verbosity = LoggerVerbosity.Minimal }); // Uncomment this to enable file logging for debugging purposes. // collection.RegisterLogger(new Microsoft.Build.BuildEngine.FileLogger() { Verbosity = LoggerVerbosity.Diagnostic, Parameters = $@"logfile=c:\temp\build\MSBuild.{Guid.NewGuid()}.log" }); collection.OnlyLogCriticalEvents = false; var xml = Microsoft.Build.Construction.ProjectRootElement.Create(xmlReader, collection); // When constructing a project from an XmlReader, MSBuild cannot determine the project file path. Setting the // path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work. xml.FullPath = Path.GetFullPath(environment.ProjectFile); var loadedProject = new Microsoft.Build.Evaluation.Project( xml, properties, toolsVersion: null, projectCollection: collection ); var buildTargets = new BuildTargets(loadedProject, "Compile"); // don't execute anything after CoreCompile target, since we've // already done everything we need to compute compiler inputs by then. buildTargets.RemoveAfter("CoreCompile", includeTargetInRemoval: true); details.Configuration = environment.Configuration; details.LoadedProject = loadedProject; // create a project instance to be executed by build engine. // The executed project will hold the final model of the project after execution via msbuild. details.ExecutedProject = loadedProject.CreateProjectInstance(); var hostServices = new Microsoft.Build.Execution.HostServices(); // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task. hostServices.RegisterHostObject(loadedProject.FullPath, "CoreCompile", "Csc", null); var buildParameters = new Microsoft.Build.Execution.BuildParameters(loadedProject.ProjectCollection); // This allows for the loggers to buildParameters.Loggers = collection.Loggers; var buildRequestData = new Microsoft.Build.Execution.BuildRequestData(details.ExecutedProject, buildTargets.Targets, hostServices); var result = BuildAsync(buildParameters, buildRequestData); if (result.Exception == null) { ValidateOutputPath(details.ExecutedProject); var projectFilePath = Path.GetFullPath(Path.GetDirectoryName(environment.ProjectFile)); details.References = details.ExecutedProject.GetItems("ReferencePath").Select(r => r.EvaluatedInclude).ToArray(); if (!details.References.Any()) { if (_log.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Error)) { _log.LogError($"Project has no references."); } LogFailedTargets(environment.ProjectFile, result); details.Generators = new (Type, Func <SourceGenerator>)[0];