Exemplo n.º 1
0
        public static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                string inputFileName = args[0];
                if (!Path.IsPathRooted(inputFileName))
                {
                    inputFileName = Path.Combine(Environment.CurrentDirectory, inputFileName);
                }
                ICharStream       input  = new ANTLRFileStream(inputFileName);
                CLexer            lex    = new CLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                CParser           parser = new CParser(tokens);

                try {
                    parser.translation_unit();
                }
                catch (RecognitionException re) {
                    Console.Out.WriteLine(re.StackTrace);
                }
            }
            else
            {
                Console.Error.WriteLine("Usage: cparse <input-file>");
            }
        }
Exemplo n.º 2
0
        ICommandOutput SetupEnvironmentForAdd()
        {
            var directory = HostEnvironment.CurrentDirectory;

            var fromDirectory = string.IsNullOrEmpty(From) ? null : FileSystem.GetDirectory(From);

            if (fromDirectory != null && fromDirectory.Exists)
            {
                if (SysPath.GetExtension(Name).EqualsNoCase(".wrap") &&
                    SysPath.IsPathRooted(Name) &&
                    FileSystem.GetDirectory(SysPath.GetDirectoryName(Name)) != fromDirectory)
                {
                    return(new Error("You provided both -From and -Name, but -Name is a path. Try removing the -From parameter."));
                }
                directory = fromDirectory;
                _userSpecifiedRepository = new FolderRepository(directory, FolderRepositoryOptions.Default);
            }


            if (SysPath.GetExtension(Name).EqualsNoCase(".wrap") && directory.GetFile(SysPath.GetFileName(Name)).Exists)
            {
                var originalName = Name;
                Name    = PackageNameUtility.GetName(SysPath.GetFileNameWithoutExtension(Name));
                Version = PackageNameUtility.GetVersion(SysPath.GetFileNameWithoutExtension(originalName)).ToString();

                return(new Warning("The requested package contained '.wrap' in the name. Assuming you pointed to a file name and meant a package named '{0}' with version qualifier '{1}'.",
                                   Name,
                                   Version));
            }
            return(null);
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                string fullpath;
                if (Path.IsPathRooted(args[0]))
                {
                    fullpath = args[0];
                }
                else
                {
                    fullpath = Path.Combine(Environment.CurrentDirectory, args[0]);
                }

                Console.Out.WriteLine("Processing file: {0}", fullpath);
                ICharStream       input  = new ANTLRFileStream(fullpath);
                LangLexer         lex    = new LangLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                LangParser        parser = new LangParser(tokens);

                //LangParser.decl_return r = parser.decl();
                LangParser.start_return r = parser.start();
                Console.Out.WriteLine("tree: " + ((ITree)r.Tree).ToStringTree());
                CommonTree           r0    = ((CommonTree)r.Tree);
                CommonTreeNodeStream nodes = new CommonTreeNodeStream(r0);
                nodes.TokenStream = tokens;
                LangDumpDecl walker = new LangDumpDecl(nodes);
                walker.decl();
            }
            else
            {
                Console.Error.WriteLine("Usage: TreeParser <input-file>");
            }
        }
Exemplo n.º 4
0
 public static void Main(string[] args)
 {
     try {
         if (args.Length > 0)
         {
             // for each directory/file specified on the command line
             for (int i = 0; i < args.Length; i++)
             {
                 string fullpath;
                 if (Path.IsPathRooted(args[i]))
                 {
                     fullpath = args[i];
                 }
                 else
                 {
                     fullpath = Path.Combine(Environment.CurrentDirectory, args[i]);
                 }
                 ProcessFileOrDirectory(new FileInfo(fullpath));                         // parse it
             }
         }
         else
         {
             Console.Error.WriteLine("Usage: Import <directory or file name>");
         }
     }
     catch (Exception e) {
         Console.Error.WriteLine("exception: " + e);
         Console.Error.WriteLine(e.StackTrace);                   // so we can get stack trace
     }
 }
