static bool TryCreateGitWorkingSet(DirectoryReference RootDir, IEnumerable <DirectoryReference> ProjectDirs, out GitSourceFileWorkingSet OutWorkingSet)
        {
            GitSourceFileWorkingSet WorkingSet = null;

            // Create the working set for the engine directory
            if (DirectoryReference.Exists(DirectoryReference.Combine(RootDir, ".git")))
            {
                WorkingSet = new GitSourceFileWorkingSet(GitPath, RootDir, WorkingSet);
            }

            // Try to create a working set for the project directory
            foreach (DirectoryReference ProjectDir in ProjectDirs)
            {
                if (WorkingSet == null || !ProjectDir.IsUnderDirectory(RootDir))
                {
                    if (DirectoryReference.Exists(DirectoryReference.Combine(ProjectDir, ".git")))
                    {
                        WorkingSet = new GitSourceFileWorkingSet(GitPath, ProjectDir, WorkingSet);
                    }
                    else if (DirectoryReference.Exists(DirectoryReference.Combine(ProjectDir.ParentDirectory, ".git")))
                    {
                        WorkingSet = new GitSourceFileWorkingSet(GitPath, ProjectDir.ParentDirectory, WorkingSet);
                    }
                }
            }

            // Set the output value
            OutWorkingSet = WorkingSet;
            return(WorkingSet != null);
        }
Example #2
0
        public void TestDiscoverGlobalConfigFilesWhenEditorConfigDisabled()
        {
            var srcFile           = ProjectDir.CreateFile("lib1.cs").WriteAllText("class C { }");
            var globalConfigFile  = ProjectDir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");
            var subdir            = ProjectDir.CreateDirectory("subdir");
            var srcFile2          = subdir.CreateFile("lib2.cs").WriteAllText("class D { }");
            var globalConfigFile2 = subdir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");

            VerifyValues(
                customProps: @"
<PropertyGroup>
    <DiscoverEditorConfigFiles>false</DiscoverEditorConfigFiles>
</PropertyGroup>",
                customTargets: null,
                targets: new[]
            {
                "CoreCompile"
            },
                expressions: new[]
            {
                "@(EditorConfigFiles)"
            },
                expectedResults: AppendExtraEditorConfigs(new[]
            {
                globalConfigFile.Path,
                globalConfigFile2.Path
            }, findEditorConfigs: false));
        }
