예제 #1
0
        public void Split()
        {
            var apeToWavCmd = new CommandLineRunner(BuildApeToWavArgs(out _tempWavPath));

            apeToWavCmd.Run();

            if (apeToWavCmd.ExitCode != 0)
            {
                throw new CommandLineOperationException(apeToWavCmd.StandardError, apeToWavCmd.ExitCode);
            }

            var wavToFlacCmd = new CommandLineRunner(BuildWavToFlacCmd(_tempWavPath, out _tempFlacPath));

            wavToFlacCmd.Run();

            if (wavToFlacCmd.ExitCode != 0)
            {
                throw new CommandLineOperationException(wavToFlacCmd.StandardError, wavToFlacCmd.ExitCode);
            }

            string orig = _cueSheet.Files[0].FileName;

            _cueSheet.Files[0].FileName = _tempFlacPath;

            var splitter = _factory.Build();

            splitter.Split();

            _cueSheet.Files[0].FileName = orig;

            _results = splitter.Results;
        }
예제 #2
0
        /// <summary>
        /// Merge the specified input files into the specified output file. Returns null if successful,
        /// a string that may be useful in debugging if not.
        /// </summary>
        public static string MergeAudioFiles(IEnumerable <string> mergeFiles, string combinedAudioPath)
        {
            var ffmpeg = "/usr/bin/ffmpeg";             // standard Linux location

            if (SIL.PlatformUtilities.Platform.IsWindows)
            {
                ffmpeg = Path.Combine(BloomFileLocator.GetCodeBaseFolder(), "ffmpeg.exe");
            }
            if (RobustFile.Exists(ffmpeg))
            {
                var argsBuilder = new StringBuilder("-i \"concat:");
                foreach (var path in mergeFiles)
                {
                    argsBuilder.Append(path + "|");
                }
                argsBuilder.Length--;

                argsBuilder.Append($"\" -c copy \"{combinedAudioPath}\"");
                var result = CommandLineRunner.Run(ffmpeg, argsBuilder.ToString(), "", 60 * 10, new NullProgress());
                var output = result.ExitCode != 0 ? result.StandardError : null;
                if (output != null)
                {
                    RobustFile.Delete(combinedAudioPath);
                }

                return(output);
            }

            return("Could not find ffmpeg");
        }
예제 #3
0
 protected CalamariResult Invoke(CommandLine command, VariableDictionary variables)
 {
     var capture = new CaptureCommandOutput();
     var runner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables), capture));
     var result = runner.Execute(command.Build());
     return new CalamariResult(result.ExitCode, capture);
 }
    IEnumerator DoTrainingCo()
    {
        Process currentProcess = null;

        configIncrement = StartingConfigIncrement;
        while (configIncrement <= MaxConfigIncrement)
        {
            if (OnStartIncrement != null)
            {
                OnStartIncrement.Invoke();
            }

            for (currentRun = 0; currentRun < RunsPerConfiguration; currentRun++)
            {
                yield return(new WaitForSeconds(PauseBeforeRun));

                UnityEngine.Debug.Log("Starting run " + currentRun + " in config increment " + configIncrement);

                var myArguments = new List <string>(); // Make a copy of the args
                var runId       = RunSetName + "-inc" + configIncrement + "-run" + currentRun;
                myArguments.Add(UnityOutputExeName);
                myArguments.Add("--run-id=" + runId); // Add our own arg
                myArguments.Add("--train");

                if (ContinueFromSaved == true)
                {
                    myArguments.Add("--load");
                    var sourcePath = Path.Combine(tensorFlowConfig.ModelsDirectory, ContinueFromModel);
                    var targetPath = Path.Combine(tensorFlowConfig.ModelsDirectory, runId);
                    Directory.CreateDirectory(targetPath);
                    CopyDirectory(sourcePath, targetPath);
                }

                CommandLineRunner.WorkingDirectory = tensorFlowConfig.MlAgentsRootDirectory;
                currentProcess = CommandLineRunner.StartCommandLine(tensorFlowConfig.MlAgentsRootDirectory, "learn.py", myArguments.ToArray());

                // Coroutine hold until process is complete
                while (currentProcess.HasExited == false)
                {
                    yield return(null);
                }

                if (TbManager != null)
                {
                    yield return(StartCoroutine(TbManager.GetRunStats(runId, currentRun, configIncrement, new Action <RunStatistics>(AddToStats))));
                }
            }
            currentRun = 0;

            if (OnNextIncrement != null)
            {
                OnNextIncrement.Invoke();
            }
        }

        if (OnAllIncrementsComplete != null)
        {
            OnAllIncrementsComplete.Invoke();
        }
    }
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            if (variablesFile != null && !File.Exists(variablesFile))
            {
                throw new CommandException("Could not find variables file: " + variablesFile);
            }

            var variables = new CalamariVariableDictionary(variablesFile, sensitiveVariablesFile, sensitiveVariablesPassword);

            variables.Set(SpecialVariables.OriginalPackageDirectoryPath, Environment.CurrentDirectory);
            var commandLineRunner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));
            var fileSystem        = new WindowsPhysicalFileSystem();
            var filesInPackage    = !string.IsNullOrWhiteSpace(packageFile);
            var conventions       = new List <IConvention>
            {
                new ContributeEnvironmentVariablesConvention(),
                new LogVariablesConvention(),
                new ExtractPackageToStagingDirectoryConvention(new GenericPackageExtractorFactory().createStandardGenericPackageExtractor(), fileSystem),
                new ConfiguredScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner),
                new DeployAzureResourceGroupConvention(templateFile, templateParameterFile, filesInPackage, fileSystem, new ResourceGroupTemplateNormalizer()),
                new PackagedScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner),
            };

            var deployment       = new RunningDeployment(packageFile, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);

            conventionRunner.RunConventions();
            return(0);
        }