Exemplo n.º 5
0
 public static void  Main(string[] args)
 {
     // Use a try/catch block for parser exceptions
     try
     {
         // if we have at least one command-line argument
         if (args.Length > 0)
         {
             Console.Error.WriteLine("Parsing...");
             // for each directory/file specified on the command line
             for (int i = 0; i < args.Length; i++)
             {
                 string fullpath;
                 if (Path.IsPathRooted(args[i]))
                 {
                     fullpath = args[i];
                 }
                 else
                 {
                     fullpath = Path.Combine(Environment.CurrentDirectory, args[i]);
                 }
                 ProcessFileOrDirectory(new FileInfo(fullpath));                         // parse it
             }
         }
         else
         {
             Console.Error.WriteLine("Usage: JavaParser <list-of-directory-or-filename>");
         }
     }
     catch (System.Exception e)
     {
         Console.Error.WriteLine("exception: " + e);
         Console.Error.WriteLine(e.StackTrace);                 // so we can get stack trace
     }
 }
Exemplo n.º 6
0
        private void StartComputingBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!Path.IsPathRooted(FileTb.Text))
            {
                MessageBox.Show("File path is not valid");
                return;
            }

            if (PhaseFirstTimeCb.SelectedItem == null || PhaseSecTimeCb.SelectedItem == null ||
                PhaseFirstUnitCb.SelectedItem == null || PhaseSecUnitCb.SelectedItem == null)
            {
                MessageBox.Show("Phases' durations are not filled correctly");
                return;
            }

            if (HowManyTasksCb.SelectedItem == null)
            {
                MessageBox.Show("There is not specified how many tasks perform computing");
                return;
            }

            if ((!((bool)TlpRb.IsChecked) && !((bool)ThreadPoolRb.IsChecked)))
            {
                MessageBox.Show("There is not specified which mechanism should be used to compute ");
                return;
            }

            RunComputing();
        }
Exemplo n.º 7
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Cleans the name of the project given the project type. (e.g. For an XML type, this
        /// will ensure that the name is rooted and ends with the correct extension)
        /// </summary>
        /// <param name="type">The type of the project.</param>
        /// <param name="name">The name of the project.</param>
        /// <returns>The cleaned up name with the appropriate extension</returns>
        /// ------------------------------------------------------------------------------------
        private static string CleanUpNameForType(BackendProviderType type, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }

            string ext;

            switch (type)
            {
            case BackendProviderType.kXML:
                ext = LcmFileHelper.ksFwDataXmlFileExtension;
                break;

            default:
                return(name);
            }

            if (!SysPath.IsPathRooted(name))
            {
                string sProjName = (SysPath.GetExtension(name) == ext) ? SysPath.GetFileNameWithoutExtension(name) : name;
                name = SysPath.Combine(SysPath.Combine(FwDirectoryFinder.ProjectsDirectory, sProjName), name);
            }
            // If the file doesn't have the expected extension and exists with the extension or
            // does not exist without it, we add the expected extension.
            if (SysPath.GetExtension(name) != ext && (FileUtils.SimilarFileExists(name + ext) || !FileUtils.SimilarFileExists(name)))
            {
                name += ext;
            }
            return(name);
        }
Exemplo n.º 8
0
 public static void Main(string[] args)
 {
     if (args.Length > 0)
     {
         try
         {
             string inputFileName = args[0];
             if (!Path.IsPathRooted(inputFileName))
             {
                 inputFileName = Path.Combine(Environment.CurrentDirectory, inputFileName);
             }
             ICharStream input = new ANTLRFileStream(inputFileName);
             XML         lexer = new XML(input);
             while (lexer.NextToken() != Token.EOF_TOKEN)
             {
                 ;
             }
         }
         catch (Exception ex)
         {
             Console.Out.WriteLine("exception: " + ex);
             Console.Out.WriteLine(ex.StackTrace);
         }
     }
     else
     {
         Console.Error.WriteLine("Usage: xmlLexer <input-file>");
     }
 }