Example #3
0
        public void TestGlobalConfigsCanBeManuallyAdded()
        {
            var srcFile          = ProjectDir.CreateFile("lib1.cs").WriteAllText("class C { }");
            var globalConfigFile = ProjectDir.CreateFile("mycustom.config").WriteAllText(@"is_global = true
some_prop = some_val");

            VerifyValues(
                customProps: @"
<ItemGroup>
    <GlobalAnalyzerConfigFiles Include=""mycustom.config"" />
</ItemGroup>",
                customTargets: null,
                targets: new[]
            {
                "CoreCompile"
            },
                expressions: new[]
            {
                "@(EditorConfigFiles)"
            },
                expectedResults: AppendExtraEditorConfigs(new[]
            {
                Path.Combine(ProjectDir.Path, ".editorconfig"),
                "mycustom.config"
            }));
        }
Example #4
0
        public void TestDiscoverGlobalConfigFilesCanBeDisabled()
        {
            var srcFile           = ProjectDir.CreateFile("lib1.cs").WriteAllText("class C { }");
            var globalConfigFile  = ProjectDir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");
            var subdir            = ProjectDir.CreateDirectory("subdir");
            var srcFile2          = subdir.CreateFile("lib2.cs").WriteAllText("class D { }");
            var globalConfigFile2 = subdir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");

            VerifyValues(
                customProps: @"
<PropertyGroup>
  <DiscoverGlobalAnalyzerConfigFiles>false</DiscoverGlobalAnalyzerConfigFiles>
  <!-- Disable automatic global .editorconfig generation by the SDK --> 
  <GenerateMSBuildEditorConfigFile>false</GenerateMSBuildEditorConfigFile>
</PropertyGroup>",
                customTargets: null,
                targets: new[]
            {
                "CoreCompile"
            },
                expressions: new[]
            {
                "@(EditorConfigFiles)"
            },
                expectedResults: AppendExtraEditorConfigs(new[]
            {
                Path.Combine(ProjectDir.Path, ".editorconfig"),
            }, findGlobalConfigs: false));
        }
Example #5
0
        public void TestDiscoverEditorAndGlobalConfigFilesCanBeDisabled()
        {
            var srcFile           = ProjectDir.CreateFile("lib1.cs").WriteAllText("class C { }");
            var globalConfigFile  = ProjectDir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");
            var subdir            = ProjectDir.CreateDirectory("subdir");
            var globalConfigFile2 = subdir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");

            VerifyValues(
                customProps: @"
<PropertyGroup>
    <DiscoverEditorConfigFiles>false</DiscoverEditorConfigFiles>
    <DiscoverGlobalAnalyzerConfigFiles>false</DiscoverGlobalAnalyzerConfigFiles>
</PropertyGroup>",
                customTargets: null,
                targets: new[]
            {
                "CoreCompile"
            },
                expressions: new[]
            {
                "@(EditorConfigFiles)"
            },
                expectedResults: new[] { "" });
        }
Example #6
0
        public void TestDiscoverGlobalConfigFiles()
        {
            var srcFile           = ProjectDir.CreateFile("lib1.cs").WriteAllText("class C { }");
            var globalConfigFile  = ProjectDir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");
            var subdir            = ProjectDir.CreateDirectory("subdir");
            var srcFile2          = subdir.CreateFile("lib2.cs").WriteAllText("class D { }");
            var globalConfigFile2 = subdir.CreateFile(".globalconfig").WriteAllText(@"is_global = true
some_prop = some_val");

            VerifyValues(
                customProps: null,
                customTargets: null,
                targets: new[]
            {
                "CoreCompile"
            },
                expressions: new[]
            {
                "@(EditorConfigFiles)"
            },
                expectedResults: AppendExtraEditorConfigs(new[]
            {
                Path.Combine(ProjectDir.Path, ".editorconfig"),
                globalConfigFile.Path,
                globalConfigFile2.Path
            }));
        }
Example #7
0
 public static void KeepOnly(ProjectDir folder, Predicate <Procedure> predicate)
 {
     folder.Processes.RemoveWhere(p => !predicate(p));
     foreach (ProjectDir subFolder in folder.Childs)
     {
         KeepOnly(subFolder, predicate);
     }
 }
Example #8
0
        public static void ExpandFolder(ProjectDir folder)
        {
            if (folder == null)
            {
                return;
            }
            folder.IsExpanded = true;
            ProjectDir parentFolder = folder.Parent;

            while (parentFolder != null)
            {
                parentFolder.IsExpanded = true;
                parentFolder            = parentFolder.Parent;
            }
        }
Example #9
0
        protected string WriteMigration(
            ScaffoldedMigration scaffoldedMigration,
            bool rescaffolding = false,
            bool force         = false,
            string name        = null)
        {
            DebugCheck.NotNull(scaffoldedMigration);

            var userCodeFileName         = scaffoldedMigration.MigrationId + "." + scaffoldedMigration.Language;
            var userCodePath             = Path.Combine(scaffoldedMigration.Directory, userCodeFileName);
            var absoluteUserCodePath     = Path.Combine(ProjectDir.Value(), userCodePath);
            var designerCodeFileName     = scaffoldedMigration.MigrationId + ".Designer." + scaffoldedMigration.Language;
            var designerCodePath         = Path.Combine(scaffoldedMigration.Directory, designerCodeFileName);
            var absoluteDesignerCodePath = Path.Combine(ProjectDir.Value(), designerCodePath);
            var resourcesFileName        = scaffoldedMigration.MigrationId + ".resx";
            var resourcesPath            = Path.Combine(scaffoldedMigration.Directory, resourcesFileName);

            if (rescaffolding && !force)
            {
                if (!string.Equals(scaffoldedMigration.UserCode, File.ReadAllText(absoluteUserCodePath)))
                {
                    Debug.Assert(!string.IsNullOrWhiteSpace(name));

                    Reporter.WriteWarning(string.Format(MyResources.RescaffoldNoForce, name));
                }
            }
            else
            {
                Directory.CreateDirectory(Path.GetDirectoryName(absoluteUserCodePath));
                File.WriteAllText(absoluteUserCodePath, scaffoldedMigration.UserCode, Encoding.UTF8);
            }

            var absoluteResourcesPath = Path.Combine(ProjectDir.Value(), resourcesPath);

            using (var writer = new ResXResourceWriter(absoluteResourcesPath))
            {
                foreach (var i in scaffoldedMigration.Resources)
                {
                    writer.AddResource(i.Key, i.Value);
                }
            }

            Directory.CreateDirectory(Path.GetDirectoryName(absoluteDesignerCodePath));
            File.WriteAllText(absoluteDesignerCodePath, scaffoldedMigration.DesignerCode, Encoding.UTF8);

            return(userCodePath);
        }
Example #10
0
        /// <summary>
        /// Enumerate projects under the given directory
        /// </summary>
        /// <param name="SolutionDir">Base directory to enumerate</param>
        /// <returns>List of project files</returns>
        static List <FileInfo> EnumerateProjects(DirectoryInfo SolutionDir)
        {
            // Enumerate all the projects in the same directory as the solution. If there's one here, we don't need to consider any other.
            List <FileInfo> ProjectFiles = new List <FileInfo>(SolutionDir.EnumerateFiles("*.uproject"));

            if (ProjectFiles.Count == 0)
            {
                // Build a list of all the parent directories for projects. This includes the UE4 root, plus any directories referenced via .uprojectdirs files.
                List <DirectoryInfo> ParentProjectDirs = new List <DirectoryInfo>();
                ParentProjectDirs.Add(SolutionDir);

                // Read all the .uprojectdirs files
                foreach (FileInfo ProjectDirsFile in SolutionDir.EnumerateFiles("*.uprojectdirs"))
                {
                    foreach (string Line in File.ReadAllLines(ProjectDirsFile.FullName))
                    {
                        string TrimLine = Line.Trim().Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar).Trim(Path.DirectorySeparatorChar);
                        if (TrimLine.Length > 0 && !TrimLine.StartsWith(";"))
                        {
                            try
                            {
                                ParentProjectDirs.Add(new DirectoryInfo(Path.Combine(SolutionDir.FullName, TrimLine)));
                            }
                            catch (Exception Ex)
                            {
                                Logging.WriteLine(String.Format("EnumerateProjects: Exception trying to resolve project directory '{0}': {1}", TrimLine, Ex.Message));
                            }
                        }
                    }
                }

                // Add projects in any subfolders of the parent directories
                HashSet <string> CheckedParentDirs = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);
                foreach (DirectoryInfo ParentProjectDir in ParentProjectDirs)
                {
                    if (CheckedParentDirs.Add(ParentProjectDir.FullName) && ParentProjectDir.Exists)
                    {
                        foreach (DirectoryInfo ProjectDir in ParentProjectDir.EnumerateDirectories())
                        {
                            ProjectFiles.AddRange(ProjectDir.EnumerateFiles("*.uproject"));
                        }
                    }
                }
            }
            return(ProjectFiles);
        }
