Beispiel #1
0
        public void HonorsMaxDepth()
        {
            var g = new Glob(FileSystem);

            g.Options.MaxDepth = 1;
            g.Pattern          = Path.GetFullPath(FixPath(TestDir + @"/**/file1"));
            AssertEqual(g.ExpandNames(), @"/file1", @"/dir2/file1", @"/dir3/file1");
            g.Options.MaxDepth = 2;
            AssertEqual(g.ExpandNames(), @"/file1", @"/dir2/file1", @"/dir2/dir2/file1", @"/dir3/file1");
            g.Options.MaxDepth = 0;
            AssertEqual(g.ExpandNames(), @"/file1");
        }
Beispiel #2
0
        public static Assembly Generate(string name, string pattern, Generator generatorPrototype = null)
        {
            if (Assemblies.ContainsKey(name))
            {
                return(Assemblies[name]);
            }

            var files = Glob.ExpandNames(pattern);

            return(GenerateFiles(name, files, generatorPrototype));
        }
Beispiel #3
0
        public void CanLog()
        {
            var log  = "";
            var glob = new Glob(@"test", new TestFileSystem())
            {
                IgnoreCase = true, ErrorLog = s => log += s
            };
            var fs = glob.ExpandNames().ToList();

            Assert.False(string.IsNullOrEmpty(log));
        }