예제 #6
0
        static int Main(string[] args)
        {
            var migrateNoInteractive = false;
            var appConfiguration     = new AppConfiguration
            {
                SupportedDialects = new List <string>
                {
                    MigratorDatabaseDialect.SqlServer,
                },
                MigrationAssemblies = new[]
                {
                    typeof(DatabaseTagTypes).Assembly,
                }
            };

            IApplicationRunner applicationRunner = new CommandLineRunner(appConfiguration, args);

            if (args != null && args.Contains(CommandLineRunner.NoInteractiveFlag))
            {
                migrateNoInteractive = true;

                args = args.Where(x => !x.Contains(CommandLineRunner.NoInteractiveFlag)).ToArray();
            }

            if (args == null || args.Length == 0)
            {
                applicationRunner = new ConfigurationRunner(appConfiguration, migrateNoInteractive);
            }

            return(applicationRunner.RunApplication());
        }
예제 #7
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);
            JavaRuntime.VerifyExists();

            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
            var variables  =
                new CalamariVariableDictionary(variablesFile, sensitiveVariableFiles, sensitiveVariablesPassword);

            var commandOutput =
                new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables));
            var commandLineRunner = new CommandLineRunner(commandOutput);
            var embeddedResources = new AssemblyEmbeddedResources();

            var conventions = new List <IConvention>
            {
                new ContributeEnvironmentVariablesConvention(),
                new JavaStepConvention(actionType, new JavaRunner(commandLineRunner, variables)),
                new FeatureRollbackConvention(DeploymentStages.DeployFailed, fileSystem, scriptEngine,
                                              commandLineRunner, embeddedResources)
            };

            var deployment       = new RunningDeployment(null, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);

            conventionRunner.RunConventions();

            return(0);
        }