Example #11
0
        public async Task <IHttpActionResult> SaveFolder([DynamicBody] dynamic param)
        {
            try
            {
                ProjectDir folder  = param.folder;
                var        content = await _prepareService.SaveFolder(folder);

                await _analyzeRepository.RefreshProcess(new AnalyzeEventArgs(nameof(SaveFolder), content, TargetAnalyze.ProjectDir));

                return(Ok(content));
            }
            catch (Exception ex)
            {
                _traceManager.TraceError(ex, ex.Message);
                return(InternalServerError(ex));
            }
        }
Example #12
0
        public static ProjectDir FindFolder(INode node, int folderId)
        {
            ProjectDir resultFolder = null;

            if (node is ProjectDir folder)
            {
                if (folder.Id == folderId)
                {
                    return(folder);
                }
                foreach (ProjectDir subfolder in folder.Childs)
                {
                    resultFolder = FindFolder(subfolder, folderId);
                    if (resultFolder != null)
                    {
                        return(resultFolder);
                    }
                }
            }
            return(resultFolder);
        }
Example #13
0
        /// <summary>
        /// Tries to find a workspace for the current project directory. Failing this, either prompts
        /// the user where to set the workspace (if permitted by the application state), or assumes the
        /// project directory to be the workspace directory (if running silently or if executing tests).
        /// </summary>
        /// <returns><code>true</code> if a workspaces was either found or has been created; <code>false</code> otherwise.</returns>
        private bool EnsureValidWorkspace()
        {
            // Find the vForge workspace directory. This may be any directory above the
            // project directory.
            // If no workspace could be found, either show a dialog (if allowed) or assume the project directory.
            if (!EditorManager.EngineManager.FindWorkspaceDirectory(ProjectDir, "workspace", out WorkspaceDir, out ProjectSearchPath))
            {
                if (!TestManager.IsRunning && !EditorManager.SilentMode)
                {
                    WorkspaceDlg dlg = new WorkspaceDlg(ProjectDir);
                    if (dlg.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    WorkspaceDir = dlg.UseProjectDir ? ProjectDir : dlg.SelectedDir.FullName;
                    if (!CreateWorkspaceFile())
                    {
                        return(false);
                    }
                    ProjectSearchPath = ":workspace/" + ProjectDir.Substring(WorkspaceDir.Length).Replace('\\', '/');
                    ProjectSearchPath = ProjectSearchPath.Trim('/');
                }
                else
                {
                    WorkspaceDir      = ProjectDir;
                    ProjectSearchPath = ":workspace";
                }
            }

            // We have a workspace. Add it as a file system to the Engine.
            if (!EditorManager.EngineManager.File_AddFileSystem("workspace", WorkspaceDir, FileSystemFlags.Writable))
            {
                return(false);
            }

            return(true);
        }
        public void InitializeSourceRootMappedPathsReturnsSourceMap(bool deterministicSourcePaths)
        {
            ProjectDir.CreateFile("Project2.csproj").WriteAllText($@"
<Project Sdk='Microsoft.NET.Sdk'>
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <DeterministicSourcePaths>{deterministicSourcePaths}</DeterministicSourcePaths>
  </PropertyGroup>
  <ItemGroup>
    <SourceRoot Include=""X\""/>
    <SourceRoot Include=""Y\"" ContainingRoot=""X\"" NestedRoot=""A""/>
    <SourceRoot Include=""Z\"" ContainingRoot=""X\"" NestedRoot=""B""/>
  </ItemGroup>
</Project>
");

            VerifyValues(
                customProps: $@"
<ItemGroup>
<ProjectReference Include=""Project2.csproj"" Targets=""InitializeSourceRootMappedPaths"" OutputItemType=""ReferencedProjectSourceRoots"" ReferenceOutputAssembly=""false"" />
</ItemGroup>
",
                customTargets: null,
                targets: new[]
            {
                "ResolveProjectReferences;_BeforeVBCSCoreCompile"
            },
                expressions: new[]
            {
                "@(ReferencedProjectSourceRoots)",
            },
                expectedResults: new[]
            {
                $"X{Path.DirectorySeparatorChar}",
                $"Y{Path.DirectorySeparatorChar}",
                $"Z{Path.DirectorySeparatorChar}",
            });
        }
Example #15
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 (IsClassic && minimumOSVersion < IPhoneSdkVersion.V3_1 && architectures.HasFlag(TargetArchitecture.ARMv7))
            {
                Log.LogWarning(null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, "Deployment Target changed from iOS {0} to iOS 3.1 (minimum requirement for ARMv7)", minimumOSVersion);
                minimumOSVersion = IPhoneSdkVersion.V3_1;
            }

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

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

            if (IsClassic || IPhoneSdks.MonoTouch.Version < new IPhoneSdkVersion(8, 5, 0))
            {
                args.Add("--nomanifest");
                args.Add("--nosign");
            }

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

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

            args.Add("--executable");
            args.AddQuoted(ExecutableName);

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

            if (Debug)
            {
                if (FastDev && IPhoneSdks.MonoTouch.SupportsFastDev)
                {
                    args.Add("--fastdev");
                }

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

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

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

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

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

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

            args.Add("--sdkroot");
            args.AddQuoted(SdkRoot);

            args.Add("--sdk");
            args.AddQuoted(SdkVersion);

            if (!minimumOSVersion.IsUseDefault)
            {
                args.Add("--targetver");
                args.AddQuoted(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");
            }

            if (IPhoneSdks.MonoTouch.SupportsGenericValueTypeSharing)
            {
                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));
            }

            if (!string.IsNullOrEmpty(TLSProvider))
            {
                args.Add(string.Format("--tls-provider={0}", TLSProvider.ToLowerInvariant()));
            }

            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.Add("--symbollist");
            args.AddQuoted(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++)
                {
                    if (extraArgs[i] == "-gcc_flags" || extraArgs[i] == "--gcc_flags")
                    {
                        // user-defined -gcc_flags argument
                        if (i + 1 < extraArgs.Length && !string.IsNullOrEmpty(extraArgs[i + 1]))
                        {
                            var gccArgs = ProcessArgumentBuilder.Parse(extraArgs[i + 1]);

                            for (int j = 0; j < gccArgs.Length; j++)
                            {
                                gcc.Arguments.Add(StringParserService.Parse(gccArgs[j], customTags));
                            }
                        }

                        i++;
                    }
                    else
                    {
                        // other user-defined mtouch arguments
                        args.AddQuoted(StringParserService.Parse(extraArgs[i], customTags));
                    }
                }
            }

            BuildNativeReferenceFlags(gcc);
            BuildEntitlementFlags(gcc);

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

            foreach (var framework in gcc.WeakFrameworks)
            {
                args.Add("-weak-framework");
                args.AddQuoted(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)
            {
                args.Add("-r");
                if (IsFrameworkItem(asm))
                {
                    args.AddQuoted(ResolveFrameworkFile(asm.ItemSpec));
                }
                else
                {
                    args.AddQuoted(Path.GetFullPath(asm.ItemSpec));
                }
            }

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

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

            args.AddQuoted(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());
        }
        protected override int Execute()
        {
            var migrationsDirectory      = _migrationsDir.Value();
            var qualifiedContextTypeName = CreateExecutor().GetContextType(
                _context.Value(),
                _contextAssembly.Value());
            var isVb           = string.Equals(Language.Value(), "VB", StringComparison.OrdinalIgnoreCase);
            var fileName       = isVb ? "Configuration.vb" : "Configuration.cs";
            var templateStream = typeof(MigrationsEnableCommand).Assembly.GetManifestResourceStream("System.Data.Entity.Tools.Templates." + fileName);

            Debug.Assert(templateStream != null);

            string template;

            using (var templateReader = new StreamReader(templateStream, Encoding.UTF8))
            {
                template = templateReader.ReadToEnd();
            }

            var tokens = new Dictionary <string, string>();

            if (!string.IsNullOrWhiteSpace(migrationsDirectory))
            {
                tokens["migrationsDirectory"]
                    = "\r\n            MigrationsDirectory = "
                      + (!isVb ? "@" : null)
                      + "\"" + migrationsDirectory + "\""
                      + (!isVb ? ";" : null);
            }
            else
            {
                migrationsDirectory = "Migrations";
            }

            tokens["enableAutomaticMigrations"]
                = _auto.HasValue()
                      ? (isVb ? "True" : "true")
                      : (isVb ? "False" : "false");

            var rootNamespace       = RootNamespace.Value();
            var migrationsNamespace = migrationsDirectory.Replace("\\", ".");

            tokens["namespace"]
                = !isVb && !string.IsNullOrWhiteSpace(rootNamespace)
                      ? rootNamespace + "." + migrationsNamespace
                      : migrationsNamespace;

            if (isVb && qualifiedContextTypeName.StartsWith(rootNamespace + "."))
            {
                tokens["contextType"]
                    = qualifiedContextTypeName.Substring(rootNamespace.Length + 1).Replace('+', '.');
            }
            else
            {
                tokens["contextType"] = qualifiedContextTypeName.Replace('+', '.');
            }

            if (Path.IsPathRooted(migrationsDirectory))
            {
                throw new CommandException(string.Format(MyResources.MigrationsDirectoryParamIsRooted, migrationsDirectory));
            }

            var absoluteMigrationsDirectory = Path.Combine(ProjectDir.Value(), migrationsDirectory);
            var absolutePath = Path.Combine(absoluteMigrationsDirectory, fileName);

            if (!_force.HasValue() &&
                File.Exists(absolutePath))
            {
                throw new CommandException(string.Format(MyResources.MigrationsAlreadyEnabled, Assembly.Value()));
            }

            var fullMigrationsNamespace = rootNamespace + "." + migrationsNamespace;

            Reporter.WriteInformation(MyResources.EnableMigrations_BeginInitialScaffold);

            var scaffoldedMigration = CreateExecutor().ScaffoldInitialCreate(
                ConnectionStringName.Value(),
                ConnectionString.Value(),
                ConnectionProvider.Value(),
                qualifiedContextTypeName,
                _contextAssembly.Value(),
                fullMigrationsNamespace,
                _auto.HasValue(),
                migrationsDirectory);

            if (scaffoldedMigration != null)
            {
                if (!_auto.HasValue())
                {
                    WriteMigration(scaffoldedMigration);

                    Reporter.WriteWarning(string.Format(
                                              MyResources.EnableMigrations_InitialScaffold,
                                              scaffoldedMigration.MigrationId));
                }

                // We found an initial create so we need to add an explicit ContextKey
                // assignment to the configuration

                tokens["contextKey"]
                    = "\r\n            ContextKey = "
                      + "\"" + qualifiedContextTypeName + "\""
                      + (!isVb ? ";" : null);
            }

            Directory.CreateDirectory(absoluteMigrationsDirectory);
            File.WriteAllText(absolutePath, new TemplateProcessor().Process(template, tokens), Encoding.UTF8);

            if (_json.HasValue())
            {
                string migrationPath          = null;
                string migrationDesignerPath  = null;
                string migrationResourcesPath = null;
                if (scaffoldedMigration != null)
                {
                    migrationPath = Path.Combine(
                        absoluteMigrationsDirectory,
                        scaffoldedMigration.MigrationId + "." + scaffoldedMigration.Language);
                    migrationDesignerPath = Path.Combine(
                        absoluteMigrationsDirectory,
                        scaffoldedMigration.MigrationId + ".resx");
                    migrationResourcesPath = Path.Combine(
                        absoluteMigrationsDirectory,
                        scaffoldedMigration.MigrationId + ".Designer." + scaffoldedMigration.Language);
                }

                Reporter.WriteData("{");
                Reporter.WriteData("  \"migrationsConfiguration\": " + Json.Literal(absolutePath) + ",");
                Reporter.WriteData("  \"migration\": " + Json.Literal(migrationPath) + ",");
                Reporter.WriteData("  \"migrationResources\": " + Json.Literal(migrationDesignerPath) + ",");
                Reporter.WriteData("  \"migrationDesigner\": " + Json.Literal(migrationResourcesPath));
                Reporter.WriteData("}");
            }

            return(base.Execute());
        }
Example #17
0
        protected override string GenerateCommandLineCommands()
        {
            var cmd = new CommandLineBuilder();

                        #if DEBUG
            cmd.AppendSwitch("/v");
                        #endif

            if (NoStdLib)
            {
                cmd.AppendSwitch("/nostdlib");
            }
            cmd.AppendSwitchIfNotNull("/compiler:", CompilerPath);
            cmd.AppendSwitchIfNotNull("/baselib:", BaseLibDll);
            cmd.AppendSwitchIfNotNull("/out:", OutputAssembly);

            if (NoStdLib)
            {
                string dir;
                if (!string.IsNullOrEmpty(BaseLibDll))
                {
                    dir = Path.GetDirectoryName(BaseLibDll);
                }
                else
                {
                    dir = null;
                }

                cmd.AppendSwitchIfNotNull("/lib:", dir);
                cmd.AppendSwitchIfNotNull("/r:", Path.Combine(dir, "mscorlib.dll"));
            }

            if (ProcessEnums)
            {
                cmd.AppendSwitch("/process-enums");
            }

            if (EmitDebugInformation)
            {
                cmd.AppendSwitch("/debug");
            }

            if (AllowUnsafeBlocks)
            {
                cmd.AppendSwitch("/unsafe");
            }

            cmd.AppendSwitchIfNotNull("/ns:", Namespace);

            if (!string.IsNullOrEmpty(DefineConstants))
            {
                var strv      = DefineConstants.Split(new [] { ';' });
                var sanitized = new List <string> ();

                foreach (var str in strv)
                {
                    if (str != string.Empty)
                    {
                        sanitized.Add(str);
                    }
                }

                if (sanitized.Count > 0)
                {
                    cmd.AppendSwitchIfNotNull("/d:", string.Join(";", sanitized.ToArray()));
                }
            }

            //cmd.AppendSwitch ("/e");

            foreach (var item in ApiDefinitions)
            {
                cmd.AppendFileNameIfNotNull(Path.GetFullPath(item.ItemSpec));
            }

            if (CoreSources != null)
            {
                foreach (var item in CoreSources)
                {
                    cmd.AppendSwitchIfNotNull("/s:", Path.GetFullPath(item.ItemSpec));
                }
            }

            if (Sources != null)
            {
                foreach (var item in Sources)
                {
                    cmd.AppendSwitchIfNotNull("/x:", Path.GetFullPath(item.ItemSpec));
                }
            }

            if (AdditionalLibPaths != null)
            {
                foreach (var item in AdditionalLibPaths)
                {
                    cmd.AppendSwitchIfNotNull("/lib:", Path.GetFullPath(item.ItemSpec));
                }
            }

            HandleReferences(cmd);

            if (Resources != null)
            {
                foreach (var item in Resources)
                {
                    var    args = new List <string> ();
                    string id;

                    args.Add(item.ToString());
                    id = item.GetMetadata("LogicalName");
                    if (!string.IsNullOrEmpty(id))
                    {
                        args.Add(id);
                    }

                    cmd.AppendSwitchIfNotNull("/res:", args.ToArray(), ",");
                }
            }

            if (NativeLibraries != null)
            {
                foreach (var item in NativeLibraries)
                {
                    var    args = new List <string> ();
                    string id;

                    args.Add(item.ToString());
                    id = item.GetMetadata("LogicalName");
                    if (string.IsNullOrEmpty(id))
                    {
                        id = Path.GetFileName(args[0]);
                    }
                    args.Add(id);

                    cmd.AppendSwitchIfNotNull("/link-with:", args.ToArray(), ",");
                }
            }

            if (GeneratedSourcesDir != null)
            {
                cmd.AppendSwitchIfNotNull("/tmpdir:", Path.GetFullPath(GeneratedSourcesDir));
            }

            if (GeneratedSourcesFileList != null)
            {
                cmd.AppendSwitchIfNotNull("/sourceonly:", Path.GetFullPath(GeneratedSourcesFileList));
            }

            cmd.AppendSwitch(GetTargetFrameworkArgument());

            if (!string.IsNullOrEmpty(ExtraArgs))
            {
                var    extraArgs = ProcessArgumentBuilder.Parse(ExtraArgs);
                var    target    = OutputAssembly;
                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 },
                    { "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];

                    cmd.AppendTextUnquoted(StringParserService.Parse(argument, customTags));
                }
            }

            return(cmd.ToString());
        }