Beispiel #4
0
        public void TestBpmn()
        {
            var assembly = Compiler.Generate("Bpmn", BpmnPattern);

            Assert.NotNull(assembly);

            var type = assembly.GetTypes().SingleOrDefault(t => t.Name == "TDefinitions");

            Assert.NotNull(type);

            var serializer = new XmlSerializer(type);

            serializer.UnknownNode      += new XmlNodeEventHandler(UnknownNodeHandler);
            serializer.UnknownAttribute += new XmlAttributeEventHandler(UnknownAttributeHandler);
            var unknownNodeError = false;
            var unknownAttrError = false;

            void UnknownNodeHandler(object sender, XmlNodeEventArgs e)
            {
                unknownNodeError = true;
            }

            void UnknownAttributeHandler(object sender, XmlAttributeEventArgs e)
            {
                unknownAttrError = true;
            }

            var currDir   = Directory.GetCurrentDirectory();
            var testDir   = "bpmn_tests";
            var fileExt   = "bpmn";
            var testFiles = Glob.ExpandNames(string.Format("{0}\\xml\\{1}\\*.{2}", currDir, testDir, fileExt));

            foreach (var testFile in testFiles)
            {
                var xmlString = File.ReadAllText(testFile);
                var reader    = XmlReader.Create(new StringReader(xmlString), new XmlReaderSettings {
                    IgnoreWhitespace = true
                });

                var isDeserializable = serializer.CanDeserialize(reader);
                Assert.True(isDeserializable);

                var deserializedObject = serializer.Deserialize(reader);
                Assert.False(unknownNodeError);
                Assert.False(unknownAttrError);

                var serializedXml = Serialize(serializer, deserializedObject, GetNamespacesFromSource(xmlString));

                var deserializedXml = serializer.Deserialize(new StringReader(serializedXml));
                AssertEx.Equal(deserializedObject, deserializedXml);
            }
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            bool show_help = false;
            bool watch     = false;
            bool force     = false;
            bool commit    = false;
            var  options   = new OptionSet()
            {
                { "o|output=", "specify output Directory", v => output = v },
                { "c|commit", "commit ocr-version", v => commit = true },
                { "w|watch", "watch directory", v => watch = true },
                { "f|force", "force generation of ocr file", v => force = true },
                { "h|help", "orccore file1 [file2 ...file-n]", v => show_help = v != null }
            };
            var pathes = options.Parse(args);

            if (show_help)
            {
                options.WriteOptionDescriptions(Console.Out);
                System.Environment.Exit(0);
            }

            if (watch)
            {
                Watcher watcher = new Watcher(pathes[0], output);
                watcher.Start();
                Console.ReadLine();
                watcher.Stop();
            }
            else
            {
                foreach (var p in pathes)
                {
                    var        globber = new Glob();
                    var        files   = globber.ExpandNames(p);
                    OcrService scanner = new OcrService(output);
                    foreach (var f in files)
                    {
                        if (commit)
                        {
                            scanner.Commit(f);
                        }
                        else
                        {
                            scanner.Scan(f, force);
                        }
                    }
                }
            }
        }
        private void DeserializeSampleXml(string pattern, Assembly assembly)
        {
            var files = Glob.ExpandNames(pattern);

            var set = new XmlSchemaSet();

            var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f), (s, e) =>
            {
                Assert.True(false, e.Message);
            }));

            foreach (var s in schemas)
            {
                set.Add(s);
            }

            set.Compile();

            var anyValidXml = false;

            foreach (var rootElement in set.GlobalElements.Values.Cast <XmlSchemaElement>().Where(e => !e.IsAbstract && !(e.ElementSchemaType is XmlSchemaSimpleType)))
            {
                var type       = FindType(assembly, rootElement.QualifiedName);
                var serializer = new XmlSerializer(type);
                var generator  = new XmlSampleGenerator(set, rootElement.QualifiedName);
                var sb         = new StringBuilder();
                using (var xw = XmlWriter.Create(sb, new XmlWriterSettings {
                    Indent = true
                }))
                {
                    // generate sample xml
                    generator.WriteXml(xw);
                    var xml = sb.ToString();

                    File.WriteAllText("xml.xml", xml);

                    // validate serialized xml
                    var settings = new XmlReaderSettings
                    {
                        ValidationType = ValidationType.Schema,
                        Schemas        = set
                    };

                    var invalid = false;

                    void validate(object s, ValidationEventArgs e)
                    {
                        if (HandleValidationError(xml, e))
                        {
                            invalid = true;
                        }
                    }

                    settings.ValidationEventHandler += validate;

                    var reader = XmlReader.Create(new StringReader(xml), settings);
                    while (reader.Read())
                    {
                        ;
                    }

                    settings.ValidationEventHandler -= validate;

                    // generated xml is not schema valid -> skip
                    if (invalid)
                    {
                        continue;
                    }
                    anyValidXml = true;

                    // deserialize from sample
                    var sr = new StringReader(xml);
                    var o  = serializer.Deserialize(sr);

                    // serialize back to xml
                    var xml2 = Serialize(serializer, o);

                    File.WriteAllText("xml2.xml", xml2);

                    void validate2(object s, ValidationEventArgs e)
                    {
                        if (HandleValidationError(xml2, e))
                        {
                            throw e.Exception;
                        }
                    };

                    settings.ValidationEventHandler += validate2;

                    reader = XmlReader.Create(new StringReader(xml2), settings);
                    while (reader.Read())
                    {
                        ;
                    }

                    settings.ValidationEventHandler -= validate2;

                    // deserialize again
                    sr = new StringReader(xml2);
                    var o2 = serializer.Deserialize(sr);

                    AssertEx.Equal(o, o2);
                }
            }

            Assert.True(anyValidXml, "No valid generated XML for this test");
        }
