Example #1
0
        bool DoExecute()
        {
            var    abis       = SupportedAbis.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
            var    results    = new List <ITaskItem> ();
            string bundlepath = Path.Combine(TempOutputPath, "bundles");

            if (!Directory.Exists(bundlepath))
            {
                Directory.CreateDirectory(bundlepath);
            }
            else
            {
                Directory.Delete(bundlepath, true);
            }
            foreach (var abi in abis)
            {
                AndroidTargetArch arch = AndroidTargetArch.Other;
                switch (abi)
                {
                case "arm64":
                case "arm64-v8a":
                case "aarch64":
                    arch = AndroidTargetArch.Arm64;
                    break;

                case "armeabi-v7a":
                    arch = AndroidTargetArch.Arm;
                    break;

                case "x86":
                    arch = AndroidTargetArch.X86;
                    break;

                case "x86_64":
                    arch = AndroidTargetArch.X86_64;
                    break;

                case "mips":
                    arch = AndroidTargetArch.Mips;
                    break;
                }

                if (!NdkUtil.ValidateNdkPlatform(Log, AndroidNdkDirectory, arch, enableLLVM: false))
                {
                    return(false);
                }

                int level   = NdkUtil.GetMinimumApiLevelFor(arch, AndroidNdkDirectory);
                var outpath = Path.Combine(bundlepath, abi);
                if (!Directory.Exists(outpath))
                {
                    Directory.CreateDirectory(outpath);
                }

                var clb = new CommandLineBuilder();
                clb.AppendSwitch("--dos2unix=false");
                clb.AppendSwitch("--nomain");
                clb.AppendSwitch("--i18n none");
                clb.AppendSwitch("--bundled-header");
                clb.AppendSwitch("--mono-api-struct-path");
                clb.AppendFileNameIfNotNull(BundleApiPath);
                clb.AppendSwitch("--style");
                clb.AppendSwitch("linux");
                clb.AppendSwitch("-c");
                clb.AppendSwitch("-o");
                clb.AppendFileNameIfNotNull(Path.Combine(outpath, "temp.c"));
                clb.AppendSwitch("-oo");
                clb.AppendFileNameIfNotNull(Path.Combine(outpath, "assemblies.o"));
                if (AutoDeps)
                {
                    clb.AppendSwitch("--autodeps");
                }
                if (KeepTemp)
                {
                    clb.AppendSwitch("--keeptemp");
                }
                clb.AppendSwitch("-z");                  // Compress
                clb.AppendFileNamesIfNotNull(Assemblies, " ");
                var psi = new ProcessStartInfo()
                {
                    FileName               = MkbundlePath,
                    Arguments              = clb.ToString(),
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                };
                var gccNoQuotes = NdkUtil.GetNdkTool(AndroidNdkDirectory, arch, "gcc");
                var gcc         = '"' + gccNoQuotes + '"';
                var gas         = '"' + NdkUtil.GetNdkTool(AndroidNdkDirectory, arch, "as") + '"';
                psi.EnvironmentVariables ["CC"] = gcc;
                psi.EnvironmentVariables ["AS"] = gas;
                Log.LogDebugMessage("CC=" + gcc);
                Log.LogDebugMessage("AS=" + gas);
                //psi.EnvironmentVariables ["PKG_CONFIG_PATH"] = Path.Combine (Path.GetDirectoryName (MonoDroidSdk.MandroidTool), "lib", abi);
                Log.LogDebugMessage("[mkbundle] " + psi.FileName + " " + clb);
                var proc = new Process();
                proc.OutputDataReceived += OnMkbundleOutputData;
                proc.ErrorDataReceived  += OnMkbundleErrorData;
                proc.StartInfo           = psi;
                proc.Start();
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();
                if (proc.ExitCode != 0)
                {
                    Log.LogCodedError("XA5102", "Conversion from assembly to native code failed. Exit code {0}", proc.ExitCode);
                    return(false);
                }

                // then compile temp.c into temp.o and ...

                clb = new CommandLineBuilder();
                clb.AppendSwitch("-c");

                // This is necessary only when unified headers are in use but it won't hurt to have it
                // defined even if we don't use them
                clb.AppendSwitch($"-D__ANDROID_API__={level}");

                // This is necessary because of the injected code, which is reused between libmonodroid
                // and the bundle
                clb.AppendSwitch("-DANDROID");

                clb.AppendSwitch("-o");
                clb.AppendFileNameIfNotNull(Path.Combine(outpath, "temp.o"));
                if (!string.IsNullOrWhiteSpace(IncludePath))
                {
                    clb.AppendSwitch("-I");
                    clb.AppendFileNameIfNotNull(IncludePath);
                }

                string asmIncludePath = NdkUtil.GetNdkAsmIncludePath(AndroidNdkDirectory, arch, level);
                if (!String.IsNullOrEmpty(asmIncludePath))
                {
                    clb.AppendSwitch("-I");
                    clb.AppendFileNameIfNotNull(asmIncludePath);
                }

                clb.AppendSwitch("-I");
                clb.AppendFileNameIfNotNull(NdkUtil.GetNdkPlatformIncludePath(AndroidNdkDirectory, arch, level));
                clb.AppendFileNameIfNotNull(Path.Combine(outpath, "temp.c"));
                Log.LogDebugMessage("[CC] " + gcc + " " + clb);
                if (MonoAndroidHelper.RunProcess(gccNoQuotes, clb.ToString(), OnCcOutputData, OnCcErrorData) != 0)
                {
                    Log.LogCodedError("XA5103", "NDK C compiler resulted in an error. Exit code {0}", proc.ExitCode);
                    return(false);
                }

                // ... link temp.o and assemblies.o into app.so

                clb = new CommandLineBuilder();
                clb.AppendSwitch("--shared");
                clb.AppendFileNameIfNotNull(Path.Combine(outpath, "temp.o"));
                clb.AppendFileNameIfNotNull(Path.Combine(outpath, "assemblies.o"));
                clb.AppendSwitch("-o");
                clb.AppendFileNameIfNotNull(Path.Combine(outpath, "libmonodroid_bundle_app.so"));
                clb.AppendSwitch("-L");
                clb.AppendFileNameIfNotNull(NdkUtil.GetNdkPlatformLibPath(AndroidNdkDirectory, arch, level));
                clb.AppendSwitch("-lc");
                clb.AppendSwitch("-lm");
                clb.AppendSwitch("-ldl");
                clb.AppendSwitch("-llog");
                clb.AppendSwitch("-lz");                  // Compress
                string ld = NdkUtil.GetNdkTool(AndroidNdkDirectory, arch, "ld");
                Log.LogMessage(MessageImportance.Normal, "[LD] " + ld + " " + clb);
                if (MonoAndroidHelper.RunProcess(ld, clb.ToString(), OnLdOutputData, OnLdErrorData) != 0)
                {
                    Log.LogCodedError("XA5201", "NDK Linker resulted in an error. Exit code {0}", proc.ExitCode);
                    return(false);
                }
                results.Add(new TaskItem(Path.Combine(outpath, "libmonodroid_bundle_app.so")));
            }
            OutputNativeLibraries = results.ToArray();
            return(true);
        }
