public override void Execute()
        {
            base.Execute();

            if (string.IsNullOrEmpty(Output) || !Directory.Exists(Output))
            {
                Logger.Instance.WriteError("Output Path '{0}' does not exist", Output);
                return;
            }

            string design = PathHelper.GetFullPath(Design);
            Logger.Instance.WriteVerbose("Selected NCD '{0}'", Design);

            OutputPath location = new OutputPath();
            location.OutputDirectory = PathHelper.GetFullPath(Output);
            location.TemporaryDirectory = SystemHelper.GetTemporaryDirectory();
            location.WorkingDirectory = Environment.CurrentDirectory;
            location.LogDirectory = location.OutputDirectory;

            Logger.Instance.WriteVerbose("Starting Build");
            BitstreamGenerator generator = new BitstreamGenerator(XilinxHelper.GetCurrentXilinxToolchain(), location, design);
            if (generator.Build())
            {
                Logger.Instance.WriteInfo("Build Complete");
            }
            else
            {
                Logger.Instance.WriteError("Build Failed");
            }

            Logger.Instance.WriteVerbose("Cleaning temporary directory");
            Directory.Delete(location.TemporaryDirectory, true);
        }
        public override void Execute()
        {
            base.Execute();

            if (string.IsNullOrEmpty(Output) || !Directory.Exists(Output))
            {
                Logger.Instance.WriteError("Output Path '{0}' does not exist", Output);
                return;
            }

            string design = PathHelper.GetFullPath(Design);
            Logger.Instance.WriteVerbose("Selected NCD '{0}'", Design);

            OutputPath location = new OutputPath();
            location.OutputDirectory = PathHelper.GetFullPath(Output);
            location.TemporaryDirectory = SystemHelper.GetTemporaryDirectory();
            location.WorkingDirectory = Environment.CurrentDirectory;
            location.LogDirectory = location.OutputDirectory;

            Logger.Instance.WriteVerbose("Starting Generation");
            BlockMemoryMapGenerator bmmGenerator = new BlockMemoryMapGenerator(location);
            bmmGenerator.NCDFile = design;
            if (bmmGenerator.Build())
            {
                Logger.Instance.WriteInfo("Generation Complete");
            }
            else
            {
                Logger.Instance.WriteError("Generation Failed");
            }

            Logger.Instance.WriteVerbose("Cleaning temporary directory");
            Directory.Delete(location.TemporaryDirectory, true);
        }
        public override void Execute()
        {
            base.Execute();

            if (string.IsNullOrEmpty(Output) || !Directory.Exists(Output))
            {
                Logger.Instance.WriteError("Output Path '{0}' does not exist", Output);
                return;
            }

            string netlist = PathHelper.GetFullPath(NetList);
            string constraints = PathHelper.GetFullPath(Constraints);
            Logger.Instance.WriteVerbose("Selected NetList '{0}'", netlist);
            Logger.Instance.WriteVerbose("Selected Constraints '{0}'", constraints);

            // Search for Part
            DevicePartSpeed device = DeviceHelper.FindDeviceByName(Device);
            if (device == null)
            {
                Logger.Instance.WriteError("Cannot Find Device '{0}'", Device);
                return;
            }
            Logger.Instance.WriteVerbose("Selected device '{0}'", device.Name);

            OutputPath location = new OutputPath();
            location.OutputDirectory = PathHelper.GetFullPath(Output);
            location.TemporaryDirectory = SystemHelper.GetTemporaryDirectory();
            location.WorkingDirectory = Environment.CurrentDirectory;
            location.LogDirectory = location.OutputDirectory;

            Logger.Instance.WriteVerbose("Starting Build");
            GenericImplementationConfiguration config = new GenericImplementationConfiguration();
            config.Constraints = constraints;
            config.NetList = netlist;
            config.TargetDevice = device;

            IImplementor implementor = XilinxHelper.GetCurrentXilinxToolchain().Implementors.FirstOrDefault();
            if (implementor != null)
            {
                using (IImplementorInstance instance = implementor.Create(location, config))
                {
                    if (instance.Build())
                    {
                        Logger.Instance.WriteInfo("Build Complete");
                    }
                    else
                    {
                        Logger.Instance.WriteError("Build Failed");
                    }
                }
            }

            Logger.Instance.WriteVerbose("Cleaning temporary directory");
            Directory.Delete(location.TemporaryDirectory, true);
        }
        public override void Execute()
        {
            base.Execute();

            if (string.IsNullOrEmpty(Output) || !Directory.Exists(Output))
            {
                Logger.Instance.WriteError("Output Path '{0}' does not exist", Output);
                return;
            }

            string bmmfile = PathHelper.GetFullPath(BlockMemoryMap);
            string bitfile = PathHelper.GetFullPath(Bitstream);
            string binary = PathHelper.GetFullPath(Binary);
            Logger.Instance.WriteVerbose("Selected BMM '{0}'", bmmfile);
            Logger.Instance.WriteVerbose("Selected Bitstream '{0}'", bitfile);
            Logger.Instance.WriteVerbose("Selected Binary '{0}'", binary);

            OutputPath location = new OutputPath();
            location.OutputDirectory = PathHelper.GetFullPath(Output);
            location.TemporaryDirectory = SystemHelper.GetTemporaryDirectory();
            location.WorkingDirectory = Environment.CurrentDirectory;
            location.LogDirectory = location.OutputDirectory;

            Logger.Instance.WriteVerbose("Starting Injection");
            BitstreamDataInjector bitInjector = new BitstreamDataInjector(location);
            bitInjector.BMMDescription = bmmfile;
            bitInjector.Bitstream = bitfile;
            bitInjector.BinaryFile = binary;
            if (bitInjector.Build())
            {
                Logger.Instance.WriteInfo("Injection Complete");
            }
            else
            {
                Logger.Instance.WriteError("Injection Failed");
            }

            Logger.Instance.WriteVerbose("Cleaning temporary directory");
            Directory.Delete(location.TemporaryDirectory, true);
        }
 public BlockMemoryMapGenerator(OutputPath output)
 {
     OutputLocation = output;
 }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="numberOfThreads"></param>
        public void RunSimulations(int numberOfThreads = -1)
        {
            int noCoresToUse = numberOfThreads;
            int noCores      = Environment.ProcessorCount;

            if (noCoresToUse <= 0)
            {
                noCoresToUse += noCores;
            }

            //Set up outputs (on main thread)
            if (OutputType == OutputType.CSVOutput)
            {
                FileInfo hlkFile = new FileInfo(FileName);

                if (OutputPath == null)
                {
                    OutputPath = hlkFile.Directory.FullName.Replace("\\", "/");
                }

                if (!OutputPath.Contains(":") || OutputPath.Contains("./"))
                {
                    DirectoryInfo outDir = new DirectoryInfo(Path.Combine(hlkFile.Directory.FullName, OutputPath));
                    if (!outDir.Exists)
                    {
                        outDir.Create();
                    }

                    OutputPath = outDir.FullName;
                }
            }
            else if (OutputType == OutputType.SQLiteOutput)
            {
                if (OutputPath == null)
                {
                    OutputPath = FileName.Replace(".hlk", ".sqlite");
                    OutputPath = OutputPath.Replace("\\", "/");
                }

                //if (DBContext == null)
                //{
                //    DBContext = new HLDBContext(new SQLiteConnection("data source=" + OutputPath + ";foreign keys=false"), true);

                //    DBContext.Configuration.AutoDetectChangesEnabled = false;
                //    DBContext.Configuration.ValidateOnSaveEnabled = false;

                //    //DBContext.SaveChanges();
                //}

                //List<string> OutputIndicies = new List<string>();

                //for(int i = 0; i < OutputDataElements.Count; i++)
                //{
                //    OutputIndicies.Add("x" + (i + 1).ToString());
                //}
                if (SQLConn != null && SQLConn.State == System.Data.ConnectionState.Open)
                {
                    SQLConn.Close();
                }

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

                SQLiteConnection.CreateFile(OutputPath);

                SQLConn = new SQLiteConnection("Data Source=" + OutputPath + ";Version=3;");
                SQLConn.Open();

                //Will need to create tables
                //Data
                string sql = "create table data (SimId int, Day int," + String.Join(" double,", OutputDataElements.Where(j => j.IsSelected == true).Select(x => x.Name)) + " double)";
                // sql = "create table data (SimId int, Day int," + String.Join(" double,", OutputIndicies) + " double)";

                SQLiteCommand command = new SQLiteCommand(sql, SQLConn);
                command.ExecuteNonQuery();

                //Annual sum data
                sql = "create table annualdata (SimId int, Year int," + String.Join(" double,", OutputDataElements.Where(j => j.IsSelected == true).Select(x => x.Name)) + " double)";
                // sql = "create table annualdata (SimId int, Year int," + String.Join(" double,", OutputIndicies) + " double)";

                command = new SQLiteCommand(sql, SQLConn);
                command.ExecuteNonQuery();

                //Annual sum average data
                sql = "create table annualaveragedata (SimId int," + String.Join(" double,", OutputDataElements.Where(j => j.IsSelected == true).Select(x => x.Name)) + " double)";
                // sql = "create table annualaveragedata (SimId int," + String.Join(" double,", OutputIndicies) + " double)";

                command = new SQLiteCommand(sql, SQLConn);
                command.ExecuteNonQuery();

                //Outputs
                sql = "create table outputs (Name string, Description string, Units string, Controller string)";

                command = new SQLiteCommand(sql, SQLConn);
                command.ExecuteNonQuery();

                StringBuilder sb = new StringBuilder();

                sb.Append("INSERT INTO OUTPUTS (Name, Description , Units, Controller) VALUES ");

                foreach (OutputDataElement ode in OutputDataElements)
                {
                    string comma = ",";

                    if (ode == OutputDataElements.First())
                    {
                        comma = "";
                    }

                    sb.Append(comma + "(\"" + ode.Name + "\",\"" + ode.Output.Description + "\",\"" + ode.Output.Unit + "\",\"" + ode.HLController.GetType().Name + "\")");
                }

                sql = sb.ToString();

                command = new SQLiteCommand(sql, SQLConn);
                command.ExecuteNonQuery();



                //Simulations
                sql = "create table simulations (Id int, Name string, StartDate DATETIME, EndDate DATETIME)";

                command = new SQLiteCommand(sql, SQLConn);
                command.ExecuteNonQuery();

                //Models
                sql = "create table models (SimId int, Name string, InputType string, LongName string)";

                command = new SQLiteCommand(sql, SQLConn);
                command.ExecuteNonQuery();
            }
            else if (OutputType == OutputType.NetCDF)
            {
                //if (HLNC == null)
                //{
                //  //  HLNC = new HLNCFile(this, this.Simulations[0].StartDate, this.Simulations[0].EndDate, FileName.Replace(".hlk", ".nc"));
                //}
            }
            //SQLite

            //Reset the counters
            CurrentSimIndex = 0;
            NoSimsComplete  = 0;

            StartRunTime = DateTime.Now;

            //Create a list of background workers
            BackgroundWorkers = new List <HLBackGroundWorker>(noCoresToUse);

            //Populate the Background workers and run
            for (int i = 0; i < noCoresToUse; i++)
            {
                BackgroundWorkers.Add(new HLBackGroundWorker());
                BackgroundWorkers[i].DoWork             += HLBackgroundWorker_DoWork;
                BackgroundWorkers[i].RunWorkerCompleted += HLBackgroundWorker_RunWorkerCompleted;

                BackgroundWorkers[i].WorkerReportsProgress      = true;
                BackgroundWorkers[i].WorkerSupportsCancellation = true;


                Simulation sim = GetSimulationElement();

                if (sim != null)
                {
                    BackgroundWorkers[i].Sim = sim;
                    // BackgroundWorkers[i].RunWorkerAsync(new List<object>(new object[] { xe, handler }));
                    //BackgroundWorkers[i].RunWorkerAsync(new List<object>(new object[] { sim }));
                    BackgroundWorkers[i].RunWorkerAsync();
                }
            }

            if (HasOwnExecutableSpace)
            {
                while (NoSimsComplete < Simulations.Count)
                {
                    System.Threading.Thread.Sleep(500);
                }
            }
        }
        //---------------------------------------------------------------------

        public static string ReplaceTemplateVars(string template,
                                                 int timestep)
        {
            varValues[TimestepVar] = timestep.ToString();
            return(OutputPath.ReplaceTemplateVars(template, varValues));
        }
 public XilinxSynthesisConfiguration(OutputPath output)
 {
     OutputLocation = output;
 }
        public override void Execute()
        {
            base.Execute();

            if (string.IsNullOrEmpty(Output) || !Directory.Exists(Output))
            {
                Logger.Instance.WriteError("Output Path '{0}' does not exist", Output);
                return;
            }

            GenericSynthesisConfiguration configuration = new GenericSynthesisConfiguration();
            configuration.Module = Program.Repository.FindModuleByName(Module);
            configuration.TargetDevice = DeviceHelper.FindDeviceByName(Device);

            if (configuration.Module == null)
            {
                Logger.Instance.WriteError("Cannot Find Module '{0}'", Module);
                return;
            }
            Logger.Instance.WriteVerbose("Selected module '{0}' in library '{1}'", configuration.Module.Name, configuration.Module.Parent.Name);

            if (configuration.TargetDevice == null)
            {
                Logger.Instance.WriteError("Cannot Find Device '{0}'", Device);
                return;
            }
            Logger.Instance.WriteVerbose("Selected device '{0}'", configuration.TargetDevice.Name);

            OutputPath location = new OutputPath();
            location.OutputDirectory = PathHelper.GetFullPath(Output);
            location.TemporaryDirectory = SystemHelper.GetTemporaryDirectory();
            location.WorkingDirectory = Environment.CurrentDirectory;
            location.LogDirectory = location.OutputDirectory;

            Logger.Instance.WriteVerbose("Starting Build");
            bool successful = false;
            ISynthesizer synthesizer = XilinxHelper.GetCurrentXilinxToolchain().Synthesizers.FirstOrDefault();
            if (synthesizer != null)
            {
                Logger.Instance.WriteDebug("Using '{0}' Synthesizer from '{1}' toolchain", synthesizer.GetType().Name, synthesizer.Toolchain.GetType().Name);
                using (ISynthesizerInstance instance = synthesizer.Create(location, configuration))
                {
                    successful = instance.Build();
                }
            }

            if (successful)
            {
                Logger.Instance.WriteInfo("Build Complete");
            }
            else
            {
                Logger.Instance.WriteError("Build Failed");
            }

            Logger.Instance.WriteVerbose("Cleaning temporary directory");
            Directory.Delete(location.TemporaryDirectory, true);
        }
 public override int GetHashCode()
 {
     return(Items.GetHashCode() ^ OutputPath.GetHashCode() ^ ProgressReporter.GetHashCode());
 }