Beispiel #7
0
        public void CanThrow()
        {
            var fs = new TestFileSystem
            {
                DirectoryInfo = new TestDirectoryInfoFactory {
                    FromDirectoryNameFunc = n => throw new ArgumentException("", "1")
                }
            };

            var g = new Glob(new GlobOptions {
                ThrowOnError = true
            }, fs)
            {
                Pattern = TestDir + @"\>"
            };

            Assert.Throws <ArgumentException>("1", () => g.ExpandNames().ToList());

            fs.Path = new TestPath(FileSystem)
            {
                GetDirectoryNameFunc = n => throw new ArgumentException("", "2")
            };

            g = new Glob(fs)
            {
                Pattern = "*"
            };
            Assert.Empty(g.ExpandNames());
            g.Options.ThrowOnError = true;
            Assert.Throws <ArgumentException>("2", () => g.ExpandNames().ToList());

            fs.Path = new TestPath(FileSystem)
            {
                GetDirectoryNameFunc = n => null
            };
            fs.DirectoryInfo = new TestDirectoryInfoFactory {
                FromDirectoryNameFunc = n => throw new ArgumentException("", "3")
            };

            g.Options.ThrowOnError = false;
            Assert.Empty(g.ExpandNames());
            g.Options.ThrowOnError = true;
            Assert.Throws <ArgumentException>("3", () => g.ExpandNames().ToList());

            fs.Path = new TestPath(FileSystem)
            {
                GetDirectoryNameFunc = n => ""
            };
            fs.DirectoryInfo = new TestDirectoryInfoFactory {
                FromDirectoryNameFunc = n => null
            };
            fs.Directory = new TestDirectory(FileSystem, null, "")
            {
                GetCurrentDirectoryFunc = () => throw new ArgumentException("", "4")
            };

            g.Options.ThrowOnError = false;
            Assert.Empty(g.ExpandNames());
            g.Options.ThrowOnError = true;
            Assert.Throws <ArgumentException>("4", () => g.ExpandNames().ToList());

            fs.Directory = new TestDirectory(FileSystem, null, "")
            {
                GetCurrentDirectoryFunc = () => "5"
            };
            var d = new TestDirectoryInfo(FileSystem, TestDir)
            {
                GetFileSystemInfosFunc = () => throw new ArgumentException("", "5")
            };

            fs.DirectoryInfo = new TestDirectoryInfoFactory {
                FromDirectoryNameFunc = n => d
            };

            g.Options.ThrowOnError = false;
            Assert.Empty(g.ExpandNames());
            g.Options.ThrowOnError = true;
            Assert.Throws <ArgumentException>("5", () => g.ExpandNames().ToList());
        }
Beispiel #8
0
 public void CanMatchRelativePaths()
 {
     AssertEqual(Glob.ExpandNames(FixPath(@"..\..\dir3\file*"), ignoreCase: true, dirOnly: false, fileSystem: FileSystem), @"\dir3\file1");
     AssertEqual(Glob.ExpandNames(FixPath(@".\..\..\.\.\dir3\file*"), ignoreCase: true, dirOnly: false, fileSystem: FileSystem), @"\dir3\file1");
 }