예제 #8
0
        private void DeployTestSite(string sampleName, string framework)
        {
            var runner = new CommandLineRunner()
            {
                Timeout = TimeSpan.FromMinutes(5)
            };

            _testsitesource = Path.GetTempFileName();
            File.Delete(_testsitesource);
            Directory.CreateDirectory(_testsitesource);

            var sourcePath = PathHelper.GetTestAppFolder(sampleName);

            Assert.NotNull(sourcePath);

            runner.Execute($"git clean -xdff .", sourcePath);
            Assert.NotEqual(-1, runner.Execute($"robocopy {sourcePath} {_testsitesource} /E /S /XD node_modules")); // robcopy doesn't return 0
            File.Copy(PathHelper.GetNuGetConfig(), Path.Combine(_testsitesource, "NuGet.config"));

            _log.LogInformation($"Testsite sources are copied to {_testsitesource}.");

            CreateTestSite();

            Assert.Equal(0, runner.Execute("git add -A .", _testsitesource));
            Assert.Equal(0, runner.Execute("git commit -m \"init\"", _testsitesource));

            var giturl = $"https://{_username}:{_password}@{_testsitename}.scm.azurewebsites.net:443/{_testsitename}.git";

            Assert.Equal(0, runner.Execute($"git remote set-url azure {giturl}", _testsitesource));

            _log.LogInformation("Git repository is set up at testsite source folder");

            runner.Timeout = TimeSpan.FromMinutes(15);
            Assert.Equal(0, runner.Execute($"git push azure master", _testsitesource));
        }
예제 #9
0
        internal static int Main(string[] args)
        {
            try
            {
                var responseFile = Path.Combine(AppContext.BaseDirectory, InteractiveResponseFileName);

                var compiler = new CSharpInteractiveCompiler(
                    responseFile,
                    AppContext.BaseDirectory,
                    args,
                    new NotImplementedAnalyzerLoader());

                var runner = new CommandLineRunner(
                    ConsoleIO.Default,
                    compiler,
                    CSharpScriptCompiler.Instance,
                    CSharpObjectFormatter.Instance);

                return(runner.RunInteractive());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(1);
            }
        }
예제 #10
0
        /// <summary>
        /// Encode the given file as an .mp3 file in the same directory.
        /// </summary>
        /// <returns>Path to the new file</returns>
        public string Encode(string sourcePath)
        {
            string destinationPath = Path.ChangeExtension(sourcePath, AudioRecording.kPublishableExtension);

            try
            {
                if (RobustFile.Exists(destinationPath))
                {
                    RobustFile.Delete(destinationPath);
                }
            }
            catch (Exception)
            {
                var shortMsg = LocalizationManager.GetString("LameEncoder.DeleteFailedShort", "Cannot replace mp3 file. Check antivirus");
                var longMsg  = LocalizationManager.GetString("LameEncoder.DeleteFailedLong", "Bloom could not replace an mp3 file. If this continues, check your antivirus.");
                NonFatalProblem.Report(ModalIf.None, PassiveIf.All, shortMsg, longMsg);
                return(null);
            }

            //-a downmix to mono
            string          arguments = $"-a \"{sourcePath}\" \"{destinationPath}\"";
            ExecutionResult result    = CommandLineRunner.Run(GetLamePath(), arguments, null, 60, new NullProgress());

            result.RaiseExceptionIfFailed("");
            return(destinationPath);
        }
        public void SupportsHook_ForClass_ReturnsFalse()
        {
            _runner = new CommandLineRunner(_log.Object, _config.Object, _fs.Object, _output);
            var supports = _runner.SupportsHook(new HookTypeRef(typeof(object)));

            Assert.That(supports, Is.False);
        }
        private static void RunCommand(params string[] inputArgs)
        {
            var consoleBuffer = new StringBuilder();
            var consoleOutput = new CommandStatusWriter(new StringWriter(consoleBuffer));

            CommandLineRunner.RunCommand(inputArgs, consoleOutput);
        }
예제 #13
0
파일: Csi.cs 프로젝트: zlphoenix/roslyn
        internal static int Main(string[] args)
        {
            try
            {
                var responseFile = Path.Combine(AppContext.BaseDirectory, InteractiveResponseFileName);

                var compiler = new CSharpInteractiveCompiler(
                    responseFile: responseFile,
                    baseDirectory: Directory.GetCurrentDirectory(),
                    sdkDirectoryOpt: CorLightup.Desktop.TryGetRuntimeDirectory(),
                    args: args,
                    clientDirectory: AppContext.BaseDirectory,
                    analyzerLoader: new NotImplementedAnalyzerLoader());

                var runner = new CommandLineRunner(
                    ConsoleIO.Default,
                    compiler,
                    CSharpScriptCompiler.Instance,
                    CSharpObjectFormatter.Instance);

                return(runner.RunInteractive());
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return(1);
            }
        }
        private int InvokeScript(CalamariVariableDictionary variables)
        {
            var validatedScriptFilePath = AssertScriptFileExists();

            var scriptEngine = new CombinedScriptEngine();
            var runner       = new CommandLineRunner(
                new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));

            Log.VerboseFormat("Executing '{0}'", validatedScriptFilePath);
            var result             = scriptEngine.Execute(new Script(validatedScriptFilePath, scriptParameters), variables, runner);
            var shouldWriteJournal = CanWriteJournal(variables) && deployment != null && !deployment.SkipJournal;

            if (result.ExitCode == 0 && result.HasErrors && variables.GetFlag(SpecialVariables.Action.FailScriptOnErrorOutput, false))
            {
                if (shouldWriteJournal)
                {
                    journal.AddJournalEntry(new JournalEntry(deployment, false));
                }

                return(-1);
            }

            if (shouldWriteJournal)
            {
                journal.AddJournalEntry(new JournalEntry(deployment, true));
            }

            return(result.ExitCode);
        }