Example #18
0
        protected override string GenerateCommandLineCommands()
        {
            var cmd = new CommandLineArgumentBuilder();

                        #if DEBUG
            cmd.Add("/v");
                        #endif

            cmd.Add("/nostdlib");
            cmd.AddQuotedSwitchIfNotNull("/baselib:", BaseLibDll);
            cmd.AddQuotedSwitchIfNotNull("/out:", OutputAssembly);

            cmd.AddQuotedSwitchIfNotNull("/attributelib:", AttributeAssembly);

            string dir;
            if (!string.IsNullOrEmpty(BaseLibDll))
            {
                dir = Path.GetDirectoryName(BaseLibDll);
                cmd.AddQuotedSwitchIfNotNull("/lib:", dir);
            }

            if (ProcessEnums)
            {
                cmd.Add("/process-enums");
            }

            if (EmitDebugInformation)
            {
                cmd.Add("/debug");
            }

            if (AllowUnsafeBlocks)
            {
                cmd.Add("/unsafe");
            }

            if (!string.IsNullOrEmpty(DotNetCscCompiler))
            {
                var compileCommand = new string [] {
                    DotNetPath,
                    DotNetCscCompiler,
                };
                cmd.AddQuoted("/compile-command:" + string.Join(" ", StringUtils.QuoteForProcess(compileCommand)));
            }

            cmd.AddQuotedSwitchIfNotNull("/ns:", Namespace);

            if (NoNFloatUsing)
            {
                cmd.Add("/no-nfloat-using:true");
            }

            if (!string.IsNullOrEmpty(DefineConstants))
            {
                var strv = DefineConstants.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var str in strv)
                {
                    cmd.AddQuoted("/d:" + str);
                }
            }

            //cmd.AppendSwitch ("/e");

            foreach (var item in ApiDefinitions)
            {
                cmd.AddQuoted(Path.GetFullPath(item.ItemSpec));
            }

            if (CoreSources != null)
            {
                foreach (var item in CoreSources)
                {
                    cmd.AddQuoted("/s:" + Path.GetFullPath(item.ItemSpec));
                }
            }

            if (Sources != null)
            {
                foreach (var item in Sources)
                {
                    cmd.AddQuoted("/x:" + Path.GetFullPath(item.ItemSpec));
                }
            }

            if (AdditionalLibPaths != null)
            {
                foreach (var item in AdditionalLibPaths)
                {
                    cmd.AddQuoted("/lib:" + Path.GetFullPath(item.ItemSpec));
                }
            }

            HandleReferences(cmd);

            if (Resources != null)
            {
                foreach (var item in Resources)
                {
                    var argument = item.ToString();
                    var id       = item.GetMetadata("LogicalName");
                    if (!string.IsNullOrEmpty(id))
                    {
                        argument += "," + id;
                    }

                    cmd.AddQuoted("/res:" + argument);
                }
            }

            if (NativeLibraries != null)
            {
                foreach (var item in NativeLibraries)
                {
                    var argument = item.ToString();
                    var id       = item.GetMetadata("LogicalName");
                    if (string.IsNullOrEmpty(id))
                    {
                        id = Path.GetFileName(argument);
                    }

                    cmd.AddQuoted("/res:" + argument + "," + id);
                }
            }

            if (GeneratedSourcesDir != null)
            {
                cmd.AddQuoted("/tmpdir:" + Path.GetFullPath(GeneratedSourcesDir));
            }

            if (GeneratedSourcesFileList != null)
            {
                cmd.AddQuoted("/sourceonly:" + Path.GetFullPath(GeneratedSourcesFileList));
            }

            cmd.Add($"/target-framework={TargetFrameworkMoniker}");

            if (!string.IsNullOrEmpty(ExtraArgs))
            {
                var    extraArgs = CommandLineArgumentBuilder.Parse(ExtraArgs);
                var    target    = OutputAssembly;
                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 },
                };
                // OutputAssembly is optional so it can be null
                if (target != null)
                {
                    var d = Path.GetDirectoryName(target);
                    var n = Path.GetFileName(target);
                    customTags.Add("targetpath", Path.Combine(d, n));
                    customTags.Add("targetdir", d);
                    customTags.Add("targetname", n);
                    customTags.Add("targetext", Path.GetExtension(target));
                }

                for (int i = 0; i < extraArgs.Length; i++)
                {
                    var argument = extraArgs[i];
                    cmd.Add(StringParserService.Parse(argument, customTags));
                }
            }

            cmd.Add(VerbosityUtils.Merge(ExtraArgs, (LoggerVerbosity)Verbosity));

            var commandLine = cmd.CreateResponseFile(this, ResponseFilePath, null);
            if (IsDotNet)
            {
                commandLine = StringUtils.Quote(Path.Combine(BTouchToolPath, BTouchToolExe)) + " " + commandLine;
            }

            return(commandLine.ToString());
        }
        protected override int Execute()
        {
            var scaffoldedMigration = CreateExecutor().Scaffold(
                _name.Value,
                ConnectionStringName.Value(),
                ConnectionString.Value(),
                ConnectionProvider.Value(),
                MigrationsConfig.Value(),
                _ignoreChanges.HasValue());

            Reporter.WriteInformation(
                string.Format(
                    !scaffoldedMigration.IsRescaffold
                        ? MyResources.ScaffoldingMigration
                        : MyResources.RescaffoldingMigration,
                    _name.Value));

            var userCodePath
                = WriteMigration(scaffoldedMigration, scaffoldedMigration.IsRescaffold, _force.HasValue(), _name.Value);

            if (!scaffoldedMigration.IsRescaffold)
            {
                Reporter.WriteWarning(string.Format(MyResources.SnapshotBehindWarning, _name.Value));

                var databaseMigrations
                    = CreateExecutor().GetDatabaseMigrations(
                          ConnectionStringName.Value(),
                          ConnectionString.Value(),
                          ConnectionProvider.Value(),
                          MigrationsConfig.Value())
                      .Take(2).ToList();

                var lastDatabaseMigration = databaseMigrations.FirstOrDefault();

                if ((lastDatabaseMigration != null) &&
                    string.Equals(lastDatabaseMigration.MigrationName(), _name.Value, StringComparison.Ordinal))
                {
                    var revertTargetMigration
                        = databaseMigrations.ElementAtOrDefault(1);

                    Reporter.WriteWarning(
                        string.Format(
                            MyResources.DidYouMeanToRescaffold,
                            _name.Value,
                            revertTargetMigration ?? "$InitialDatabase",
                            Path.GetFileName(userCodePath)));
                }
            }

            if (_json.HasValue())
            {
                string migrationPath          = null;
                string migrationDesignerPath  = null;
                string migrationResourcesPath = null;
                if (scaffoldedMigration != null)
                {
                    var absoluteMigrationsDirectory = Path.Combine(ProjectDir.Value(), scaffoldedMigration.Directory);

                    migrationPath = Path.Combine(
                        absoluteMigrationsDirectory,
                        scaffoldedMigration.MigrationId + "." + scaffoldedMigration.Language);
                    migrationDesignerPath = Path.Combine(
                        absoluteMigrationsDirectory,
                        scaffoldedMigration.MigrationId + ".resx");
                    migrationResourcesPath = Path.Combine(
                        absoluteMigrationsDirectory,
                        scaffoldedMigration.MigrationId + ".Designer." + scaffoldedMigration.Language);
                }

                Reporter.WriteData("{");
                Reporter.WriteData("  \"migration\": " + Json.Literal(migrationPath) + ",");
                Reporter.WriteData("  \"migrationResources\": " + Json.Literal(migrationDesignerPath) + ",");
                Reporter.WriteData("  \"migrationDesigner\": " + Json.Literal(migrationResourcesPath));
                Reporter.WriteData("}");
            }

            return(base.Execute());
        }