Example #2
0
 /// <summary>
 /// Generates the SvnAdmin command.
 /// </summary>
 /// <returns></returns>
 protected virtual void AppendCommand(CommandLineBuilder commandLine)
 {
     commandLine.AppendSwitch(Command);
     commandLine.AppendFileNameIfNotNull(RepositoryPath);
 }
Example #3
0
 /// <summary>
 /// Generates the command line arguments.
 /// </summary>
 /// <returns>
 /// Returns a string value containing the command line arguments to pass directly to the executable file.
 /// </returns>
 protected override void AppendCommand(CommandLineBuilder commandLine)
 {
     base.AppendCommand(commandLine);
     commandLine.AppendFileNameIfNotNull(BackupPath);
 }
Example #4
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 = 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 },
                    { "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 #5
0
 /// <summary>
 /// Generates the svn command.
 /// </summary>
 /// <returns></returns>
 protected virtual void AppendCommand(CommandLineBuilder commandLine)
 {
     commandLine.AppendSwitch(Command);
     
     // import has paths in diff order
     if (Command == Commands.Import)
     {
         commandLine.AppendFileNameIfNotNull(LocalPath); 
         commandLine.AppendFileNameIfNotNull(RepositoryPath);
     }
     else
     {
         commandLine.AppendFileNameIfNotNull(RepositoryPath);
         commandLine.AppendFileNameIfNotNull(LocalPath);                
     }
     
 }
Example #6
0
        protected override string GenerateCommandLineCommands()
        {
            //   Running command: C:\Program Files (x86)\Java\jdk1.6.0_20\bin\java.exe
            //     "-jar" "C:\Program Files (x86)\Android\android-sdk-windows\platform-tools\jill.jar"
            //     "--output-dex" "bin\classes"
            //     "-classpath" "C:\Users\Jonathan\Documents\Visual Studio 2010\Projects\AndroidMSBuildTest\AndroidMSBuildTest\obj\Debug\android\bin\mono.android.jar"
            //     "@C:\Users\Jonathan\AppData\Local\Temp\tmp79c4ac38.tmp"

            //var android_dir = MonoDroid.MonoDroidSdk.GetAndroidProfileDirectory (TargetFrameworkDirectory);

            var doc           = AndroidAppManifest.Load(ManifestFile, MonoAndroidHelper.SupportedVersions);
            int minApiVersion = doc.MinSdkVersion == null ? 4 : (int)doc.MinSdkVersion;

            var cmd = new CommandLineBuilder();

            // Add the JavaOptions if they are not null
            // These could be any of the additional options
            if (!string.IsNullOrEmpty(JavaOptions))
            {
                cmd.AppendSwitch(JavaOptions);
            }

            // Add the specific -XmxN to override the default heap size for the JVM
            // N can be in the form of Nm or NGB (e.g 100m or 1GB )
            cmd.AppendSwitchIfNotNull("-Xmx", JavaMaximumHeapSize);

            cmd.AppendSwitchIfNotNull("-jar ", DesugarJarPath);

            cmd.AppendSwitch("--bootclasspath_entry ");
            cmd.AppendFileNameIfNotNull(JavaPlatformJarPath);

            cmd.AppendSwitch("--min_sdk_version ");
            cmd.AppendSwitch(minApiVersion.ToString());

            if (minApiVersion < 24)
            {
                cmd.AppendSwitch("--desugar_try_with_resources_omit_runtime_classes ");
            }

            //cmd.AppendSwitchIfNotNull ("-J-Dfile.encoding=", "UTF8");

            if (!string.IsNullOrEmpty(DesugarExtraArguments))
            {
                cmd.AppendSwitch(DesugarExtraArguments);                  // it should contain "--dex".
            }
            var outputs = new List <string> ();
            var md5     = System.Security.Cryptography.MD5.Create();

            foreach (var jar in InputJars)
            {
                var output = Path.Combine(OutputDirectory, BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(jar))) + Path.GetFileName(jar));
                outputs.Add(output);
                cmd.AppendSwitch("--classpath_entry ");
                cmd.AppendFileNameIfNotNull(jar);
                cmd.AppendSwitch("--input ");
                cmd.AppendFileNameIfNotNull(jar);
                cmd.AppendSwitch("--output ");
                cmd.AppendFileNameIfNotNull(output);
            }

            OutputJars = outputs.ToArray();

            return(cmd.ToString());
        }