예제 #15
0
        private static bool TrimVideoUsingFfmpeg(string sourceVideoFilePath,
                                                 string destinationPath,
                                                 string timings)
        {
            Guard.Against(string.IsNullOrEmpty(FfmpegProgram), "Caller should have verified 'ffmpeg' existence.");
            var timingArray = timings.Split(',');
            var startTiming = ConvertSecondsToHhMmSsString(timingArray[0]);
            var endTiming   = ConvertSecondsToHhMmSsString(timingArray[1]);
            // Run ffmpeg on the file to trim it down using the timings.
            // -hide_banner = don't write all the version and build information to the console
            // -i <path> = specify input file
            // -ss HH:MM:SS.T = trim to this start time
            // -to HH:MM:SS.T = trim to this end time
            // -c:v copy -c:a copy = copy video (and audio) streams with no codec modification
            var parameters = $"-hide_banner -i \"{sourceVideoFilePath}\" -ss {startTiming} -to {endTiming} -c:v copy -c:a copy \"{destinationPath}\"";
            var result     = CommandLineRunner.Run(FfmpegProgram, parameters, "", 60, new NullProgress());

            if (result.DidTimeOut)
            {
                Logger.WriteEvent("ffmpeg timed out trimming video for publication");
                return(false);
            }

            var output = result.StandardError;

            if (string.IsNullOrWhiteSpace(output) || output.Contains("Invalid data found when processing input"))
            {
                Logger.WriteEvent("ffmpeg did not return normal output");
                return(false);
            }

            return(true);
        }
예제 #16
0
파일: Csi.cs 프로젝트: nemec/roslyn
        internal static int Main(string[] args)
        {
            try
            {
                var responseFile = Path.Combine(AppContext.BaseDirectory, InteractiveResponseFileName);

                var compiler = new CSharpInteractiveCompiler(
                    responseFile,
                    AppContext.BaseDirectory, 
                    args,
                    new NotImplementedAnalyzerLoader());

                var runner = new CommandLineRunner(
                    ConsoleIO.Default,
                    compiler,
                    CSharpScriptCompiler.Instance,
                    CSharpObjectFormatter.Instance);

                return runner.RunInteractive();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return 1;
            }
        }
예제 #17
0
파일: Csi.cs 프로젝트: hbarve1/roslyn
        internal static int Main(string[] args)
        {
            try
            {
                var responseFile = Path.Combine(AppContext.BaseDirectory, InteractiveResponseFileName);

                var compiler = new CSharpInteractiveCompiler(
                    responseFile: responseFile,
                    baseDirectory: Directory.GetCurrentDirectory(), 
                    sdkDirectoryOpt: CorLightup.Desktop.TryGetRuntimeDirectory(),
                    args: args,
                    analyzerLoader: new NotImplementedAnalyzerLoader());

                var runner = new CommandLineRunner(
                    ConsoleIO.Default,
                    compiler,
                    CSharpScriptCompiler.Instance,
                    CSharpObjectFormatter.Instance);

                return runner.RunInteractive();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return 1;
            }
        }
예제 #18
0
        protected void when_executing(string line)
        {
            var commandLineRunner = new CommandLineRunner();

            Results = commandLineRunner.Run(CommandDescriptor, line).ToList();
            Command = (T)commandLineRunner.LastCommand;
        }