Example #20
0
        protected override string GenerateCommandLineCommands()
        {
            var           args          = GenerateCommandLineArguments();
            List <string> unescapedArgs = new List <string> ();

            TargetArchitecture architectures;

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

            if (architectures == TargetArchitecture.ARMv6)
            {
                Log.LogError(MSBStrings.E0053);
                return(null);
            }

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

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

            args.AddQuotedLine($"--executable={ExecutableName}");

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

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

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

            if (!string.IsNullOrEmpty(Interpreter))
            {
                args.AddLine($"--interpreter={Interpreter}");
            }

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

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

            args.AddQuotedLine($"--sdk={SdkVersion}");

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

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

            if (LinkDescriptions != null)
            {
                foreach (var desc in LinkDescriptions)
                {
                    args.AddQuotedLine($"--xml={desc.ItemSpec}");
                }
            }

            if (EnableBitcode)
            {
                switch (Platform)
                {
                case ApplePlatform.WatchOS:
                    args.AddLine("--bitcode=full");
                    break;

                case ApplePlatform.TVOS:
                    args.AddLine("--bitcode=asmonly");
                    break;

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

            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 (architectures.HasFlag(TargetArchitecture.ARM64_32))
                {
                    abi += (abi.Length > 0 ? "," : "") + "arm64_32" + llvm;
                }

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

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

            args.AddLine($"--abi={abi}");

            // output symbols to preserve when stripping
            args.AddQuotedLine($"--symbollist={Path.GetFullPath (SymbolsList)}");

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

            var gcc = new GccOptions();

            if (!string.IsNullOrEmpty(ExtraArgs))
            {
                var    extraArgs = CommandLineArgumentBuilder.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 = CommandLineArgumentBuilder.Parse(flags);

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

            BuildNativeReferenceFlags(gcc);
            BuildEntitlementFlags(gcc);

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

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

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

            if (gcc.Arguments.Length > 0)
            {
                unescapedArgs.Add($"--gcc_flags={gcc.Arguments.ToString ()}");
            }

            foreach (var asm in References)
            {
                if (IsFrameworkItem(asm))
                {
                    args.AddQuotedLine($"--reference={ResolveFrameworkFile (asm.ItemSpec)}");
                }
                else
                {
                    args.AddQuotedLine($"--reference={Path.GetFullPath (asm.ItemSpec)}");
                }
            }

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

            if (!string.IsNullOrWhiteSpace(License))
            {
                args.AddLine($"--license={License}");
            }

            return(CreateResponseFile(args, unescapedArgs));
        }
Example #21
0
        protected override string GenerateCommandLineCommands()
        {
            var           args          = new CommandLineArgumentBuilder();
            List <string> unescapedArgs = new List <string> ();

            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.AddQuotedLine($"--cache={Path.GetFullPath (IntermediateOutputPath)}");
            }

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

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

            args.AddQuotedLine($"--executable={ExecutableName}");

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

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

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

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

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

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

            if (!string.IsNullOrEmpty(Interpreter))
            {
                args.Add($"--interpreter={Interpreter}");
            }

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

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

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

            args.AddQuotedLine($"--sdkroot={SdkRoot}");

            args.AddQuotedLine($"--sdk={SdkVersion}");

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

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

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

            if (LinkDescriptions != null)
            {
                foreach (var desc in LinkDescriptions)
                {
                    args.AddQuotedLine($"--xml={desc.ItemSpec}");
                }
            }

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

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

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

            if (!string.IsNullOrEmpty(HttpClientHandler))
            {
                args.AddLine($"--http-message-handler={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.AddLine($"--abi={abi}");

            // output symbols to preserve when stripping
            args.AddQuotedLine($"--symbollist={Path.GetFullPath (SymbolsList)}");

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

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

            var gcc = new GccOptions();

            if (!string.IsNullOrEmpty(ExtraArgs))
            {
                var    extraArgs = CommandLineArgumentBuilder.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 = CommandLineArgumentBuilder.Parse(flags);

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

            BuildNativeReferenceFlags(gcc);
            BuildEntitlementFlags(gcc);

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

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

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

            if (gcc.Arguments.Length > 0)
            {
                unescapedArgs.Add($"--gcc_flags={gcc.Arguments.ToString ()}");
            }

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

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

            args.AddLine($"--target-framework={TargetFrameworkIdentifier},{TargetFrameworkVersion}");

            args.AddQuotedLine($"--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.AddLine(GetVerbosityLevel(Verbosity));
            }

            if (!string.IsNullOrWhiteSpace(License))
            {
                args.AddLine($"--license={License}");
            }

            // Generate a response file
            var responseFile = Path.GetFullPath(ResponseFilePath);

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

            try {
                using (var fs = File.Create(responseFile)) {
                    using (var writer = new StreamWriter(fs))
                        writer.Write(args);
                }
            } catch (Exception ex) {
                Log.LogWarning("Failed to create response file '{0}': {1}", responseFile, ex);
            }

            // Some arguments can not safely go in the response file and are
            // added separately. They must go _after_ the response file
            // as they may override options passed in the response file
            var actualArgs = new CommandLineArgumentBuilder();

            actualArgs.AddQuoted($"@{responseFile}");

            foreach (var arg in unescapedArgs)
            {
                actualArgs.AddQuoted(arg);
            }

            return(actualArgs.ToString());
        }