Example #7
0
        /// <summary>
        /// Returns a string value containing the command line arguments to pass directly to the executable file.
        /// </summary>
        /// <returns>
        /// A string value containing the command line arguments to pass directly to the executable file.
        /// </returns>
        protected override string GenerateCommandLineCommands()
        {
            CommandLineBuilder builder = new CommandLineBuilder();

            builder.AppendFileNameIfNotNull(_sourceFolder);
            builder.AppendFileNameIfNotNull(_destinationFolder);
            builder.AppendFileNamesIfNotNull(_sourceFiles, " ");

            if (_subdirectories)
            {
                builder.AppendSwitch("/S");
            }
            if (_allSubdirectories)
            {
                builder.AppendSwitch("/E");
            }
            if (_restartableMode)
            {
                builder.AppendSwitch("/Z");
            }
            if (_backupMode)
            {
                builder.AppendSwitch("/B");
            }
            builder.AppendSwitchIfNotNull("/COPY:", _copyFlags);
            if (_copyAll)
            {
                builder.AppendSwitch("/COPYALL");
            }
            if (_noCopy)
            {
                builder.AppendSwitch("/NOCOPY");
            }
            if (_security)
            {
                builder.AppendSwitch("/SEC");
            }
            if (_moveFiles)
            {
                builder.AppendSwitch("/MOV");
            }
            if (_move)
            {
                builder.AppendSwitch("/move");
            }
            if (_purge)
            {
                builder.AppendSwitch("/PURGE");
            }
            if (_mirror)
            {
                builder.AppendSwitch("/MIR");
            }
            if (_noCopy)
            {
                builder.AppendSwitch("/NOCOPY");
            }
            if (_create)
            {
                builder.AppendSwitch("/CREATE");
            }
            if (_fatFileNames)
            {
                builder.AppendSwitch("/FAT");
            }
            if (_fatFileTimes)
            {
                builder.AppendSwitch("/FFT");
            }
            builder.AppendSwitchIfNotNull("/IA:", _includeAttributes);
            builder.AppendSwitchIfNotNull("/XA:", _excluedAttributes);
            if (_includeArchive)
            {
                builder.AppendSwitch("/A");
            }
            if (_includeArchiveClear)
            {
                builder.AppendSwitch("/M");
            }
            if (_excludeJunctions)
            {
                builder.AppendSwitch("/XJ");
            }

            builder.AppendSwitchIfNotNull("/XF ", _excludeFiles, " ");
            builder.AppendSwitchIfNotNull("/XD ", _excludeFolders, " ");

            if (_verbose)
            {
                builder.AppendSwitch("/V");
            }
            if (_noFileLogging)
            {
                builder.AppendSwitch("/NFL");
            }
            if (_noFolderLogging)
            {
                builder.AppendSwitch("/NDL");
            }
            if (_noJobHeader)
            {
                builder.AppendSwitch("/NJH");
            }
            if (_noJobSummary)
            {
                builder.AppendSwitch("/NJS");
            }
            if (_noProgress)
            {
                builder.AppendSwitch("/NP");
            }

            builder.AppendSwitchIfNotNull("/LOG:", _logFile);
            builder.AppendSwitchIfNotNull("/LOG+:", _appendLogFile);
            builder.AppendSwitchIfNotNull("", _options, " ");

            return(builder.ToString());
        }
        protected override string GenerateCommandLineCommands()
        {
            var builder = new CommandLineBuilder();

            builder.AppendSwitch("/nologo");
            builder.AppendSwitch("/quiet");

            builder.AppendFileNameIfNotNull(Source);
            if (Resource != null)
            {
                builder.AppendSwitch("/resource=\"" + Resource + "\"");
            }

            if (Output != null)
            {
                builder.AppendSwitch("/output=\"" + Output + "\"");
            }
            if (string.Compare(OutputType, "library", true) == 0 ||
                (string.IsNullOrEmpty(OutputType) && Output != null && !".exe".Equals(Path.GetExtension(Output), StringComparison.InvariantCultureIgnoreCase)))
            {
                builder.AppendSwitch("/dll");
            }

            if (NoAutoInherit)
            {
                builder.AppendSwitch("/noautoinherit");
            }
            if (CreatePdb)
            {
                builder.AppendSwitch("/pdb");
            }
            if (Optimize)
            {
                builder.AppendSwitch("/optimize");
            }
            if (Fold)
            {
                builder.AppendSwitch("/fold");
            }
            if (NoCorStub)
            {
                builder.AppendSwitch("/nocorstub");
            }
            if (StripReloc)
            {
                builder.AppendSwitch("/stripreloc");
            }

            if (!string.IsNullOrEmpty(Debug))
            {
                try
                {
                    var debug = Convert.ToBoolean(Debug);
                    if (debug)
                    {
                        builder.AppendSwitch("/debug");
                    }
                }
                catch
                {
                    builder.AppendSwitch("/debug=" + Debug.ToLower());
                }
            }
            if (Key != null)
            {
                builder.AppendSwitch("/key=" + Key);
            }
            if (Include != null)
            {
                builder.AppendSwitch("/include=" + Include);
            }
            if (MDV != null)
            {
                builder.AppendSwitch("/mdv=" + MDV);
            }
            if (MSV != null)
            {
                builder.AppendSwitch("/msv=" + MSV);
            }
            if (string.Compare(Platform, "x64") == 0)
            {
                builder.AppendSwitch("/x64");
            }
            if (string.Compare(Platform, "itanium") == 0)
            {
                builder.AppendSwitch("/itanium");
            }

            if (Subsystem != 0)
            {
                builder.AppendSwitch("/subsystem=" + Subsystem);
            }
            if (Flags != 0)
            {
                builder.AppendSwitch("/flags=" + Flags);
            }
            if (Alignment != 0)
            {
                builder.AppendSwitch("/alignment=" + Alignment);
            }
            if (Base != 0)
            {
                builder.AppendSwitch("/base=" + Base);
            }
            if (Stack != 0)
            {
                builder.AppendSwitch("/stack=" + Stack);
            }

            Log.LogMessage(MessageImportance.High, "Assembling {0}...", Source);
            return(builder.ToString());
        }