예제 #19
0
    public void StartTensorboard()
    {
        var args = new List <string>();

        args.Add("--logdir=" + tensorFlowCOnfig.SummariesDirectory);
        CommandLineRunner.StartCommandLine(tensorFlowCOnfig.TensorboardDirectory, "tensorboard", args.ToArray());
    }
예제 #20
0
        /// <summary>
        /// Converts to low-quality, small picture
        /// </summary>
        /// <returns>log of the run</returns>
        public static ExecutionResult MakeLowQualitySmallPicture(string inputPath, string outputPath, IProgress progress)
        {
            if (string.IsNullOrEmpty(LocateAndRememberFFmpeg()))
            {
                return(new ExecutionResult()
                {
                    StandardError = "Could not locate FFMpeg"
                });
            }

            //enhance: how to lower the quality?

            var arguments = "-i \"" + inputPath + "\" -f image2  -s 176x144 \"" + outputPath + "\"";

            progress.WriteMessage("ffmpeg " + arguments);

            var result = CommandLineRunner.Run(LocateAndRememberFFmpeg(),
                                               arguments,
                                               Environment.CurrentDirectory,
                                               60 * 10,          //10 minutes
                                               progress
                                               );

            progress.WriteVerbose(result.StandardOutput);
            if (result.StandardError.ToLower().Contains("error")) //ffmpeg always outputs config info to standarderror
            {
                progress.WriteError(result.StandardError);
            }

            return(result);
        }
        static Maybe <Version> GetPython3Version()
        {
            var executable = PythonBootstrapper.FindPythonExecutable();
            var command    = new CommandLine(executable).Argument("--version");
            var capture    = new CaptureCommandOutput();
            var runner     = new CommandLineRunner(
                new SplitCommandOutput(
                    new ConsoleCommandOutput(),
                    new ServiceMessageCommandOutput(new VariableDictionary()),
                    capture));
            var result = runner.Execute(command.Build());

            if (result.ExitCode != 0)
            {
                return(Maybe <Version> .None);
            }

            var allCapturedMessages = capture.AllMessages.Aggregate((a, b) => $"{a}, {b}");
            var pythonVersionMatch  = PythonVersionFinder.Match(allCapturedMessages);

            if (!pythonVersionMatch.Success)
            {
                return(Maybe <Version> .None);
            }

            var major = pythonVersionMatch.Groups[1].Value;
            var minor = pythonVersionMatch.Groups[2].Value;

            return(new Version(int.Parse(major), int.Parse(minor)).AsSome());
        }