Exemple #11
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { nameof(AfterMigrationFolderName), AfterMigrationFolderName.to_string() },
                { nameof(AlterDatabaseFolderName), AlterDatabaseFolderName.to_string() },
                { nameof(Baseline), Baseline.to_string() },
                { nameof(BeforeMigrationFolderName), BeforeMigrationFolderName.to_string() },
                { nameof(CommandTimeout), CommandTimeout.to_string() },
                { nameof(CommandTimeoutAdmin), CommandTimeoutAdmin.to_string() },
                { nameof(ConfigurationFile), ConfigurationFile.to_string() },
                { nameof(ConnectionString), ConnectionString.to_string() },
                { nameof(ConnectionStringAdmin), ConnectionStringAdmin.to_string() },
                { nameof(CreateDatabaseCustomScript), CreateDatabaseCustomScript.to_string() },
                { nameof(DatabaseName), DatabaseName.to_string() },
                { nameof(DatabaseType), DatabaseType.to_string() },
                { nameof(Debug), Debug.to_string() },
                { nameof(DisableOutput), DisableOutput.to_string() },
                { nameof(DisableTokenReplacement), DisableTokenReplacement.to_string() },
                { nameof(DoNotAlterDatabase), DoNotAlterDatabase.to_string() },
                { nameof(DoNotCreateDatabase), DoNotCreateDatabase.to_string() },
                { nameof(DoNotStoreScriptsRunText), DoNotStoreScriptsRunText.to_string() },
                { nameof(DownFolderName), DownFolderName.to_string() },
                { nameof(Drop), Drop.to_string() },
                { nameof(DryRun), DryRun.to_string() },