Example #9
0
        protected virtual CommandLineBuilder GetCommandLineBuilder()
        {
            var cmd = new CommandLineBuilder();

            if (!string.IsNullOrEmpty(JavaOptions))
            {
                cmd.AppendSwitch(JavaOptions);
            }
            cmd.AppendSwitchIfNotNull("-Xmx", JavaMaximumHeapSize);
            cmd.AppendSwitchIfNotNull("-jar ", JarPath);

            if (!string.IsNullOrEmpty(ExtraArguments))
            {
                cmd.AppendSwitch(ExtraArguments);                  // it should contain "--dex".
            }
            if (Debug)
            {
                cmd.AppendSwitch("--debug");
            }
            else
            {
                cmd.AppendSwitch("--release");
            }

            //NOTE: if this is blank, we can omit --min-api in this call
            if (!string.IsNullOrEmpty(AndroidManifestFile))
            {
                var doc           = AndroidAppManifest.Load(AndroidManifestFile, MonoAndroidHelper.SupportedVersions);
                int minApiVersion = doc.MinSdkVersion == null ? 4 : (int)doc.MinSdkVersion;
                cmd.AppendSwitchIfNotNull("--min-api ", minApiVersion.ToString());
            }

            if (!EnableDesugar)
            {
                cmd.AppendSwitch("--no-desugaring");
            }

            var injars  = new List <string> ();
            var libjars = new List <string> ();

            if (AlternativeJarLibrariesToEmbed?.Length > 0)
            {
                Log.LogDebugMessage("  processing AlternativeJarLibrariesToEmbed...");
                foreach (var jar in AlternativeJarLibrariesToEmbed)
                {
                    injars.Add(jar.ItemSpec);
                }
            }
            else if (JavaLibrariesToEmbed != null)
            {
                Log.LogDebugMessage("  processing ClassesZip, JavaLibrariesToEmbed...");
                if (File.Exists(ClassesZip))
                {
                    injars.Add(ClassesZip);
                }
                foreach (var jar in JavaLibrariesToEmbed)
                {
                    injars.Add(jar.ItemSpec);
                }
            }
            libjars.Add(JavaPlatformJarPath);
            if (JavaLibrariesToReference != null)
            {
                foreach (var jar in JavaLibrariesToReference)
                {
                    libjars.Add(jar.ItemSpec);
                }
            }

            cmd.AppendSwitchIfNotNull("--output ", OutputDirectory);
            foreach (var jar in libjars)
            {
                cmd.AppendSwitchIfNotNull("--lib ", jar);
            }
            foreach (var jar in injars)
            {
                cmd.AppendFileNameIfNotNull(jar);
            }

            return(cmd);
        }