Beispiel #9
0
        static void Main(string[] args)
        {
            var    showHelp                               = args.Length == 0;
            var    namespaces                             = new List <string>();
            var    outputFolder                           = (string)null;
            var    integerType                            = typeof(string);
            var    namespacePrefix                        = "";
            var    verbose                                = false;
            var    nullables                              = false;
            var    pclCompatible                          = false;
            var    enableDataBinding                      = false;
            var    emitOrder                              = false;
            var    entityFramework                        = false;
            var    interfaces                             = true;
            var    pascal                                 = true;
            var    collectionType                         = typeof(Collection <>);
            Type   collectionImplementationType           = null;
            var    codeTypeReferenceOptions               = default(CodeTypeReferenceOptions);
            string textValuePropertyName                  = "Value";
            var    generateDebuggerStepThroughAttribute   = true;
            var    disableComments                        = false;
            var    doNotUseUnderscoreInPrivateMemberNames = false;
            var    generateDescriptionAttribute           = true;
            var    enableUpaCheck                         = true;

            var options = new OptionSet {
                { "h|help", "show this message and exit", v => showHelp = v != null },
                { "n|namespace=", @"map an XML namespace to a C# namespace
Separate XML namespace and C# namespace by '='.
One option must be given for each namespace to be mapped.
A file name may be given by appending a pipe sign (|) followed by a file name (like schema.xsd) to the XML namespace.
If no mapping is found for an XML namespace, a name is generated automatically (may fail).", v => namespaces.Add(v) },
                { "o|output=", "the {FOLDER} to write the resulting .cs files to", v => outputFolder = v },
                { "i|integer=", @"map xs:integer and derived types to {TYPE} instead of automatic approximation
{TYPE} can be i[nt], l[ong], or d[ecimal].", v => {
                      switch (v)
                      {
                      case "i":
                      case "int":
                          integerType = typeof(int);
                          break;

                      case "l":
                      case "long":
                          integerType = typeof(long);
                          break;

                      case "d":
                      case "decimal":
                          integerType = typeof(decimal);
                          break;
                      }
                  } },
                { "e|edb|enable-data-binding", "enable INotifyPropertyChanged data binding", v => enableDataBinding = v != null },
                { "r|order", "emit order for all class members stored as XML element", v => emitOrder = v != null },
                { "c|pcl", "PCL compatible output", v => pclCompatible = v != null },
                { "p|prefix=", "the {PREFIX} to prepend to auto-generated namespace names", v => namespacePrefix = v },
                { "v|verbose", "print generated file names on stdout", v => verbose = v != null },
                { "0|nullable", "generate nullable adapter properties for optional elements/attributes w/o default values", v => nullables = v != null },
                { "f|ef", "generate Entity Framework Code First compatible classes", v => entityFramework = v != null },
                { "t|interface", "generate interfaces for groups and attribute groups (default is enabled)", v => interfaces = v != null },
                { "a|pascal", "use Pascal case for class and property names (default is enabled)", v => pascal = v != null },
                { "u|enableUpaCheck", "should XmlSchemaSet check for Unique Particle Attribution (UPA) (default is enabled)", v => enableUpaCheck = v != null },
                { "ct|collectionType=", "collection type to use (default is " + typeof(Collection <>).FullName + ")", v => collectionType = v == null ? typeof(Collection <>) : Type.GetType(v, true) },
                { "cit|collectionImplementationType=", "the default collection type implementation to use (default is null)", v => collectionImplementationType = v == null ? null : Type.GetType(v, true) },
                { "ctro|codeTypeReferenceOptions=", "the default CodeTypeReferenceOptions Flags to use (default is unset; can be: {GlobalReference, GenericTypeParameter})", v => codeTypeReferenceOptions = v == null ? default(CodeTypeReferenceOptions) : (CodeTypeReferenceOptions)Enum.Parse(typeof(CodeTypeReferenceOptions), v, false) },
                { "tvpn|textValuePropertyName=", "the name of the property that holds the text value of an element (default is Value)", v => textValuePropertyName = v },
                { "dst|debuggerStepThrough", "generate DebuggerStepThroughAttribute (default is enabled)", v => generateDebuggerStepThroughAttribute = v != null },
                { "dc|disableComments", "do not include comments from xsd", v => disableComments = v != null },
                { "nu|noUnderscore", "do not generate underscore in private member name (default is false)", v => doNotUseUnderscoreInPrivateMemberNames = v != null },
                { "da|description", "generate DescriptionAttribute (default is true)", v => generateDescriptionAttribute = v != null },
            };

            var files = options.Parse(args);

            if (showHelp)
            {
                ShowHelp(options);
                return;
            }

            files = files.SelectMany(f => Glob.ExpandNames(f)).Concat(files.Where(f => Uri.IsWellFormedUriString(f, UriKind.Absolute))).ToList();

            var namespaceMap = namespaces.Select(n => ParseNamespace(n, namespacePrefix)).ToNamespaceProvider(key =>
            {
                var xn   = key.XmlSchemaNamespace;
                var name = string.Join(".", xn.Split('/').Where(p => p != "schema" && GeneratorConfiguration.IdentifierRegex.IsMatch(p))
                                       .Select(n => n.ToTitleCase(NamingScheme.PascalCase)));
                if (!string.IsNullOrEmpty(namespacePrefix))
                {
                    name = namespacePrefix + (string.IsNullOrEmpty(name) ? "" : ("." + name));
                }
                return(name);
            });

            if (!string.IsNullOrEmpty(outputFolder))
            {
                outputFolder = Path.GetFullPath(outputFolder);
            }

            var generator = new Generator
            {
                NamespaceProvider                      = namespaceMap,
                OutputFolder                           = outputFolder,
                GenerateNullables                      = nullables,
                EnableDataBinding                      = enableDataBinding,
                EmitOrder                              = emitOrder,
                IntegerDataType                        = integerType,
                EntityFramework                        = entityFramework,
                GenerateInterfaces                     = interfaces,
                NamingScheme                           = pascal ? NamingScheme.PascalCase : NamingScheme.Direct,
                CollectionType                         = collectionType,
                CollectionImplementationType           = collectionImplementationType,
                CodeTypeReferenceOptions               = codeTypeReferenceOptions,
                TextValuePropertyName                  = textValuePropertyName,
                GenerateDebuggerStepThroughAttribute   = generateDebuggerStepThroughAttribute,
                DisableComments                        = disableComments,
                GenerateDescriptionAttribute           = generateDescriptionAttribute,
                DoNotUseUnderscoreInPrivateMemberNames = doNotUseUnderscoreInPrivateMemberNames,
                EnableUpaCheck                         = enableUpaCheck
            };

            if (pclCompatible)
            {
                generator.UseXElementForAny = true;
                generator.GenerateDesignerCategoryAttribute    = false;
                generator.GenerateSerializableAttribute        = false;
                generator.GenerateDebuggerStepThroughAttribute = false;
                generator.DataAnnotationMode           = DataAnnotationMode.None;
                generator.GenerateDescriptionAttribute = false;
            }

            if (verbose)
            {
                generator.Log = s => System.Console.Out.WriteLine(s);
            }

            generator.Generate(files);
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            string outputFolder = Path.Join(Environment.CurrentDirectory, "out");
            var    resolve      = new List <string>();
            var    exclusions   = new List <string>();

            var options = new OptionSet
            {
                { "o|output=", "Output folder", o => outputFolder = o },
                { "v", "Increase verbosity", v =>
                  {
                      if (v != null)
                      {
                          Logger.Verbosity++;
                      }
                  } },
                { "r|resolve=", "Additional resolve folders", r => resolve.Add(r) },
                { "e|exclude=", "Excluded files", e => exclusions.Add(e) }
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException ex)
            {
                Logger.Error(ex);
                return;
            }

            if (!Directory.Exists(outputFolder))
            {
                try
                {
                    Directory.CreateDirectory(outputFolder);
                }
                catch (IOException ex)
                {
                    Logger.Error(ex);
                    return;
                }
            }

            if (!Path.IsPathRooted(outputFolder))
            {
                outputFolder = Path.Combine(Environment.CurrentDirectory, outputFolder);
            }

            Logger.Trace($"Writing files to '{outputFolder}'", 1);

            var excludedFiles = new HashSet <string>();

            foreach (string exclusion in exclusions)
            {
                foreach (string file in Glob.ExpandNames(exclusion))
                {
                    excludedFiles.Add(file);
                }
            }

            foreach (string extra in extras)
            {
                foreach (string fileName in Glob.ExpandNames(extra))
                {
                    if (excludedFiles.Contains(fileName))
                    {
                        Logger.Trace($"Excluding file '{fileName}'", 2);
                        continue;
                    }

                    try
                    {
                        List <string> paths = new List <string>(resolve);
                        paths.Add(Path.GetDirectoryName(fileName));
                        GenerateStrippedAssembly(fileName, outputFolder, paths);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex);
                    }
                }
            }
        }