#pragma warning disable 618
                { nameof(EnvironmentName), string.Join(",", EnvironmentNames) },
#pragma warning restore 618
                { nameof(EnvironmentNames), string.Join(",", EnvironmentNames) },
                { nameof(FunctionsFolderName), FunctionsFolderName.to_string() },
                { nameof(IndexesFolderName), IndexesFolderName.to_string() },
                { nameof(Initialize), Initialize.to_string() },
                { nameof(OutputPath), OutputPath.to_string() },
                { nameof(PermissionsFolderName), PermissionsFolderName.to_string() },
                { nameof(RecoveryMode), RecoveryMode.to_string() },
                { nameof(RepositoryPath), RepositoryPath.to_string() },
                { nameof(Restore), Restore.to_string() },
                { nameof(RestoreCustomOptions), RestoreCustomOptions.to_string() },
                { nameof(RestoreFromPath), RestoreFromPath.to_string() },
                { nameof(RestoreTimeout), RestoreTimeout.to_string() },
                { nameof(RunAfterCreateDatabaseFolderName), RunAfterCreateDatabaseFolderName.to_string() },
                { nameof(RunAfterOtherAnyTimeScriptsFolderName), RunAfterOtherAnyTimeScriptsFolderName.to_string() },
                { nameof(RunAllAnyTimeScripts), RunAllAnyTimeScripts.to_string() },
                { nameof(RunBeforeUpFolderName), RunBeforeUpFolderName.to_string() },
                { nameof(RunFirstAfterUpFolderName), RunFirstAfterUpFolderName.to_string() },
                { nameof(SchemaName), SchemaName.to_string() },
                { nameof(ScriptsRunErrorsTableName), ScriptsRunErrorsTableName.to_string() },
                { nameof(ScriptsRunTableName), ScriptsRunTableName.to_string() },
                { nameof(SearchAllSubdirectoriesInsteadOfTraverse), SearchAllSubdirectoriesInsteadOfTraverse.to_string() },
                { nameof(ServerName), ServerName.to_string() },
                { nameof(Silent), Silent.to_string() },
                { nameof(SprocsFolderName), SprocsFolderName.to_string() },
                { nameof(SqlFilesDirectory), SqlFilesDirectory.to_string() },
                { nameof(TriggersFolderName), TriggersFolderName.to_string() },
                { nameof(UpFolderName), UpFolderName.to_string() },
                { nameof(Version), Version.to_string() },
                { nameof(VersionFile), VersionFile.to_string() },
                { nameof(VersionTableName), VersionTableName.to_string() },
                { nameof(VersionXPath), VersionXPath.to_string() },
                { nameof(ViewsFolderName), ViewsFolderName.to_string() },
                { nameof(WarnAndIgnoreOnOneTimeScriptChanges), WarnAndIgnoreOnOneTimeScriptChanges.to_string() },
                { nameof(WarnOnOneTimeScriptChanges), WarnOnOneTimeScriptChanges.to_string() },
                { nameof(WithTransaction), WithTransaction.to_string() },
            };

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
        public override bool Execute()
        {
            if (string.IsNullOrWhiteSpace(UnchangedFiles))
            {
                Log.LogCommandLine("WARNING: UnchangedFiles must be set.");
                return(true);
            }

            if (string.IsNullOrWhiteSpace(OutputPath))
            {
                Log.LogCommandLine("WARNING: OutputPath must be set.");
                return(true);
            }

            Log.LogCommandLine("! CullFilesFromProject Task !");
            Log.LogCommandLine("OutputPath: " + OutputPath);
            Log.LogCommandLine("UnchangedFiles: " + UnchangedFiles);

            var normalizedFiles = File.ReadAllLines(UnchangedFiles).Select(i => i.Replace("/", @"\")).ToArray();

            var normalizedOutputDir = (OutputPath?.Replace("\\\\", "\\")).TrimEnd('\\');

            foreach (var file in Directory.EnumerateFiles(normalizedOutputDir, "*.*", SearchOption.AllDirectories))
            {
                // do not delete config files or xml files as they may be transformed
                if (file.EndsWith(".config") || file.EndsWith(".xml"))
                {
                    continue;
                }

                // need to search /bin for *.dll files
                if (file.EndsWith(".dll"))
                {
                    var dllOnly = file.Split('\\').Last();

                    if (!normalizedFiles.Any(i => i.EndsWith(dllOnly)))
                    {
                        continue;
                    }

                    File.Delete(file);
                    Log.LogCommandLine("CullFilesFromProject :: Deleted file: " + file);
                    continue;
                }

                var relativeFilePath = file.Replace(normalizedOutputDir, "");

                if (!normalizedFiles.Any(i => i.EndsWith(relativeFilePath)))
                {
                    continue;
                }

                File.Delete(file);
                Log.LogCommandLine("CullFilesFromProject :: Deleted file: " + file);
            }

            foreach (var directory in Directory.EnumerateDirectories(normalizedOutputDir, "*", SearchOption.AllDirectories).OrderByDescending(i => i.Length))
            {
                if (Directory.GetFiles(directory).Length != 0 || Directory.GetDirectories(directory).Length != 0)
                {
                    continue;
                }

                Directory.Delete(directory, false);
                Log.LogCommandLine("CullFilesFromProject :: Deleted empty directory: " + directory);
            }

            return(true);
        }
 public BitstreamDataInjector(OutputPath output)
 {
     OutputLocation = output;
 }
Exemple #14
0
        public override bool Start()
        {
            #region Set exe files path

            if (this.IsNodeInPath)
            {
                this.NodeJsPath = FindInPath.Find("node.exe", MainWindow.WorkingDirectory, false);
            }
            if (this.IsCoffeeGlobal)
            {
                CoffeePath = FindInPath.Find("coffee", MainWindow.WorkingDirectory, true, false);
                if (CoffeePath.EndsWith(".bat", StringComparison.OrdinalIgnoreCase) || CoffeePath.EndsWith(".cmd", StringComparison.OrdinalIgnoreCase) || CoffeePath.EndsWith(".com", StringComparison.OrdinalIgnoreCase))
                {
                    HashSet <string> possibleCoffeeLocations = FindPathInfo.InBat("%~dp0\\.\\", "coffee", CoffeePath);
                    if (possibleCoffeeLocations != null)
                    {
                        foreach (string possibleCoffeeLocation in possibleCoffeeLocations)
                        {
                            string temp         = possibleCoffeeLocation.Replace("%~dp0\\.\\", string.Empty);
                            string tempFullPath = Path.GetDirectoryName(CoffeePath) + Path.DirectorySeparatorChar + temp;
                            if (File.Exists(tempFullPath))
                            {
                                CoffeePath = tempFullPath;
                                break;
                            }
                        }
                    }
                }
                ;
            }
            fileName  = this.NodeJsPath;
            arguments = "\"" + PathConverter.ConvertWinToUnix(this.CoffeePath) + "\"";

            #endregion

            #region Merge paths

            InputPath = !String.IsNullOrEmpty(InputPath) ? PathConverter.ConvertUnixToWin(InputPath) : ".";
            if (Directory.Exists(InputPath))
            {
                if (InputPath[InputPath.Length - 1] != '\\')
                {
                    InputPath += '\\';
                }
            }
            if (Directory.Exists(OutputPath))
            {
                if (OutputPath[OutputPath.Length - 1] != '\\')
                {
                    OutputPath += '\\';
                }
            }
            if (String.IsNullOrEmpty(OutputPath))
            {
                workingDirectory = Path.GetDirectoryName(InputPath);
                InputPath        = PathConverter.ConvertWinToUnix(Path.GetFileName(InputPath));
                OutputPath       = PathConverter.ConvertWinToUnix(Path.GetFileName(OutputPath));
            }
            else
            {
                workingDirectory = ComparePath.Compare(InputPath, OutputPath, '\\');
                int headerIndex = workingDirectory.Length;
                InputPath  = PathConverter.ConvertWinToUnix(InputPath.Substring(headerIndex));
                OutputPath = PathConverter.ConvertWinToUnix(OutputPath.Substring(headerIndex));
            }
            if (String.IsNullOrEmpty(InputPath))
            {
                InputPath = ".";
            }
            if (String.IsNullOrEmpty(OutputPath))
            {
                OutputPath = ".";
            }

            #endregion

            #region Set arguments

            arguments += " " + this.AddParams;
            if (this.IsBare)
            {
                arguments += " --bare";
            }
            if (this.IsWatch)
            {
                arguments += " --watch";
            }
            arguments += " --compile";
            if (!String.IsNullOrEmpty(OutputPath))
            {
                arguments += " --output " + this.OutputPath;
            }
            arguments += " " + this.InputPath;

            #endregion

            #region Set process properties

            setupInfo(fileName, arguments, workingDirectory);

            return(run());

            #endregion
        }
Exemple #15
0
        /// <summary>
        /// Start processing the compositions.
        /// </summary>
        /// <returns>Number of successful conversions</returns>
        public int Process()
        {
            if (Compositions == null || FFmpegPath == null)
            {
                return(0);
            }
            int finished = 0;

            failures = new StringBuilder();
            foreach (string composition in Compositions)
            {
                if (!File.Exists(composition))
                {
                    continue;
                }
                string title = Finder.GetCPLTitle(composition);
                OnStatusUpdate?.Invoke($"Processing {title}...");
                string finalOutput = OutputPath, sourceFolder = composition.Substring(0, composition.LastIndexOf('\\'));
                if (!string.IsNullOrEmpty(OutputPath) && OutputPath.Equals(parentMarker))
                {
                    int index = sourceFolder.LastIndexOf('\\');
                    if (index < 0)
                    {
                        failures.AppendLine("Drive root is an invalid directory: " + title);
                        continue;
                    }
                    finalOutput = sourceFolder.Substring(0, index);
                }
                CompositionProcessor processor = new CompositionProcessor(FFmpegPath, composition)
                {
                    ForcePath         = finalOutput,
                    Overwrite         = Overwrite,
                    VideoFormat       = VideoFormat,
                    ChromaSubsampling = ChromaSubsampling,
                    CRF         = CRF,
                    CRF3D       = CRF3D,
                    StereoMode  = StereoMode,
                    AudioFormat = AudioFormat
                };
                if (processor.ProcessComposition(Force2K))
                {
                    ++finished;
                    if (ZipAfter)
                    {
                        OnStatusUpdate?.Invoke($"Zipping {title}...");
                        Finder.ZipAssets(sourceFolder, $"{finalOutput}\\{title}.zip", textOut => OnStatusUpdate(textOut));
                    }
                    if (DeleteAfter)
                    {
                        Finder.DeleteAssets(sourceFolder);
                    }
                }
                else
                {
                    failures.AppendLine("Conversion error: " + title);
                }
            }
            OnStatusUpdate?.Invoke("Finished!");
            OnCompletion?.Invoke(finished);
            return(finished);
        }
 public FPGAImplementorInstance(FPGAImplementor implementor, OutputPath output, IImplementationConfiguration config)
 {
     Implementor = implementor;
     OutputLocation = output;
     Configuration = config;
 }
Exemple #17
0
        /// <summary>
        /// 执行制定生成
        /// </summary>
        /// <param name="op"></param>
        public void Run(string op)
        {
            if (AppPath == null)
            {
                return;
            }

            var path = Path.Combine(OutputPath, CurrentOption + ".cs");

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

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName               = "cmd.exe";
            p.StartInfo.UseShellExecute        = false; //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput  = true;  //接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
            p.StartInfo.RedirectStandardError  = true;  //重定向标准错误输出
            p.StartInfo.CreateNoWindow         = true;  //不显示程序窗口
            p.Start();                                  //启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(AppPath.Replace("\\", "/") + " --csharp_out=\"" + OutputPath.Replace("\\", "/") + "/\" --proto_path=\"" + SourcesPath.Replace("\\", "/") + "/\" " + op + ".proto" + "&exit");
            p.StandardInput.AutoFlush = true;

            var ans = p.WaitForExit(1000);

            p.Close();

            if (!ans)
            {
                GenerateText.Text = "";
                return;
            }

            //Log(op + "生成完成." );

            path = Path.Combine(OutputPath, CurrentOption + ".cs");
            if (File.Exists(path))
            {
                var text  = File.ReadAllText(path);
                var index = GenerateText.CaretOffset;
                GenerateText.Text        = text.Replace("global::Google.Protobuf", "global::Secode.Protobuf");
                GenerateText.CaretOffset = index;
                File.WriteAllText(path, GenerateText.Text);
            }
        }
Exemple #18
0
        public override bool Execute()
        {
            OutputPath = OutputPath.Replace('\\', '/');
            Directory.CreateDirectory(Path.GetDirectoryName(OutputPath));

            DependencyVersionsFile depsFile;

            if (File.Exists(OutputPath))
            {
                if (!DependencyVersionsFile.TryLoad(OutputPath, out depsFile))
                {
                    depsFile = DependencyVersionsFile.Create(AddOverrideImport, AdditionalImports);
                    Log.LogWarning($"Could not load the existing deps file from {OutputPath}. This file will be overwritten.");
                }
            }
            else
            {
                depsFile = DependencyVersionsFile.Create(AddOverrideImport, AdditionalImports);
            }

            var varNames = new HashSet <string>();

            foreach (var pkg in Packages)
            {
                var packageVersion = pkg.GetMetadata("Version");

                if (string.IsNullOrEmpty(packageVersion))
                {
                    Log.LogError("Package {0} is missing the Version metadata", pkg.ItemSpec);
                    continue;
                }

                string packageVarName;
                if (!string.IsNullOrEmpty(pkg.GetMetadata("VariableName")))
                {
                    packageVarName = pkg.GetMetadata("VariableName");
                    if (!packageVarName.EndsWith("Version", StringComparison.Ordinal))
                    {
                        Log.LogError("VariableName for {0} must end in 'Version'", pkg.ItemSpec);
                        continue;
                    }
                }
                else
                {
                    packageVarName = DependencyVersionsFile.GetVariableName(pkg.ItemSpec);
                }

                if (varNames.Contains(packageVarName))
                {
                    Log.LogError("Multiple packages would produce {0} in the generated dependencies.props file. Set VariableName to differentiate the packages manually", packageVarName);
                    continue;
                }

                var item = depsFile.Update(packageVarName, packageVersion);
                if (!SuppressVariableLabels)
                {
                    item.SetLabel(pkg.ItemSpec);
                }
            }

            depsFile.Save(OutputPath);
            Log.LogMessage(MessageImportance.Normal, $"Generated {OutputPath}");
            return(!Log.HasLoggedErrors);
        }
        /// <summary>
        /// Run the predictor with given args and check if it adds up
        /// </summary>
        protected void Run(RunContext ctx)
        {
            Contracts.Assert(IsActive);
            List <string> args = new List <string>();

            if (ctx.Command != Cmd.Test)
            {
                AddIfNotEmpty(args, ctx.Predictor.Trainer, "tr");
            }
            string dataName = ctx.Command == Cmd.Test ? ctx.Dataset.testFilename : ctx.Dataset.trainFilename;

            AddIfNotEmpty(args, GetDataPath(dataName), "data");
            AddIfNotEmpty(args, 1, "seed");
            //AddIfNotEmpty(args, false, "threads");

            Log("Running '{0}' on '{1}'", ctx.Predictor.Trainer.Kind, ctx.Dataset.name);

            string dir = ctx.BaselineDir;

            if (ctx.Command == Cmd.TrainTest)
            {
                AddIfNotEmpty(args, GetDataPath(ctx.Dataset.testFilename), "test");
            }
            if (ctx.Command == Cmd.TrainTest || ctx.Command == Cmd.Train)
            {
                AddIfNotEmpty(args, GetDataPath(ctx.Dataset.validFilename), "valid");
            }

            // Add in the loader args, and keep a location so we can backtrack and remove it later.
            int    loaderArgIndex = -1;
            string loaderArgs     = GetLoaderTransformSettings(ctx.Dataset);

            if (!string.IsNullOrWhiteSpace(loaderArgs))
            {
                loaderArgIndex = args.Count;
                args.Add(loaderArgs);
            }
            // Add in the dataset transforms. These need to come before the predictor imposed transforms.
            if (ctx.Dataset.mamlExtraSettings != null)
            {
                args.AddRange(ctx.Dataset.mamlExtraSettings);
            }

            // Model file output, used only for train/traintest.
            var modelPath = ctx.Command == Cmd.Train || ctx.Command == Cmd.TrainTest ? ctx.ModelPath() : null;

            AddIfNotEmpty(args, modelPath, "out");

            string basePrefix = ctx.BaselineNamePrefix;

            // Predictions output, for all types of commands except train.
            OutputPath predOutPath = ctx.Command == Cmd.Train ? null : ctx.InitPath(".txt");

            AddIfNotEmpty(args, predOutPath, "dout");

            if (ctx.Predictor.MamlArgs != null)
            {
                args.AddRange(ctx.Predictor.MamlArgs);
            }

            // If CV, do not run the CV in multiple threads.
            if (ctx.Command == Cmd.CV)
            {
                args.Add("threads-");
            }

            if (ctx.ExtraArgs != null)
            {
                foreach (string arg in ctx.ExtraArgs)
                {
                    args.Add(arg);
                }
            }

            AddIfNotEmpty(args, ctx.Predictor.Scorer, "scorer");
            if (ctx.Command != Cmd.Test)
            {
                AddIfNotEmpty(args, ctx.Predictor.Tester, "eval");
            }
            else
            {
                AddIfNotEmpty(args, ctx.ModelOverride.Path, "in");
            }

            string runcmd = string.Join(" ", args.Where(a => !string.IsNullOrWhiteSpace(a)));

            Log("  Running as: {0} {1}", ctx.Command, runcmd);

            int res;

            if (basePrefix == null)
            {
                // Not capturing into a specific log.
                Log("*** Start raw predictor output");
                res = MainForTest(Env, LogWriter, string.Join(" ", ctx.Command, runcmd), ctx.BaselineProgress);
                Log("*** End raw predictor output, return={0}", res);
                return;
            }
            var consOutPath = ctx.StdoutPath();

            TestCore(ctx, ctx.Command.ToString(), runcmd);
            bool matched = consOutPath.CheckEqualityNormalized();

            if (modelPath != null && (ctx.Summary || ctx.SaveAsIni))
            {
                // Save the predictor summary and compare it to baseline.
                string        str   = string.Format("SavePredictorAs in={{{0}}}", modelPath.Path);
                List <string> files = new List <string>();
                if (ctx.Summary)
                {
                    var summaryName = basePrefix + "-summary.txt";
                    files.Add(summaryName);
                    var summaryPath = DeleteOutputPath(dir, summaryName);
                    str += string.Format(" sum={{{0}}}", summaryPath);
                    Log("  Saving summary with: {0}", str);
                }

                if (ctx.SaveAsIni)
                {
                    var iniName = basePrefix + ".ini";
                    files.Add(iniName);
                    var iniPath = DeleteOutputPath(dir, iniName);
                    str += string.Format(" ini={{{0}}}", iniPath);
                    Log("  Saving ini file: {0}", str);
                }

                MainForTest(Env, LogWriter, str);
                files.ForEach(file => CheckEqualityNormalized(dir, file));
            }

            if (ctx.Command == Cmd.Train || ctx.Command == Cmd.Test || ctx.ExpectedToFail)
            {
                return;
            }

            // ResultProcessor output
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // -rp.txt files are not getting generated for Non-Windows Os
            {
                string rpName    = basePrefix + "-rp.txt";
                string rpOutPath = DeleteOutputPath(dir, rpName);

                string[] rpArgs = null;
                if (ctx.Command == Cmd.CV && ctx.ExtraArgs != null && ctx.ExtraArgs.Any(arg => arg.Contains("opf+")))
                {
                    rpArgs = new string[] { "opf+" }
                }
                ;

                // Run result processor on the console output.
                RunResultProcessorTest(new string[] { consOutPath.Path }, rpOutPath, rpArgs);
                CheckEqualityNormalized(dir, rpName);
            }

            // Check the prediction output against its baseline.
            Contracts.Assert(predOutPath != null);
            predOutPath.CheckEquality();

            if (ctx.Command == Cmd.TrainTest)
            {
                // Adjust the args so that we no longer have the loader and transform
                // arguments in there.
                if (loaderArgIndex >= 0)
                {
                    args.RemoveAt(loaderArgIndex);
                }
                bool             foundOut   = false;
                List <int>       toRemove   = new List <int>();
                HashSet <string> removeArgs = new HashSet <string>();
                removeArgs.Add("tr=");
                removeArgs.Add("data=");
                removeArgs.Add("valid=");
                removeArgs.Add("norm=");
                removeArgs.Add("cali=");
                removeArgs.Add("numcali=");
                removeArgs.Add("xf=");
                removeArgs.Add("cache-");
                removeArgs.Add("sf=");

                for (int i = 0; i < args.Count; ++i)
                {
                    if (string.IsNullOrWhiteSpace(args[i]))
                    {
                        continue;
                    }
                    if (removeArgs.Any(x => args[i].StartsWith(x)))
                    {
                        toRemove.Add(i);
                    }
                    if (args[i].StartsWith("out="))
                    {
                        args[i] = string.Format("in={0}", args[i].Substring(4));
                    }
                    if (args[i].StartsWith("test="))
                    {
                        args[i] = string.Format("data={0}", args[i].Substring(5));
                    }
                    foundOut = true;
                }
                Contracts.Assert(foundOut);
                toRemove.Reverse();
                foreach (int i in toRemove)
                {
                    args.RemoveAt(i);
                }
                runcmd = string.Join(" ", args.Where(a => !string.IsNullOrWhiteSpace(a)));

                // Redirect output to the individual log and run the test.
                var        ctx2         = ctx.TestCtx();
                OutputPath consOutPath2 = ctx2.StdoutPath();
                TestCore(ctx2, "Test", runcmd);

                if (CheckTestOutputMatchesTrainTest(consOutPath.Path, consOutPath2.Path, 1))
                {
                    File.Delete(consOutPath2.Path);
                }
                else if (matched)
                {
                    // The TrainTest output matched the baseline, but the SaveLoadTest output did not, so
                    // append some stuff to the .txt output so comparing output to baselines in BeyondCompare
                    // will show the issue.
                    using (var writer = OpenWriter(consOutPath.Path, true))
                    {
                        writer.WriteLine("*** Unit Test Failure! ***");
                        writer.WriteLine("Loaded predictor test results differ! Compare baseline with {0}", consOutPath2.Path);
                        writer.WriteLine("*** Unit Test Failure! ***");
                    }
                }
                // REVIEW: There is nothing analogous to the old predictor output comparison here.
                // The MAML command does not "export" the result of its training programmatically, that would
                // allow us to compare it to the loaded model. To verify that the result of the trained model
                // is the same as its programmatic
            }
        }
 public IImplementorInstance Create(OutputPath output, IImplementationConfiguration configuration)
 {
     return new FPGAImplementorInstance(this, output, configuration);
 }
        public override bool Execute()
        {
            if (!Enum.TryParse(OutputType, true, out m_OutputType))
            {
                Log.LogError("Unrecognized OutputType {0}", OutputType);
                return(false);
            }

            if (!Enum.TryParse(Platform, true, out m_Platform))
            {
                Log.LogError("Unrecognized Platform {0}", Platform);
                return(false);
            }

            m_responseFile = Path.GetTempFileName();
            List <string> argv = new List <string>();

            argv.Add("-nologo");
            argv.Add("-version:1.8");
            argv.Add("-w4");

            switch (m_OutputType)
            {
            case ParsedOutputType.Exe:
                argv.Add("-target:exe");
                break;

            case ParsedOutputType.WinExe:
                argv.Add("-target:winexe");
                break;

            case ParsedOutputType.Library:
                argv.Add("-target:library");
                break;
            }

            switch (m_Platform)
            {
            case ParsedPlatform.AnyCpu:
                argv.Add("-platform:anycpu");
                break;

            case ParsedPlatform.AnyCpuPrefer32Bit:
                argv.Add("-platform:anycpu32bitpreferred");
                break;

            case ParsedPlatform.ARM:
                argv.Add("-platform:arm");
                break;

            case ParsedPlatform.x64:
                argv.Add("-platform:x64");
                break;

            case ParsedPlatform.x86:
                argv.Add("-platform:x86");
                break;
            }

            if (!string.IsNullOrEmpty(Version))
            {
                argv.Add("-version:" + Version);
            }
            if (!string.IsNullOrEmpty(FileVersion))
            {
                argv.Add("-fileversion:" + FileVersion);
            }
            if (!string.IsNullOrEmpty(ApplicationIcon))
            {
                argv.Add("-win32icon:" + ApplicationIcon);
            }
            if (!string.IsNullOrEmpty(Win32Manifest))
            {
                argv.Add("-win32manifest:" + Win32Manifest);
            }

            argv.AddRange(NoWarn.Select(x => "-nowarn:" + x));
            if (CompressResources)
            {
                argv.Add("-compressresources");
            }
            if (StrictFieldSemantics)
            {
                argv.Add("-strictfinalfieldsemantics");
            }
            if (RemoveAssertions)
            {
                argv.Add("-removeassertions");
            }
            if (SharedClassLoader)
            {
                argv.Add("-sharedclassloader");
            }
            if (SuppressParameterReflection)
            {
                argv.Add("-noparameterreflection");
            }
            argv.AddRange(ExtraArguments ?? Enumerable.Empty <string>());
            argv.Add("-highentropyva"); // for security

            argv.Add("-out:" + OutputPath.GetMetadata("FullPath"));
            // Don't use FullPath here, as some of these might be bare filenames, and those must be preserved.
            argv.AddRange(References?.Select(x => "-r:" + x.ItemSpec) ?? Enumerable.Empty <string>());
            argv.AddRange(ClassFiles?.Select(x => x.GetMetadata("FullPath")) ?? Enumerable.Empty <string>());

            File.WriteAllLines(m_responseFile, argv);
            bool taskSuccess = base.Execute();

            if (taskSuccess)
            {
                DeleteTempFile(m_responseFile);
            }
            else
            {
                Log.LogMessage(MessageImportance.High, "Migrator arguments can be found here: {0}", m_responseFile);
            }

            return(taskSuccess);
        }
Exemple #22
0
 private protected IDisposable TemporarySetPackageVersion(SVersion version, bool targetOutputPath = false)
 {
     return(TempFileTextModification.TemporaryReplacePackageVersion(!targetOutputPath ? PackageJson.JsonFilePath : OutputPath.AppendPart("package.json"), version));
 }
Exemple #23
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            tokens["AfterMigrationFolderName"] = AfterMigrationFolderName.to_string();
            tokens["AlterDatabaseFolderName"]  = AlterDatabaseFolderName.to_string();
            tokens["Baseline"] = Baseline.to_string();
            tokens["BeforeMigrationFolderName"]  = BeforeMigrationFolderName.to_string();
            tokens["CommandTimeout"]             = CommandTimeout.to_string();
            tokens["CommandTimeoutAdmin"]        = CommandTimeoutAdmin.to_string();
            tokens["ConfigurationFile"]          = ConfigurationFile.to_string();
            tokens["ConnectionString"]           = ConnectionString.to_string();
            tokens["ConnectionStringAdmin"]      = ConnectionStringAdmin.to_string();
            tokens["CreateDatabaseCustomScript"] = CreateDatabaseCustomScript.to_string();
            tokens["DatabaseName"]             = DatabaseName.to_string();
            tokens["DatabaseType"]             = DatabaseType.to_string();
            tokens["Debug"]                    = Debug.to_string();
            tokens["DisableOutput"]            = DisableOutput.to_string();
            tokens["DisableTokenReplacement"]  = DisableTokenReplacement.to_string();
            tokens["DoNotAlterDatabase"]       = DoNotAlterDatabase.to_string();
            tokens["DoNotCreateDatabase"]      = DoNotCreateDatabase.to_string();
            tokens["DoNotStoreScriptsRunText"] = DoNotStoreScriptsRunText.to_string();
            tokens["DownFolderName"]           = DownFolderName.to_string();
            tokens["Drop"]                                     = Drop.to_string();
            tokens["DryRun"]                                   = DryRun.to_string();
            tokens["EnvironmentName"]                          = string.Join(",", EnvironmentNames);
            tokens["EnvironmentNames"]                         = string.Join(",", EnvironmentNames);
            tokens["FunctionsFolderName"]                      = FunctionsFolderName.to_string();
            tokens["IndexesFolderName"]                        = IndexesFolderName.to_string();
            tokens["Initialize"]                               = Initialize.to_string();
            tokens["OutputPath"]                               = OutputPath.to_string();
            tokens["PermissionsFolderName"]                    = PermissionsFolderName.to_string();
            tokens["RecoveryMode"]                             = RecoveryMode.to_string();
            tokens["RepositoryPath"]                           = RepositoryPath.to_string();
            tokens["Restore"]                                  = Restore.to_string();
            tokens["RestoreCustomOptions"]                     = RestoreCustomOptions.to_string();
            tokens["RestoreFromPath"]                          = RestoreFromPath.to_string();
            tokens["RestoreTimeout"]                           = RestoreTimeout.to_string();
            tokens["RunAfterCreateDatabaseFolderName"]         = RunAfterCreateDatabaseFolderName.to_string();
            tokens["RunAfterOtherAnyTimeScriptsFolderName"]    = RunAfterOtherAnyTimeScriptsFolderName.to_string();
            tokens["RunAllAnyTimeScripts"]                     = RunAllAnyTimeScripts.to_string();
            tokens["RunBeforeUpFolderName"]                    = RunBeforeUpFolderName.to_string();
            tokens["RunFirstAfterUpFolderName"]                = RunFirstAfterUpFolderName.to_string();
            tokens["SchemaName"]                               = SchemaName.to_string();
            tokens["ScriptsRunErrorsTableName"]                = ScriptsRunErrorsTableName.to_string();
            tokens["ScriptsRunTableName"]                      = ScriptsRunTableName.to_string();
            tokens["SearchAllSubdirectoriesInsteadOfTraverse"] = SearchAllSubdirectoriesInsteadOfTraverse.to_string();
            tokens["ServerName"]                               = ServerName.to_string();
            tokens["Silent"]                                   = Silent.to_string();
            tokens["SprocsFolderName"]                         = SprocsFolderName.to_string();
            tokens["SqlFilesDirectory"]                        = SqlFilesDirectory.to_string();
            tokens["TriggersFolderName"]                       = TriggersFolderName.to_string();
            tokens["UpFolderName"]                             = UpFolderName.to_string();
            tokens["Version"]                                  = Version.to_string();
            tokens["VersionFile"]                              = VersionFile.to_string();
            tokens["VersionTableName"]                         = VersionTableName.to_string();
            tokens["VersionXPath"]                             = VersionXPath.to_string();
            tokens["ViewsFolderName"]                          = ViewsFolderName.to_string();
            tokens["WarnAndIgnoreOnOneTimeScriptChanges"]      = WarnAndIgnoreOnOneTimeScriptChanges.to_string();
            tokens["WarnOnOneTimeScriptChanges"]               = WarnOnOneTimeScriptChanges.to_string();
            tokens["WithTransaction"]                          = WithTransaction.to_string();

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
Exemple #24
0
 private protected IDisposable TemporaryPrePack(SVersion version, Action <JObject> packageJsonPreProcessor, bool ckliLocalFeedMode)
 {
     return(TempFileTextModification.TemporaryReplaceDependenciesVersion(NpmSolution, OutputPath.AppendPart("package.json"), ckliLocalFeedMode, version, packageJsonPreProcessor));
 }
Exemple #25
0
        private void CopyValidFilesToOutFolder(string basePath, string outFolder, IEnumerable <ValidFileContents> validFileContents)
        {
            var outputPath = new OutputPath(basePath, outFolder);

            _validFileContentsWriter.WriteValidFileContents(outputPath, validFileContents);
        }
 public BitstreamGenerator(XilinxToolchain toolchain, OutputPath output, string ncd)
 {
     Toolchain = toolchain;
     OutputLocation = output;
     NCDFile = ncd;
 }
 //---------------------------------------------------------------------
 public static string ReplaceTemplateVars(string template,
                                          string agentName)
 {
     varValues[AgentNameVar] = agentName;
     return(OutputPath.ReplaceTemplateVars(template, varValues));
 }
Exemple #28
0
 public NGDBuilder(XilinxToolchain toolchain, OutputPath output)
 {
     Toolchain = toolchain;
     OutputLocation = output;
 }
Exemple #29
0
 //---------------------------------------------------------------------
 public static string ReplaceTemplateVars(string template,
                                          string insectName)
 {
     varValues[InsectNameVar] = insectName;
     return(OutputPath.ReplaceTemplateVars(template, varValues));
 }
Exemple #30
0
        internal bool Run(out string errors)
        {
            errors = null;

            if (RawMarkdown != null)
            {
                RawMarkdown = RawMarkdown.Replace("\\r\\n", "\\n").Replace("\\n", "\n");
                var f = RawMarkdown.ToHtml();
                //if this.OutputPath != null
                if (!DryRun)
                {
                    Console.WriteLine(f);
                }
                else
                {
                    Console.WriteLine("(dryrun)" + f);
                }
                return(true);
            }

            if (FileName != null)
            {
                return(Generate(FileName, OutputPath, InputPath, NoTemplate, DefaultTemplate, DryRun, out errors));
            }

            if (InputPath != null)
            {
                foreach (var f in Directory.EnumerateFiles(InputPath, "*.*", Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
                {
                    if (Path.GetExtension(f).ToLowerInvariant() == ".md")
                    {
                        var result = Generate(f, OutputPath, InputPath, NoTemplate, DefaultTemplate, DryRun, out errors);
                        if (!result)
                        {
                            return(false);
                        }
                    }
                    else if (   //todo:linux case sensitive, todo: configurable set
                        !f.Contains("\\.git\\") && //todo:linux path separator
                        Path.GetExtension(f).ToLowerInvariant() != ".html" &&
                        Path.GetExtension(f).ToLowerInvariant() != ".clowncar" &&
                        Path.GetExtension(f).ToLowerInvariant() != ".clowntent" &&
                        Path.GetExtension(f).ToLowerInvariant() != ".gitignore" &&
                        Path.GetExtension(f).ToLowerInvariant() != ".pre" &&
                        Path.GetExtension(f).ToLowerInvariant() != ".ok" &&
                        Path.GetExtension(f).ToLowerInvariant() != ".ps1")
                    {
                        if (!string.IsNullOrWhiteSpace(OutputPath))
                        {
                            var inputFilePath  = Path.GetDirectoryName(f);
                            var relativePath   = Path.GetRelativePath(InputPath, inputFilePath);
                            var targetFileName = Path.Combine(OutputPath, relativePath, Path.GetFileName(f));
                            // don't copy anything FROM the output path.....
                            //TODO: depends if OS is case-insensitive
                            if (inputFilePath.ToLowerInvariant().StartsWith(OutputPath.ToLowerInvariant() + "/"))
                            {
                                Console.WriteLine("sub-site:");
                                continue;
                            }
                            if (!DryRun)
                            {
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.WriteLine($"++> {Path.Combine(relativePath, targetFileName)}");
                                Console.ResetColor();
                                File.Copy(f, targetFileName, true);
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.WriteLine($"(dryrun)++> {Path.Combine(relativePath, targetFileName)}");
                                Console.ResetColor();
                            }
                        }
                    }
                    else
                    {
                        var inputFilePath  = Path.GetDirectoryName(f);
                        var relativePath   = Path.GetRelativePath(InputPath, inputFilePath);
                        var targetFileName = Path.Combine(OutputPath, relativePath, Path.GetFileName(f));

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        if (!DryRun)
                        {
                            Console.WriteLine($"xx> (skipped) {Path.Combine(relativePath, targetFileName)}");
                        }
                        else
                        {
                            Console.WriteLine($"(dryrun)xx> (skipped) {Path.Combine(relativePath, targetFileName)}");
                        }
                        Console.ResetColor();
                    }
                }
            }

            return(true);
        }
        public void AddPorcelain <ApiClient>(CommandLineApplication app, IClientFactory <ApiClient> clientFactory)
        {
            var properties = clientFactory.GetProperties();

            properties.ToList().ForEach(prop =>
            {
                var groupType = prop.PropertyType;
                var groupName = groupType.Name.Substring(0, groupType.Name.Length - 3).Substring(1);
                var methods   = groupType.GetMethods();
                methods.ToList().ForEach(m =>
                {
                    var methodName  = m.Name;
                    var commandName = $"{methodName}".ToKebabCase();
                    if (commandName.EndsWith("-"))
                    {
                        commandName = commandName.Substring(0, commandName.Length - 1);
                    }

                    var parameters = m.GetParameters().Where(param => !param.Name.ToLower().Equals("useragent"));
                    app.Command(commandName, (command) =>
                    {
                        command.Description = $"Porcelain command for {methodName.ToText()} Api";

                        command.HelpOption("-?|-h|--help");

                        // standard options
                        var apiToken       = new Token();
                        var apiTokenOption = command.Option(apiToken.Template,
                                                            apiToken.Description,
                                                            apiToken.OptionType);

                        var indent = new Indent();
                        command.Option(indent.Template,
                                       indent.Description,
                                       indent.OptionType);

                        var outputPath = new OutputPath();
                        command.Option(outputPath.Template,
                                       outputPath.Description,
                                       outputPath.OptionType);

                        var filter = new Filter();
                        command.Option(filter.Template,
                                       filter.Description,
                                       filter.OptionType);

                        var options = new List <CommandOption>();
                        parameters.ToList().ForEach(param =>
                        {
                            var paramName = $"--{param.Name}";
                            var paramDesc = $"The {param.Name}";
                            var option    = command.Option(paramName, paramDesc, CommandOptionType.SingleValue);
                            options.Add(option);
                        });

                        command.OnExecute(() =>
                        {
                            return(command.Run(
                                       app,
                                       () =>
                            {
                                var client = clientFactory.GetClient(apiTokenOption.Value());

                                var api = GetApi(client, prop);

                                var method = api.GetType().GetMethod(m.Name);

                                List <object> args = CompileRequestArgs <ApiClient>(app, clientFactory, options);

                                return InvokeRequest(api, method, args);
                            }
                                       ));
                        });
                    });
                });
            });
        }
Exemple #32
0
        private Boolean Validate()
        {
            String outputDirectory = OutputPath.Substring(0, OutputPath.LastIndexOf('\\') == -1 ? 0:OutputPath.LastIndexOf('\\'));

            return(File.Exists(InputPath) && Directory.Exists(outputDirectory) && SelectedType != -1);
        }
Exemple #33
0
        //---------------------------------------------------------------------

        public static string ReplaceTemplateVars(string template,
                                                 string speciesMapName)
        {
            varValues[SpeciesNameVar] = speciesMapName;
            return(OutputPath.ReplaceTemplateVars(template, varValues));
        }
    private static string AutoGenerateFilename(OutputPath outputPathType, string path, string filename)
    {
        // Create folder
        string fileFolder = string.Empty;
        if (outputPathType == OutputPath.RelativeToProject)
        {
            string projectFolder = System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, ".."));
            fileFolder = System.IO.Path.Combine(projectFolder, path);
        }
        else if (outputPathType == OutputPath.Absolute)
        {
            fileFolder = path;
        }

        // Combine path and filename
        return System.IO.Path.Combine(fileFolder, filename);
    }
Exemple #35
0
        //---------------------------------------------------------------------

        public static void CheckTemplateVars(string template)
        {
            OutputPath.CheckTemplateVars(template, knownVars);
        }
Exemple #36
0
 public FileWriter(OutputPath outputPath)
 {
     _outputPath = outputPath;
 }
 public ISynthesizerInstance Create(OutputPath output, ISynthesisConfiguration configuration)
 {
     return new XSTInstance(this, output, configuration);
 }
 public PlaceAndRouter(XilinxToolchain toolchain, OutputPath output)
 {
     Toolchain = toolchain;
     OutputLocation = output;
 }
    private static string ManualGenerateFilename(OutputPath outputPathType, string path, string filename)
    {
        string result = filename;

        if (outputPathType == OutputPath.RelativeToProject)
        {
            if (!System.IO.Path.IsPathRooted(filename) && !System.IO.Path.IsPathRooted(path))
            {
                string projectFolder = System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, ".."));
                result = System.IO.Path.Combine(System.IO.Path.Combine(projectFolder, path), filename);
            }
        }
        else if (outputPathType == OutputPath.Absolute)
        {
            if (!System.IO.Path.IsPathRooted(filename))
            {
                result = System.IO.Path.Combine(path, filename);
            }
        }

        return result;
    }