Example #10
0
        private static unsafe CommandLineBuilder Init_MakeConEmuCommandLine([NotNull] ConEmuStartInfo startinfo, [NotNull] HostContext hostcontext, [CanBeNull] AnsiLog ansilog, [NotNull] DirectoryInfo dirLocalTempRoot)
        {
            if (startinfo == null)
            {
                throw new ArgumentNullException(nameof(startinfo));
            }
            if (hostcontext == null)
            {
                throw new ArgumentNullException(nameof(hostcontext));
            }

            var cmdl = new CommandLineBuilder();

            // This sets up hosting of ConEmu in our control
            cmdl.AppendSwitch("-InsideWnd");
            cmdl.AppendFileNameIfNotNull("0x" + ((ulong)hostcontext.HWndParent).ToString("X"));

            // Don't use keyboard hooks in ConEmu when embedded
            cmdl.AppendSwitch("-NoKeyHooks");

            // Basic settings, like fonts and hidden tab bar
            // Plus some of the properties on this class
            cmdl.AppendSwitch("-LoadCfgFile");
            cmdl.AppendFileNameIfNotNull(Init_MakeConEmuCommandLine_EmitConfigFile(dirLocalTempRoot, startinfo, hostcontext));

            if (!string.IsNullOrEmpty(startinfo.StartupDirectory))
            {
                cmdl.AppendSwitch("-Dir");
                cmdl.AppendFileNameIfNotNull(startinfo.StartupDirectory);
            }

            // ANSI Log file
            if (ansilog != null)
            {
                cmdl.AppendSwitch("-AnsiLog");
                cmdl.AppendFileNameIfNotNull(ansilog.Directory.FullName);
            }
            if (dirLocalTempRoot == null)
            {
                throw new ArgumentNullException(nameof(dirLocalTempRoot));
            }

            // This one MUST be the last switch
            cmdl.AppendSwitch("-cmd");

            // Console mode command
            // NOTE: if placed AFTER the payload command line, otherwise somehow conemu hooks won't fetch the switch out of the cmdline, e.g. with some complicated git fetch/push cmdline syntax which has a lot of colons inside on itself
            string sConsoleExitMode;

            switch (startinfo.WhenConsoleProcessExits)
            {
            case WhenConsoleProcessExits.CloseConsoleEmulator:
                sConsoleExitMode = "n";
                break;

            case WhenConsoleProcessExits.KeepConsoleEmulator:
                sConsoleExitMode = "c0";
                break;

            case WhenConsoleProcessExits.KeepConsoleEmulatorAndShowMessage:
                sConsoleExitMode = "c";
                break;

            default:
                throw new ArgumentOutOfRangeException("ConEmuStartInfo" + "::" + "WhenConsoleProcessExits", startinfo.WhenConsoleProcessExits, "This is not a valid enum value.");
            }
            cmdl.AppendSwitchIfNotNull("-cur_console:", $"{(startinfo.IsElevated ? "a" : "")}{sConsoleExitMode}");

            // And the shell command line itself
            cmdl.AppendSwitch(startinfo.ConsoleProcessCommandLine);

            return(cmdl);
        }