Exemplo n.º 9
0
        /** Load a template from dir or group file.  Group file is given
         *  precedence over dir with same name.
         */
        protected override CompiledTemplate Load(string name)
        {
            string parent = Utility.GetPrefix(name);

            if (Path.IsPathRooted(parent))
            {
                throw new ArgumentException();
            }

            Uri groupFileURL = null;

            try
            {
                // see if parent of template name is a group file
                groupFileURL = new Uri(Path.Combine(root.LocalPath, parent) + ".stg");
            }
            catch (UriFormatException e)
            {
                ErrorManager.InternalError(null, "bad URL: " + Path.Combine(root.LocalPath, parent) + ".stg", e);
                return(null);
            }

            if (!File.Exists(groupFileURL.LocalPath))
            {
                return(LoadTemplateFile(parent, name + ".st"));
            }
#if false
            InputStream @is = null;
            try
            {
                @is = groupFileURL.openStream();
            }
            catch (FileNotFoundException fnfe)
            {
                // must not be in a group file
                return(loadTemplateFile(parent, name + ".st")); // load t.st file
            }
            catch (IOException ioe)
            {
                errMgr.internalError(null, "can't load template file " + name, ioe);
            }

            try
            {
                // clean up
                if (@is != null)
                {
                    @is.close();
                }
            }
            catch (IOException ioe)
            {
                errMgr.internalError(null, "can't close template file stream " + name, ioe);
            }
#endif

            LoadGroupFile(parent, Path.Combine(root.LocalPath, parent) + ".stg");

            return(RawGetTemplate(name));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Generates the doctests given the extracted doctests from the input file.
        /// </summary>
        /// <param name="doctests">Extracted doctests from the input file</param>
        /// <param name="relativeInputPath">Relative path to the input file</param>
        /// <param name="outputPath">Absolute path to the output doctest file</param>
        /// <returns>true if there is at least one generated doctest</returns>
        /// <exception cref="ArgumentException"></exception>
        public static bool Generate(
            List <Extraction.Doctest> doctests,
            string relativeInputPath,
            string outputPath)
        {
            // Pre-condition(s)
            if (!Path.IsPathRooted(outputPath))
            {
                throw new ArgumentException($"Expected a rooted outputPath, but got: {outputPath}");
            }

            // Implementation

            if (doctests.Count == 0)
            {
                return(false);
            }

            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            string identifier = Identifier(relativeInputPath);

            using var streamWriter = new System.IO.StreamWriter(outputPath);

            Generation.Generate(doctests, identifier, streamWriter);
            return(true);
        }
Exemplo n.º 11
0
        /**
         * Return the location where ANTLR will generate output files for a given
         * file. This is a base directory and output files will be relative to
         * here in some cases such as when -o option is used and input files are
         * given relative to the input directory.
         *
         * @param fileNameWithPath path to input source
         */
        public virtual string GetOutputDirectory(string fileNameWithPath)
        {
            string outputDir;
            string fileDirectory;

            // Some files are given to us without a PATH but should should
            // still be written to the output directory in the relative path of
            // the output directory. The file directory is either the set of sub directories
            // or just or the relative path recorded for the parent grammar. This means
            // that when we write the tokens files, or the .java files for imported grammars
            // taht we will write them in the correct place.
            if (fileNameWithPath.LastIndexOfAny(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }) == -1)
            {
                // No path is included in the file name, so make the file
                // directory the same as the parent grammar (which might sitll be just ""
                // but when it is not, we will write the file in the correct place.
                fileDirectory = ".";

            }
            else
            {
                fileDirectory = fileNameWithPath.Substring(0, fileNameWithPath.LastIndexOfAny(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }));
            }
            if (haveOutputDir)
            {
                // -o /tmp /var/lib/t.g4 => /tmp/T.java
                // -o subdir/output /usr/lib/t.g4 => subdir/output/T.java
                // -o . /usr/lib/t.g4 => ./T.java
                if (fileDirectory != null &&
                    (Path.IsPathRooted(fileDirectory) ||
                     fileDirectory.StartsWith("~")))
                { // isAbsolute doesn't count this :(
                  // somebody set the dir, it takes precedence; write new file there
                    outputDir = outputDirectory;
                }
                else
                {
                    // -o /tmp subdir/t.g4 => /tmp/subdir/t.g4
                    if (fileDirectory != null)
                    {
                        outputDir = Path.Combine(outputDirectory, fileDirectory);
                    }
                    else
                    {
                        outputDir = outputDirectory;
                    }
                }
            }
            else
            {
                // they didn't specify a -o dir so just write to location
                // where grammar is, absolute or relative, this will only happen
                // with command line invocation as build tools will always
                // supply an output directory.
                outputDir = fileDirectory;
            }

            return outputDir;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets a value indicating whether the specified path string contains a root.
        /// </summary>
        /// <param name="path">The path to test.</param>
        /// <returns>
        /// <see langword="true"/> if <paramref name="path"/> contains a root; otherwise,
        /// <see langword="false"/>.
        /// </returns>
        public static bool IsPathRooted(string path)
        {
#if PORTABLE
            throw Portable.NotImplementedException;
#else
            return(BclPath.IsPathRooted(path));
#endif
        }