예제 #22
0
        public static int Run(String script, ShellControl !shellControl,
                              CommandLineRunner runner, String[] arguments)
        {
            ScriptEngine engine = new ScriptEngine(script, runner);

            try {
                engine.Parse();
            }
            catch (Parser.ParseException e) {
                Console.WriteLine(e.Message);
                return(-1);
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
                return(-1);
            }

            try {
                return(engine.Run(shellControl, arguments));
            }
            catch (Interpretation.InterpretationException e) {
                Console.WriteLine(e.Message);
            }
            catch (ScriptException e) {
                Console.WriteLine(e.Message);
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            return(-1);
        }
예제 #23
0
        public override bool Execute()
        {
            if (Debug)
            {
                Debugger.Launch();
            }

            var runner = new CommandLineRunner();

            var commands = ReadCommands(_environment);

            var command = commands.FirstOrDefault(x => x.Noun.EqualsNoCase(Noun) && x.Verb.EqualsNoCase(Verb));

            if (command == null)
            {
                Log.LogError("Command named '{0}-{1}' is not a recognized command.", Verb, Noun);
                return(false);
            }
            foreach (var value in runner.Run(command, GetArguments()))
            {
                ProcessOutput(value);
            }

            return(_success);
        }
예제 #24
0
        ICommand CreateInstance(Type type, IVariables variables, ILog log)
        {
            var fileSystem        = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
            var commandLineRunner = new CommandLineRunner(ConsoleLog.Instance, variables);
            var substituteInFiles = new SubstituteInFiles(fileSystem, new FileSubstituter(log, fileSystem), variables);
            var extractPackages   = new ExtractPackage(new CombinedPackageExtractor(log), fileSystem, variables, log);

            if (type == typeof(PlanCommand))
            {
                return(new PlanCommand(log, variables, fileSystem, commandLineRunner, substituteInFiles, extractPackages));
            }

            if (type == typeof(ApplyCommand))
            {
                return(new ApplyCommand(log, variables, fileSystem, commandLineRunner, substituteInFiles, extractPackages));
            }

            if (type == typeof(DestroyCommand))
            {
                return(new DestroyCommand(log, variables, fileSystem, commandLineRunner, substituteInFiles, extractPackages));
            }

            if (type == typeof(DestroyPlanCommand))
            {
                return(new DestroyPlanCommand(log, variables, fileSystem, commandLineRunner, substituteInFiles, extractPackages));
            }

            throw new ArgumentException();
        }
예제 #25
0
 public static void CompressImage(string path, IProgress progress)
 {
     progress.WriteStatus("Compressing image: " + Path.GetFileName(path));
     var pngoutPath = FileLocator.GetFileDistributedWithApplication("optipng.exe");
     var result     = CommandLineRunner.Run(pngoutPath, "\"" + path + "\"", Encoding.UTF8, Path.GetDirectoryName(path), 300, progress,
                                            (s) => progress.WriteMessage(s));
 }
예제 #26
0
        internal static int Main(string[] args)
        {
            try
            {
                // Note that AppContext.BaseDirectory isn't necessarily the directory containing csi.exe.
                // For example, when executed via corerun it's the directory containing corerun.
                string csiDirectory = Path.GetDirectoryName(typeof(Csi).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName);

                var buildPaths = new BuildPaths(
                    clientDir: csiDirectory,
                    workingDir: Directory.GetCurrentDirectory(),
                    sdkDir: RuntimeMetadataReferenceResolver.GetDesktopFrameworkDirectory(),
                    tempDir: Path.GetTempPath());

                var compiler = new CSharpInteractiveCompiler(
                    responseFile: Path.Combine(csiDirectory, InteractiveResponseFileName),
                    buildPaths: buildPaths,
                    args: args,
                    analyzerLoader: new NotImplementedAnalyzerLoader());

                var runner = new CommandLineRunner(
                    ConsoleIO.Default,
                    compiler,
                    CSharpScriptCompiler.Instance,
                    CSharpObjectFormatter.Instance);

                return(runner.RunInteractive());
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return(1);
            }
        }
예제 #27
0
        public async Task <FileInfo> PackageArchive(string sourceDirectory, string targetDirectory)
        {
            var cmdLineRunner = new CommandLineRunner(Log, Variables);
            var jarTool       = new JarTool(cmdLineRunner, Log, Variables);

            var packageMetadata = PackageName.FromFile(Deployment.PackageFilePath);

            var customPackageFileName = Variables.Get(PackageVariables.CustomPackageFileName);

            if (!string.IsNullOrWhiteSpace(customPackageFileName))
            {
                Log.Verbose($"Using custom package file-name: '{customPackageFileName}'");
            }

            var targetFilePath = Path.Combine(targetDirectory, customPackageFileName ?? Path.GetFileName(Deployment.PackageFilePath));

            var enableCompression = Variables.GetFlag(PackageVariables.JavaArchiveCompression, true);

            await Task.Run(() =>
            {
                jarTool.CreateJar(sourceDirectory, targetFilePath, enableCompression);
            });

            return(new FileInfo(targetFilePath));
        }
예제 #28
0
        public string Encode(string inputFilePath, Track track, ITagger tagger)
        {
            if (string.IsNullOrWhiteSpace(inputFilePath))
            {
                throw new ArgumentNullException("inputFilePath");
            }

            if (track == null)
            {
                throw new ArgumentNullException("track");
            }

            if (tagger == null)
            {
                throw new ArgumentNullException("tagger");
            }

            var outputFilePath = BuildOutputFilePath(track);

            string buildArgsFunc = _buildArgsFunc(inputFilePath, outputFilePath, _quality);

            var encoderCmd = new CommandLineRunner(buildArgsFunc);

            encoderCmd.Run();

            if (encoderCmd.ExitCode != 0)
            {
                throw new CommandLineOperationException(encoderCmd.StandardError, encoderCmd.ExitCode);
            }

            tagger.Tag(outputFilePath, track);

            return(outputFilePath);
        }
예제 #29
0
        public override bool Execute()
        {
            if (Debug)
            {
                Debugger.Launch();
            }

            var runner = new CommandLineRunner();

            var commands = ReadCommands(_environment);

            var command = commands.FirstOrDefault(x => x.Noun.EqualsNoCase(Noun) && x.Verb.EqualsNoCase(Verb));

            if (command == null)
            {
                Log.LogError("Command named '{0}-{1}' is not a recognized command.", Verb, Noun);
                return(false);
            }
            var captures      = (Capture ?? string.Empty).Split(';');
            var captureResult = new List <ITaskItem>();

            foreach (var value in runner.Run(command, GetArguments()))
            {
                ProcessOutput(value);
                CaptureOutput(value, captures, captureResult);
            }
            Captures = captureResult.ToArray();
            return(_success);
        }
예제 #30
0
        private static CalamariResult ExecuteScript(IScriptEngine psse, string scriptName, CalamariVariableDictionary variables)
        {
            var capture = new CaptureCommandOutput();
            var runner  = new CommandLineRunner(capture);
            var result  = psse.Execute(new Script(scriptName), variables, runner);

            return(new CalamariResult(result.ExitCode, capture));
        }
예제 #31
0
        protected static string RunCommand(params string[] inputArgs)
        {
            var consoleBuffer = new StringBuilder();
            var consoleOutput = new CommandStatusWriter(new StringWriter(consoleBuffer));

            CommandLineRunner.RunCommand(inputArgs, consoleOutput);
            return(consoleBuffer.ToString());
        }
        public void ExecuteHook_WhenGivenAProcessThatExitsWithANoneZeroCode_Throws()
        {
            _runner = new CommandLineRunner(_log.Object, _config.Object, _fs.Object, _output);
            var ex = Assert.Throws <HookFailureException>(() => _runner.ExecuteHook(new HookTypeRef("cmd", HookType.File), "/c exit -300"));

            Assert.That(ex.HookFile, Is.EqualTo("cmd"));
            Assert.That(ex.ExitCode, Is.EqualTo(-300));
        }
예제 #33
0
        public void Can_deploy_to_directory()
        {
            // setup
            var deployDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DeploymentDirectory");
            if (Directory.Exists(deployDirectory))
                Directory.Delete(deployDirectory, true);
            Directory.CreateDirectory(deployDirectory);
            var writer = new ConsoleWriter();
            var runContext = new RunContext();
            var runner = new CommandLineRunner(writer,
                new PackageProcessor(new ActionExecutor(writer, runContext), writer, new NuGetProcess(writer), runContext),
                new NullActionExecutor(),
                runContext);
            SetDefinitions(new Packages
            {
                Items = new object[]
                {
                    new Package
                    {
                        BasePath = _baseDirectory,
                        name = "package 1",
                        NuSpecPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestData/TestNuSpec.nuspec"),
                        OutputDirectory = _outputDirectory,
                        Version = "",
                        Deployments = new PackageDeployments
                        {
                            Deployment = new[]
                            {
                                new Deployment
                                {
                                    name = "test deployment",
                                    path = deployDirectory
                                }
                            }
                        }
                    }
                }
            });

            // act
            runner.Run(_rootDirectory, _nugetLocation, _defintionsFileLocation, "", new Dictionary<string, string>());

            // assert
            Assert.IsTrue(File.Exists(Path.Combine(deployDirectory, "package1.1.2.3.nupkg")));
        }
예제 #34
0
        public void Invalid_defintions_file_writes_error()
        {
            // setup
            var writer = new Mock<IConsoleWriter>();
            writer.Setup(x => x.WriteError("Error with definitions file: The 'Invalid' start tag on line 1 position 51 does not match the end tag of 'Packages'. Line 1, position 61."));
            var runner = new CommandLineRunner(writer.Object, new NullPackageProcessor(), new NullActionExecutor(), new RunContext());
            var invalidXmlFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "invaidxml.xml");
            if (File.Exists(invalidXmlFile))
                File.Delete(invalidXmlFile);
            File.WriteAllText(invalidXmlFile, "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Packages><Invalid></Packages>");

            // act
            runner.Run(_rootDirectory, _nugetLocation, invalidXmlFile, string.Empty, new Dictionary<string, string>());

            // assert
            writer.Verify(x => x.WriteError("Error with definitions file: The 'Invalid' start tag on line 1 position 51 does not match the end tag of 'Packages'. Line 1, position 61."));
        }