Example #11
0
        /// <summary>
        /// Launches Visual Studio.
        /// </summary>
        /// <param name="arguments">The current <see cref="ProgramArguments" />.</param>
        /// <param name="visualStudioInstance">A <see cref="VisualStudioInstance" /> object representing which instance of Visual Studio to launch.</param>
        /// <param name="solutionFileFullPath">The full path to the solution file.</param>
        /// <param name="logger">A <see cref="ISlnGenLogger" /> to use for logging.</param>
        /// <returns>true if Visual Studio was launched, otherwise false.</returns>
        public static bool TryLaunch(ProgramArguments arguments, VisualStudioInstance visualStudioInstance, string solutionFileFullPath, ISlnGenLogger logger)
        {
            if (!arguments.ShouldLaunchVisualStudio())
            {
                return(true);
            }

            if (!Utility.RunningOnWindows)
            {
                logger.LogWarning("Launching Visual Studio is not currently supported on your operating system.");

                return(true);
            }

            string devEnvFullPath = arguments.GetDevEnvFullPath(visualStudioInstance);

            if (!devEnvFullPath.IsNullOrWhiteSpace())
            {
                visualStudioInstance = VisualStudioConfiguration.GetInstanceForPath(devEnvFullPath);
            }

            if (visualStudioInstance == null)
            {
                logger.LogError(
                    Program.CurrentDevelopmentEnvironment.IsCorext
                        ? $"Could not find a Visual Studio {Environment.GetEnvironmentVariable("VisualStudioVersion")} installation.  Please do one of the following:\n a) Specify a full path to devenv.exe via the -vs command-line argument\n b) Update your corext.config to specify a version of MSBuild.Corext that matches a Visual Studio version you have installed\n c) Install a version of Visual Studio that matches the version of MSBuild.Corext in your corext.config"
                        : "Could not find a Visual Studio installation.  Please run from a command window that has MSBuild.exe on the PATH or specify the full path to devenv.exe via the -vs command-line argument");

                return(false);
            }

            if (visualStudioInstance.IsBuildTools)
            {
                logger.LogError("Cannot use a BuildTools instance of Visual Studio.");

                return(false);
            }

            if (!File.Exists(devEnvFullPath))
            {
                logger.LogError($"The specified path to Visual Studio ({devEnvFullPath}) does not exist or is inaccessible.");

                return(false);
            }

            CommandLineBuilder commandLineBuilder = new CommandLineBuilder();

            commandLineBuilder.AppendFileNameIfNotNull(solutionFileFullPath);

            if (!arguments.ShouldLoadProjectsInVisualStudio())
            {
                commandLineBuilder.AppendSwitch(DoNotLoadProjectsCommandLineArgument);
            }

            try
            {
                Process process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName        = devEnvFullPath,
                        Arguments       = commandLineBuilder.ToString(),
                        UseShellExecute = false,
                    },
                };

                logger.LogMessageHigh("Launching Visual Studio...");
                logger.LogMessageLow("  FileName = {0}", process.StartInfo.FileName);
                logger.LogMessageLow("  Arguments = {0}", process.StartInfo.Arguments);

                if (!process.Start())
                {
                    logger.LogError("Failed to launch Visual Studio.");
                }
            }
            catch (Exception e)
            {
                logger.LogError($"Failed to launch Visual Studio. {e.Message}");
            }

            return(true);
        }