Exemplo n.º 13
0
    /// <summary>
    /// Gets a value indicating whether the specified path string contains a root.
    /// </summary>
    /// <param name="path">The path to test.</param>
    /// <returns>
    /// <see langword="true"/> if <paramref name="path"/> contains a root; otherwise, 
    /// <see langword="false"/>. 
    /// </returns>
    public static bool IsPathRooted(string path)
    {

      throw Portable.NotImplementedException;
#else
      return BclPath.IsPathRooted(path);

    }
Exemplo n.º 14
0
        public static string InputPath(string relativePath, DirectoryInfo input)
        {
            if (Path.IsPathRooted(relativePath))
            {
                throw new ArgumentException($"Expected a relative path, but got a rooted one: {relativePath}");
            }

            return(Path.Join(input.FullName, relativePath));
        }
Exemplo n.º 15
0
        private static int Handle(string[] inputs, FileInfo schema)
        {
            string schemaText = System.IO.File.ReadAllText(schema.FullName);
            var    jSchema    = Newtonsoft.Json.Schema.JSchema.Parse(schemaText);

            string cwd = System.IO.Directory.GetCurrentDirectory();

            bool failed = false;

            foreach (string pattern in inputs)
            {
                IEnumerable <string> paths;
                if (Path.IsPathRooted(pattern))
                {
                    var root = Path.GetPathRoot(pattern);
                    if (root == null)
                    {
                        throw new ArgumentException(
                                  $"Root could not be retrieved from rooted pattern: {pattern}");
                    }

                    var relPattern = Path.GetRelativePath(root, pattern);
                    paths = GlobExpressions.Glob.Files(root, relPattern)
                            .Select((path) => Path.Join(root, relPattern));
                }
                else
                {
                    paths = GlobExpressions.Glob.Files(cwd, pattern)
                            .Select((path) => Path.Join(cwd, path));
                }

                foreach (string path in paths)
                {
                    string text    = System.IO.File.ReadAllText(path);
                    var    jObject = Newtonsoft.Json.Linq.JObject.Parse(text);

                    bool valid = jObject.IsValid(jSchema, out IList <string> messages);

                    if (!valid)
                    {
                        Console.Error.WriteLine($"FAIL: {path}");
                        foreach (string message in messages)
                        {
                            Console.Error.WriteLine(message);
                        }

                        failed = true;
                    }
                    else
                    {
                        Console.WriteLine($"OK: {path}");
                    }
                }
            }

            return((failed) ? 1 : 0);
        }
Exemplo n.º 16
0
 FileTarget(Graph graph, string path)
     : base(graph)
 {
     Guard.Required(path, nameof(path));
     if (!IOPath.IsPathRooted(path))
     {
         throw new ArgumentException("Not an absolute path", nameof(path));
     }
     Path = IOPath.GetFullPath(path);
 }
Exemplo n.º 17
0
        private void NavigateFile(string file)
        {
            if (!Path.IsPathRooted(file))
            {
                file = Path.GetFullPath(Path.Combine(App.CurrentRootPath,
                                                     this.ViewModel.Profile.ProjectName,
                                                     "Config",
                                                     file));
            }

            Helpers.NavigateFile(file);
        }