예제 #35
0
        public void Throws_error_if_nuget_doesnt_exist()
        {
            var commandLineRunner = new CommandLineRunner(new ConsoleWriter(), new NullPackageProcessor(), new NullActionExecutor(), new RunContext());

            try
            {
                commandLineRunner.Run(_rootDirectory, "C:\\no\\where.exe", _defintionsFileLocation, string.Empty, new Dictionary<string, string>());
            }
            catch (Exception ex)
            {
                Assert.AreEqual("The nuget location \"C:\\no\\where.exe\" doesn't exist.", ex.Message);
                return;
            }

            Assert.Fail("No error thrown");
        }
예제 #36
0
        public void Nuspec_overrides_package_and_global_level_versions()
        {
            // setup
            var writer = new ConsoleWriter();
            var runContext = new RunContext();
            var runner = new CommandLineRunner(writer,
                new PackageProcessor(new ActionExecutor(writer, runContext), writer, new NuGetProcess(writer), runContext),
                new NullActionExecutor(),
                runContext);
            SetDefinitions(new Packages
            {
                Items = new object[]
                {
                    new Package
                    {
                        BasePath = _baseDirectory,
                        name = "package 1",
                        NuSpecPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestData/TestNuSpec.nuspec"),
                        OutputDirectory = _outputDirectory,
                        Version = "4.0.1"
                    }
                }
            });

            // act
            runner.Run(_rootDirectory, _nugetLocation, _defintionsFileLocation, "5.0.1", new Dictionary<string, string>());

            // assert
            Assert.IsTrue(File.Exists(Path.Combine(_outputDirectory, "package1.1.2.3.nupkg")));
        }