Example #12
0
 private void AppendScriptCommands(CommandLineBuilder builder)
 {
     builder.AppendSwitch("script");
     builder.AppendFileNameIfNotNull(_output);
     builder.AppendSwitch("-f");
 }
        internal static string GenerateCompilerCommandLine(
            string outputFolder, ITaskItem[] references, ITaskItem[] sources, bool emitDebugInformation,
            string[] disabledWarnings)
        {
            var builder = new CommandLineBuilder();

            #region javac <options> <source files>

            /* where possible options include:
             * -g                         Generate all debugging info
             * -g:none                    Generate no debugging info
             * -g:{lines,vars,source}     Generate only some debugging info
             * -nowarn                    Generate no warnings
             * -verbose                   Output messages about what the compiler is doing
             * -deprecation               Output source locations where deprecated APIs are used
             * -classpath <path>          Specify where to find user class files and annotation processors
             * -cp <path>                 Specify where to find user class files and annotation processors
             * -sourcepath <path>         Specify where to find input source files
             * -bootclasspath <path>      Override location of bootstrap class files
             * -extdirs <dirs>            Override location of installed extensions
             * -endorseddirs <dirs>       Override location of endorsed standards path
             * -proc:{none,only}          Control whether annotation processing and/or compilation is done.
             * -processor <class1>[,<class2>,<class3>...]Names of the annotation processors to run; bypasses default discovery process
             * -processorpath <path>      Specify where to find annotation processors
             * -d <directory>             Specify where to place generated class files
             * -s <directory>             Specify where to place generated source files
             * -implicit:{none,class}     Specify whether or not to generate class files for implicitly referenced files
             * -encoding <encoding>       Specify character encoding used by source files
             * -source <release>          Provide source compatibility with specified release
             * -target <release>          Generate class files for specific VM version
             * -version                   Version information
             * -help                      Print a synopsis of standard options
             * -Akey[=value]              Options to pass to annotation processors
             * -X                         Print a synopsis of nonstandard options
             * -J<flag>                   Pass <flag> directly to the runtime system */
            #endregion

            #region Debugging information
            if (emitDebugInformation)
            {
                builder.AppendSwitch("-g");
            }
            else
            {
                builder.AppendSwitch("-g:none");
            }
            #endregion

            builder.AppendSwitch("-d");
            builder.AppendFileNameIfNotNull(outputFolder);

            builder.AppendSwitch("-Xlint:all");
            if (disabledWarnings != null)
            {
                foreach (string warning in disabledWarnings)
                {
                    builder.AppendSwitch("-Xlint:-" + warning);
                }
            }

            #region Project references built into a classpath
            if (references != null)
            {
                builder.AppendSwitch("-classpath");
                builder.AppendSwitch('"' + references.Join(";", (item) => item.GetMetadata("HintPath")) + '"');
            }
            #endregion

            builder.AppendFileNamesIfNotNull(sources, " ");

            var result = builder.ToString();
            return(result);
        }
        /// <summary>
        /// Gets the MSBuild command-line based on the current properties of this object.
        /// </summary>
        /// <param name="useShortSwitchNames"><code>true</code> to use short command-line argument switches like '/nr' instead of '/NodeReuse', otherwise <code>false</code>.</param>
        /// <returns></returns>
        public string ToString(bool useShortSwitchNames)
        {
            CommandLineBuilder commandLineBuilder = new CommandLineBuilder();

            commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "t" : "Target")}:", Targets);

            commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "p" : "Property")}:", Properties);

            commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "m" : "MaxCpuCount")}:", MaxCpuCount, minValue: 1);

            commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "tv" : "ToolsVersion")}:", ToolsVersion);

            commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "v" : "Verbosity")}:", Verbosity);

            commandLineBuilder.AppendSwitchIfNotNullOrEmpty($"/{(useShortSwitchNames ? "val" : "Validate")}:", Validate);

            commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "ignore" : "IgnoreProjectExtensions")}:", IgnoreProjectExtensions);

            if (ConsoleLoggerParameters != null)
            {
                commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "clp" : "ConsoleLoggerParameters")}:", ConsoleLoggerParameters.ToString(useShortSwitchNames));
            }

            commandLineBuilder.AppendSwitchIfTrue($"/{(useShortSwitchNames ? "dfl" : "DistributedFileLogger")}", DistributedFileLogger);

            foreach (MSBuildLoggerParameters logger in Loggers)
            {
                commandLineBuilder.AppendSwitch($"\"/{(useShortSwitchNames ? "l" : "Logger")}:{logger}\"");
            }

            commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "nr" : "NodeReuse")}:", NodeReuse);

            commandLineBuilder.AppendSwitchIfTrue($"/{(useShortSwitchNames ? "noconlog" : "NoConsoleLogger")}", NoConsoleLogger);

            for (int i = 0; i < FileLoggers.Count; i++)
            {
                string index = FileLoggers.Count > 1 ? i.ToString() : String.Empty;

                commandLineBuilder.AppendSwitch($"/{(useShortSwitchNames ? "fl" : "FileLogger")}{index}");

                commandLineBuilder.AppendSwitchIfNotNull($"/{(useShortSwitchNames ? "flp" : "FileLoggerParameters")}{index}:", FileLoggers[i].ToString(useShortSwitchNames));
            }

            foreach (MSBuildDistributedLoggerParameters distributedLogger in DistributedLoggers)
            {
                commandLineBuilder.AppendSwitch($"\"/{(useShortSwitchNames ? "dl" : "DistributedLogger")}:{distributedLogger}\"");
            }

            if (BinaryLogger != null)
            {
                commandLineBuilder.AppendSwitch($"/{(useShortSwitchNames ? "bl" : "BinaryLogger")}{BinaryLogger}");
            }

            commandLineBuilder.AppendSwitchIfNotNullOrEmpty($"/{(useShortSwitchNames ? "pp" : "PreProcess")}:", PreProcess);

            commandLineBuilder.AppendSwitchIfTrue($"/{(useShortSwitchNames ? "ds" : "DetailedSummary")}", DetailedSummary);

            commandLineBuilder.AppendSwitchIfTrue($"/{(useShortSwitchNames ? "noautorsp" : "NoAutoResponse")}", NoAutoResponse);

            commandLineBuilder.AppendSwitchIfTrue("/NoLogo", NoLogo);

            commandLineBuilder.AppendSwitchIfTrue($"/{(useShortSwitchNames ? "ver" : "Version")}", Version);

            foreach (string responseFile in ResponseFiles.Where(i => !String.IsNullOrWhiteSpace(i)))
            {
                commandLineBuilder.AppendSwitch("@");
                commandLineBuilder.AppendTextUnquoted($"\"{responseFile}\"");
            }

            commandLineBuilder.AppendFileNameIfNotNull(Project);

            return(commandLineBuilder.ToString());
        }