Exemplo n.º 18
0
        private static Tuple <string, TempDirectoryHelper> BuildXnb(IServiceLocator services, string applicationName, string fileName, bool createModelNode, bool recreateModelAndMaterialFiles)
        {
            Debug.Assert(services != null);
            Debug.Assert(applicationName != null);
            Debug.Assert(applicationName.Length > 0);
            Debug.Assert(fileName != null);
            Debug.Assert(fileName.Length > 0);

            var tempDirectoryHelper = new TempDirectoryHelper(applicationName, "ModelDocument");

            try
            {
                var contentBuilder = new GameContentBuilder(services)
                {
                    IntermediateFolder = tempDirectoryHelper.TempDirectoryName + "\\obj",
                    OutputFolder       = tempDirectoryHelper.TempDirectoryName + "\\bin",
                };

                string processorName;
                var    processorParams = new OpaqueDataDictionary();
                if (createModelNode)
                {
                    processorName = "GameModelProcessor";
                    processorParams.Add("RecreateModelDescriptionFile", recreateModelAndMaterialFiles);
                    processorParams.Add("RecreateMaterialDefinitionFiles", recreateModelAndMaterialFiles);
                }
                else
                {
                    processorName = "ModelProcessor";
                }

                string errorMessage;
                bool   success = contentBuilder.Build(Path.GetFullPath(fileName), null, processorName, processorParams, out errorMessage);
                if (!success)
                {
                    throw new EditorException(Invariant($"Could not process 3d model: {fileName}.\n See output window for details."));
                }

                // Return output folder into which we built the XNB.
                var outputFolder = contentBuilder.OutputFolder;
                if (!Path.IsPathRooted(outputFolder))
                {
                    outputFolder = Path.GetFullPath(Path.Combine(contentBuilder.ExecutableFolder, contentBuilder.OutputFolder));
                }

                return(Tuple.Create(outputFolder, tempDirectoryHelper));
            }
            catch
            {
                tempDirectoryHelper.Dispose();
                throw;
            }
        }
Exemplo n.º 19
0
        /** Load full path name .st file relative to root by prefix */
        public virtual CompiledTemplate LoadTemplateFile(string prefix, string fileName)
        {
            if (Path.IsPathRooted(fileName))
            {
                throw new ArgumentException();
            }

            //System.out.println("load "+fileName+" from "+root+" prefix="+prefix);
            string templateName = Path.ChangeExtension(fileName, null);
            Uri    f            = null;

            try
            {
                f = new Uri(Path.Combine(root.LocalPath, fileName));
            }
            catch (UriFormatException me)
            {
                ErrorManager.RuntimeError(null, 0, ErrorType.INVALID_TEMPLATE_NAME, me, Path.Combine(root.LocalPath, fileName));
                return(null);
            }

            ANTLRReaderStream fs = null;

            try
            {
                fs = new ANTLRReaderStream(new StreamReader(f.LocalPath, Encoding ?? Encoding.UTF8));
            }
            catch (IOException)
            {
                // doesn't exist; just return null to say not found
                return(null);
            }

            GroupLexer lexer = new GroupLexer(fs);

            fs.name = fileName;
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            GroupParser       parser = new GroupParser(tokens);

            parser.Group = this;
            lexer.group  = this;
            try
            {
                parser.templateDef(prefix);
            }
            catch (RecognitionException re)
            {
                ErrorManager.GroupSyntaxError(ErrorType.SYNTAX_ERROR, Path.GetFileName(f.LocalPath), re, re.Message);
            }

            return(RawGetTemplate(templateName));
        }
Exemplo n.º 20
0
        public static string OutputPath(string relativePath, DirectoryInfo output)
        {
            if (Path.IsPathRooted(relativePath))
            {
                throw new ArgumentException($"Expected a relative path, but got a rooted one: {relativePath}");
            }

            string doctestRelativePath = Path.Join(
                Path.GetDirectoryName(relativePath),
                "DocTest" + Path.GetFileName(relativePath));

            return(Path.Join(output.FullName, doctestRelativePath));
        }