Beispiel #11
0
        public static int Main(string[] args)
        {
#if DNX451 || NET451
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
#else
            CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
#endif

            var options = new Options
            {
                OutputFile    = default(string),
                OutputFormat  = ".pot",
                InputFormat   = default(string),
                Keywords      = new List <Keyword>(),
                InputPatterns = new List <string>()
            };

            for (var i = 0; i < args.Length; i++)
            {
                var arg = args[i];

                if (arg.StartsWith("-"))
                {
                    if (arg == "-o" || arg == "--output")
                    {
                        options.OutputFile = args[++i];
                        continue;
                    }

                    if (arg == "-f" || arg == "--format")
                    {
                        options.OutputFormat = args[++i];
                        continue;
                    }

                    if (arg == "-k" || arg == "--keyword")
                    {
                        options.Keywords.Add(Keyword.Parse(args[++i]));
                        continue;
                    }

                    if (arg == "-l" || arg == "--language")
                    {
                        options.InputFormat = args[++i];
                        continue;
                    }

                    PrintUsage("Unrecognized argument '{0}'", arg);
                    return(-1);
                }

                options.InputPatterns.Add(arg);
            }

            if (options.InputPatterns.Count <= 0)
            {
                PrintUsage();
                return(-1);
            }

            if (options.InputFormat != null && !extractors.ContainsKey(options.InputFormat))
            {
                PrintUsage("Language '{0}' not found", options.InputFormat);
                return(-1);
            }

            var generatorFactory = default(IGeneratorFactory);
            if (string.IsNullOrEmpty(options.OutputFormat) || !generators.TryGetValue(options.OutputFormat, out generatorFactory))
            {
                PrintUsage("Generator '{0}' not found", options.OutputFormat);
                return(-1);
            }

            var files = options.InputPatterns
                        .SelectMany(f => Glob.ExpandNames(f))
                        .ToArray();

            var missingFiles = files.Where(f => !File.Exists(f)).ToArray();
            if (missingFiles.Length > 0)
            {
                PrintUsage("Files {0} not found", string.Join(", ", missingFiles.Select(f => $"'${f}'")));
                return(-1);
            }

            if (options.InputFormat == null)
            {
                var unknownFiles = files.Where(f => !extractors.ContainsKey(Path.GetExtension(f))).ToArray();
                if (unknownFiles.Length > 0)
                {
                    PrintUsage("Unknown format for files: {0}", string.Join(", ", unknownFiles.Select(f => $"'${f}'")));
                    return(-1);
                }
            }

            var matches = new List <KeywordMatch>();

            foreach (var file in files)
            {
                using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (var reader = new StreamReader(stream))
                    {
                        var extension         = options.InputFormat ?? Path.GetExtension(file);
                        var extractor         = extractors[extension];
                        var effectiveKeywords = options.Keywords.Count > 0 ? options.Keywords : extractor.DefaultKeywords;

                        var calls = extractor.GetInvocations(reader, fileName: file);

                        foreach (var call in calls)
                        {
                            var match = effectiveKeywords.Select(k => k.Match(call))
                                        .Where(m => m != null)
                                        .FirstOrDefault();

                            if (match == null)
                            {
                                continue;
                            }

                            matches.Add(match);
                        }
                    }
            }

            var groups = matches.GroupBy(m => m, m => m,
                                         (k, g) => new KeywordMatchGroup(k.Singular, k.Plural, k.Context, g.Where(i => i.Source != null).Select(i => i.Source.Value))
                                         );

            var hasOutputFile = !string.IsNullOrEmpty(options.OutputFile) && options.OutputFile != "-";
            using (var outputStream = hasOutputFile ? new FileStream(options.OutputFile, FileMode.Create, FileAccess.Write, FileShare.None) : Console.OpenStandardOutput())
                using (var generator = generatorFactory.Create(outputStream, new UTF8Encoding(false, true)))
                {
                    generator.WriteHeader();
                    foreach (var group in groups)
                    {
                        generator.WriteEntry(group);
                    }
                    generator.WriteFooter();
                    generator.Flush();
                }

            return(0);
        }