Example #15
0
        /// <summary>
        /// Launches Visual Studio.
        /// </summary>
        /// <param name="arguments">The current <see cref="ProgramArguments" />.</param>
        /// <param name="visualStudioInstance">A <see cref="VisualStudioInstance" /> object representing which instance of Visual Studio to launch.</param>
        /// <param name="solutionFileFullPath">The full path to the solution file.</param>
        /// <param name="logger">A <see cref="ISlnGenLogger" /> to use for logging.</param>
        /// <returns>true if Visual Studio was launched, otherwise false.</returns>
        public static bool TryLaunch(ProgramArguments arguments, VisualStudioInstance visualStudioInstance, string solutionFileFullPath, ISlnGenLogger logger)
        {
            if (!arguments.ShouldLaunchVisualStudio())
            {
                return(true);
            }

            bool loadProjectsInVisualStudio = arguments.ShouldLoadProjectsInVisualStudio();
            bool enableShellExecute         = arguments.EnableShellExecute();

            string devEnvFullPath = arguments.DevEnvFullPath?.LastOrDefault();

            if (!enableShellExecute || !loadProjectsInVisualStudio || Program.IsCorext)
            {
                if (devEnvFullPath.IsNullOrWhiteSpace())
                {
                    if (visualStudioInstance == null)
                    {
                        logger.LogError(
                            Program.IsCorext
                                ? $"Could not find a Visual Studio {Environment.GetEnvironmentVariable("VisualStudioVersion")} installation.  Please do one of the following:\n a) Specify a full path to devenv.exe via the -vs command-line argument\n b) Update your corext.config to specify a version of MSBuild.Corext that matches a Visual Studio version you have installed\n c) Install a version of Visual Studio that matches the version of MSBuild.Corext in your corext.config"
                                : "Could not find a Visual Studio installation.  Please specify the full path to devenv.exe via the -vs command-line argument");

                        return(false);
                    }

                    if (visualStudioInstance.IsBuildTools)
                    {
                        logger.LogError("Cannot use a BuildTools instance of Visual Studio.");

                        return(false);
                    }

                    devEnvFullPath = Path.Combine(visualStudioInstance.InstallationPath, "Common7", "IDE", "devenv.exe");
                }
            }

            if (solutionFileFullPath.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException(nameof(solutionFileFullPath));
            }

            CommandLineBuilder commandLineBuilder = new CommandLineBuilder();

            ProcessStartInfo processStartInfo;

            if (!devEnvFullPath.IsNullOrWhiteSpace())
            {
                if (!File.Exists(devEnvFullPath))
                {
                    logger.LogError($"The specified path to Visual Studio ({devEnvFullPath}) does not exist or is inaccessible.");

                    return(false);
                }

                processStartInfo = new ProcessStartInfo
                {
                    FileName        = devEnvFullPath !,
                    UseShellExecute = false,
                };

                commandLineBuilder.AppendFileNameIfNotNull(solutionFileFullPath);

                if (!arguments.ShouldLoadProjectsInVisualStudio())
                {
                    commandLineBuilder.AppendSwitch(DoNotLoadProjectsCommandLineArgument);
                }
            }
            else
            {
                processStartInfo = new ProcessStartInfo
                {
                    FileName        = solutionFileFullPath,
                    UseShellExecute = true,
                };
            }

            try
            {
                processStartInfo.Arguments = commandLineBuilder.ToString();

                Process process = new Process
                {
                    StartInfo = processStartInfo,
                };

                logger.LogMessageHigh("Launching Visual Studio...");
                logger.LogMessageLow("  FileName = {0}", processStartInfo.FileName);
                logger.LogMessageLow("  Arguments = {0}", processStartInfo.Arguments);
                logger.LogMessageLow("  UseShellExecute = {0}", processStartInfo.UseShellExecute);
                logger.LogMessageLow("  WindowStyle = {0}", processStartInfo.WindowStyle);

                if (!process.Start())
                {
                    logger.LogError("Failed to launch Visual Studio.");
                }
            }
            catch (Exception e)
            {
                logger.LogError($"Failed to launch Visual Studio. {e.Message}");
            }

            return(true);
        }