Exemplo n.º 21
0
        private static void ReadConfigFile()
        {
            configDoc = new XmlDocument();
            string configFileName = Path.Combine(applDir, applName + ".xml");

            configDoc.Load(configFileName);
            string logFileName0 = GetConfigParm("logFile");

            logFileName = Path.IsPathRooted(logFileName0) ? logFileName0 : Path.Combine(applDir, logFileName0);
            logLevel    = GetConfigParmInt("logLevel");
            ReadGatewayConfigs();
            configDoc = null;
        }
Exemplo n.º 22
0
        public override bool Execute()
        {
            AppDomain domain = null;
            bool      success;

            if (!Path.IsPathRooted(ToolPath))
            {
                ToolPath = Path.Combine(Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode), ToolPath);
            }

            if (!Path.IsPathRooted(BuildTaskPath))
            {
                BuildTaskPath = Path.Combine(Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode), BuildTaskPath);
            }

            try
            {
                domain = GetAntlrTaskAppDomain();
                AntlrClassGenerationTaskInternal wrapper = CreateBuildTaskWrapper(domain);
                success = wrapper.Execute();

                if (success)
                {
                    _generatedCodeFiles.AddRange(wrapper.GeneratedCodeFiles.Select(file => (ITaskItem) new TaskItem(file)));
                }

                foreach (BuildMessage message in wrapper.BuildMessages)
                {
                    ProcessBuildMessage(message);
                }
            }
            catch (Exception exception)
            {
                if (IsFatalException(exception))
                {
                    throw;
                }

                ProcessExceptionAsBuildMessage(exception);
                success = false;
            }
            finally
            {
                if (domain != null && domain != _sharedAppDomain)
                {
                    AppDomain.Unload(domain);
                }
            }

            return(success);
        }
        public override bool Execute()
        {
            bool success;

            if (!Path.IsPathRooted(AntlrToolPath))
            {
                AntlrToolPath = Path.Combine(Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode), AntlrToolPath);
            }

            if (!Path.IsPathRooted(BuildTaskPath))
            {
                BuildTaskPath = Path.Combine(Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode), BuildTaskPath);
            }

            try
            {
                AntlrClassGenerationTaskInternal wrapper = CreateBuildTaskWrapper();

                _lock.Wait();
                try
                {
                    success = wrapper.Execute();
                }
                finally
                {
                    _lock.Release();
                }

                if (success)
                {
                    _generatedCodeFiles.AddRange(wrapper.GeneratedCodeFiles.Select(file => (ITaskItem) new TaskItem(file)));
                }

                foreach (BuildMessage message in wrapper.BuildMessages)
                {
                    ProcessBuildMessage(message);
                }
            }
            catch (Exception exception)
            {
                if (IsFatalException(exception))
                {
                    throw;
                }

                ProcessExceptionAsBuildMessage(exception);
                success = false;
            }

            return(success);
        }
Exemplo n.º 24
0
        /**
         * Convert an object of type T to JSON representation, and output to a file.
         * If filename is not an absolute path, it will be relative to the
         * Application's dataPath.
         */
        public void Persist(string filename, T settings)
        {
            string dstFilePath = filename;

            if (!Path.IsPathRooted(dstFilePath)) // If relative path, base at dataPath.
            {
                dstFilePath = Path.Combine(Application.dataPath, dstFilePath);
            }
            if (!Directory.Exists(Path.GetDirectoryName(dstFilePath))) // If directory doesnt exist create it.
            {
                Directory.CreateDirectory(Path.GetDirectoryName(dstFilePath));
            }
            File.WriteAllText(dstFilePath, JsonUtility.ToJson(settings));
        }
Exemplo n.º 25
0
        /// <summary>
        /// Infers the identifier for the test suite based on the relative path to the input file.
        /// </summary>
        /// <param name="relativeInputPath">path to the input file, relative</param>
        /// <returns>Valid C# class identifier</returns>
        public static string Identifier(string relativeInputPath)
        {
            if (relativeInputPath.Length == 0)
            {
                throw new ArgumentException($"Unexpected empty {nameof(relativeInputPath)}");
            }

            if (Path.IsPathRooted(relativeInputPath))
            {
                throw new ArgumentException(
                          $"Unexpected rooted {nameof(relativeInputPath)}: {relativeInputPath}");
            }

            return($"DocTest_{nonidentifierCharRe.Replace(relativeInputPath, "_")}");
        }