Exemple #40
0
        public override bool Execute()
        {
            if (!Directory.Exists(OutputPath))
            {
                Log.LogError($"OutputPath not found: {OutputPath}");
                return(false);
            }

            var modInfoPath = Path.Combine(OutputPath, "info.json");

            if (!File.Exists(modInfoPath))
            {
                // Unix FS is case sensitive
                modInfoPath = Path.Combine(OutputPath, "Info.json");
                if (!File.Exists(modInfoPath))
                {
                    Log.LogError($"Mod Info.json not found: {modInfoPath}");
                    return(false);
                }
            }

            ModInfo modInfo = null;

            try
            {
                modInfo = JsonConvert.DeserializeObject <ModInfo>(File.ReadAllText(modInfoPath));
                modInfo.Validate();
            }
            catch
            {
                Log.LogError($"Error parsing {modInfoPath}");
                return(false);
            }

            var modSettingsPath = Path.Combine(OutputPath, "settings.xml");

            if (File.Exists(modSettingsPath))
            {
                XDocument modSettings = null;
                try
                {
                    modSettings = XDocument.Load(modSettingsPath);
                }
                catch
                {
                    Log.LogError($"Error parsing {modSettingsPath}");
                    return(false);
                }
            }

            var modDir      = Path.Combine(PublishPath, modInfo.DisplayName);
            var zipFilePath = Path.Combine(modDir, $"{modInfo.Id}.zip");

            EnsureParentDirExists(zipFilePath);

            // Patch info.json
            modInfo.Repository = $"https://{HostSiteDomain}/{Uri.EscapeDataString(modInfo.DisplayName)}/{RepositoryJsonFileName}";
            if (string.IsNullOrEmpty(modInfo.HomePage))
            {
                modInfo.HomePage = $"https://{HostSiteDomain}/{Uri.EscapeDataString(modInfo.DisplayName)}/";
            }

            // Copy readme files
            foreach (var readmeFilePath in Directory.EnumerateFiles(OutputPath, "*.md", SearchOption.TopDirectoryOnly))
            {
                var publishPath = Path.Combine(modDir, Path.GetFileName(readmeFilePath));
                File.Copy(readmeFilePath, publishPath, overwrite: true);
            }

            File.WriteAllText(modInfoPath, JsonConvert.SerializeObject(modInfo, _jsonSerializerSettings));

            {
                using var zipFileStream = File.Create(zipFilePath);
                using var outStream     = new ZipOutputStream(zipFileStream);

                foreach (var filePath in Directory.EnumerateFiles(OutputPath, "*", SearchOption.AllDirectories))
                {
                    var relativeRootIndex = OutputPath.TrimEnd(Path.DirectorySeparatorChar).Length + 1;
                    outStream.PutNextEntry(new ZipEntry($"{modInfo.Id}/{filePath.Substring(relativeRootIndex).Replace('\\', '/')}"));
                    using var entryFs = File.OpenRead(filePath);
                    entryFs.CopyTo(outStream);
                }
            }

            var repositoryJsonPath = Path.Combine(modDir, RepositoryJsonFileName);

            EnsureParentDirExists(repositoryJsonPath);
            var repo = new Repository
            {
                Releases = new Release[]
                {
                    new Release
                    {
                        Id          = modInfo.Id,
                        Version     = modInfo.Version,
                        DownloadUrl = $"https://{HostSiteDomain}/{Uri.EscapeDataString(modInfo.DisplayName)}/{Uri.EscapeDataString(modInfo.Id)}.zip",
                    }
                },
            };

            File.WriteAllText(repositoryJsonPath, JsonConvert.SerializeObject(repo, _jsonSerializerSettings));

            return(true);
        }