예제 #37
0
        public void Error_when_proccessing_nuspec_without_global_or_package_version()
        {
            // setup
            var writer = new Mock<IConsoleWriter>();
            writer.Setup(x => x.WriteMessage(It.IsAny<string>()));
            writer.Setup(x => x.WriteError(It.IsAny<string>()));
            var runContext = new RunContext();
            var runner = new CommandLineRunner(writer.Object,
                new PackageProcessor(new ActionExecutor(writer.Object, runContext), writer.Object, new NuGetProcess(writer.Object), runContext),
                new NullActionExecutor(),
                runContext);
            SetDefinitions(new Packages
            {
                Items = new object[]
                {
                    new Package
                    {
                        BasePath = _baseDirectory,
                        name = "package 1",
                        NuSpecPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestData/TestNuSpecWithoutVersion.nuspec"),
                        OutputDirectory = _outputDirectory,
                        Version = ""
                    }
                }
            });

            // act
            runner.Run(_rootDirectory, _nugetLocation, _defintionsFileLocation, "", new Dictionary<string, string>());

            // assert
            writer.Verify(
                x =>
                x.WriteError("The nuspec for package \"package 1\" expects a version to be supplied but the package didn't define one and also there wasn't a version inputed via the parameter -v."));
        }
예제 #38
0
        public void No_packages_or_commands_writes_warning()
        {
            // setup
            var writer = new Mock<IConsoleWriter>();
            writer.Setup(x => x.WriteWarning("There are no packages or pre/post commands defined."));
            var runner = new CommandLineRunner(writer.Object, new NullPackageProcessor(), new NullActionExecutor(), new RunContext());
            var validXmlFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "validxml.xml");
            if (File.Exists(validXmlFile))
                File.Delete(validXmlFile);
            File.WriteAllText(validXmlFile, "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Packages></Packages>");

            // act
            runner.Run(_rootDirectory, _nugetLocation, validXmlFile, string.Empty, new Dictionary<string, string>());

            // assert
            writer.Verify(x => x.WriteWarning("There are no packages or pre/post commands defined."));
        }