Exemplo n.º 26
0
        private static string GetRootedPath(string rootPath, string?inputPath)
        {
            if (!string.IsNullOrEmpty(inputPath))
            {
                if (Path.IsPathRooted(inputPath))
                {
                    rootPath = inputPath;
                }
                else
                {
                    rootPath = Path.GetFullPath(inputPath, rootPath);
                }
            }

            return(rootPath);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Check if the given path is a well-formed absolute path.
        /// If not, throw and <see cref="AxeWindowsAutomationException"/>.
        /// </summary>
        /// <param name="path"></param>
        /// <exception cref="AxeWindowsAutomationException"/>
        private void VerifyPathOrThrow(string path)
        {
            try
            {
                // the following throws various exceptions if the given path is invalid
                Path.GetFullPath(path);

                if (!Path.IsPathRooted(path))
                {
                    throw new Exception(DisplayStrings.ErrorIsNotFullPath);
                }
            }
            catch (Exception ex)
            {
                throw new AxeWindowsAutomationException(string.Format(CultureInfo.InvariantCulture, DisplayStrings.ErrorDirectoryInvalid, path), ex);
            }
        }
Exemplo n.º 28
0
        /**
         * Read the contents of a file and parse it as a JSON object of type T.
         * If filename is not an absolute path, it will be relative to the
         * Application's dataPath.
         */
        public T Load(string filename)
        {
            string srcFilePath = filename;

            if (!Path.IsPathRooted(srcFilePath)) // If relative path, base at dataPath.
            {
                srcFilePath = Path.Combine(Application.dataPath, srcFilePath);
            }
            if (!File.Exists(srcFilePath)) // If file doesn't exist throw an error.
            {
                Debug.Log("Error loading setting file. File " + srcFilePath + " does not exist.");
                throw new Exception("No file " + srcFilePath);
            }
            T settings = JsonUtility.FromJson <T>(File.ReadAllText(srcFilePath));

            return(settings);
        }
Exemplo n.º 29
0
        public static void writeFile(string dir, string fileName, string content)
        {
            if (Path.IsPathRooted(fileName))
            {
                throw new ArgumentException();
            }

            string fullPath = Path.GetFullPath(Path.Combine(dir, fileName));

            dir = Path.GetDirectoryName(fullPath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            File.WriteAllText(fullPath, content);
        }
Exemplo n.º 30
0
        /** Load full path name .st file relative to root by prefix */
        public virtual CompiledTemplate LoadTemplateFile(string prefix, string unqualifiedFileName)
        {
            if (Path.IsPathRooted(unqualifiedFileName))
            {
                throw new ArgumentException();
            }

            if (Verbose)
            {
                Console.WriteLine("loadTemplateFile({0}) in groupdir from {1} prefix={2}", unqualifiedFileName, root, prefix);
            }

            string templateName = Path.ChangeExtension(unqualifiedFileName, null);
            Uri    f;

            try
            {
                f = new Uri(root.LocalPath + prefix + unqualifiedFileName);
            }
            catch (UriFormatException me)
            {
                ErrorManager.RuntimeError(null, ErrorType.INVALID_TEMPLATE_NAME, me, Path.Combine(root.LocalPath, unqualifiedFileName));
                return(null);
            }

            ANTLRReaderStream fs = null;

            try
            {
                fs      = new ANTLRReaderStream(new StreamReader(File.OpenRead(f.LocalPath), Encoding));
                fs.name = unqualifiedFileName;
            }
            catch (IOException)
            {
                if (Verbose)
                {
                    Console.WriteLine("{0}/{1} doesn't exist", root, unqualifiedFileName);
                }

                //errMgr.IOError(null, ErrorType.NO_SUCH_TEMPLATE, ioe, unqualifiedFileName);
                return(null);
            }

            return(LoadTemplateFile(prefix, unqualifiedFileName, fs));
        }