RingDotNetfor Ring

File patterns (globbing)

Patterns such as **/*.ring describe sets of files, the way a .gitignore file or a build tool does. This lesson uses the Matcher of .NET with include and exclude rules, finds files in a folder tree, and tests a plain list of paths without a disk.

What you will learn#

The tutorial Files and folders listed the files of a folder and the tutorial Regular expressions in depth used regular expressions. A glob is simpler than a regular expression and made for paths, so it is the language of file selection: build files, ignore files, backup rules, "which files changed".

Note

Microsoft.Extensions.FileSystemGlobbing is part of the ASP.NET Core runtime, so the program has "RingDotNet.Web" in its using { } (Getting started).

The program#

samples/UsingDotNet/tutorials/ch05_globbing.ring
# file patterns (globbing) - "**/*.ring", include and exclude rules, matching a list of paths, and finding files in a folder tree
load "dotnet.ring"

using {
	"Microsoft.Extensions.FileSystemGlobbing"
	"System"
	"System.IO"
	"RingDotNet.Web"                  # Microsoft.Extensions.FileSystemGlobbing is part of the ASP.NET Core runtime: this line starts it
}

func main

	# A glob pattern describes a set of files with wildcards, like the patterns in a .gitignore file or a build tool:
	#   *      any characters inside one name           *.ring     a.ring, b.ring
	#   **     any number of folders (also none)         **/*.ring  src/a.ring, src/sub/b.ring, a.ring
	#   ?      one character                             file?.txt  file1.txt, fileA.txt
	cBase = makeTree()

	# 1. A Matcher has include rules and exclude rules. A file is in the result when an include rule matches it and no exclude rule does.
	oMatcher = new Matcher()
	oMatcher.AddInclude("**/*.ring")
	? "1. **/*.ring :"
	showFiles(oMatcher,cBase)

	# 2. Exclude: everything under "tests" and every file whose name starts with "old_" is left out
	oMatcher2 = new Matcher()
	oMatcher2.AddInclude("**/*.ring")
	oMatcher2.AddExclude("tests/**")
	oMatcher2.AddExclude("**/old_*")
	? nl + "2. **/*.ring without tests/** and old_* :"
	showFiles(oMatcher2,cBase)

	# 3. Several include rules at once: the code and the documents
	oMatcher3 = new Matcher()
	oMatcher3.AddInclude("src/*.ring")
	oMatcher3.AddInclude("docs/**/*.md")
	? nl + "3. src/*.ring (one folder only) and docs/**/*.md :"
	showFiles(oMatcher3,cBase)

	# 4. A pattern does not need files on a disk: Match(root, list of paths) tests a list of names, for example the files of an archive
	#    (the tutorial "ZIP archives in memory") or the changed files of a project. The paths use / and are relative to the root.
	aPaths = ["src/main.ring","src/old_main.ring","README.md","docs/guide/intro.md","docs/logo.png"]
	oResult = oMatcher3.Match([ :rootDir = ".", :files = aPaths ])
	? nl + "4. which of the names are matched: has matches = " + oResult.HasMatches
	aFiles = oResult.Files.toList()
	for oFile in aFiles
		? "   " + oFile.Path
	next

	# 5. By default a Matcher ignores case (OrdinalIgnoreCase). The constructor takes a StringComparison: with Ordinal, case counts.
	oStrict = (new Matcher).@New([ :comparisonType = "Ordinal" ])
	oStrict.AddInclude("**/*.RING")
	oResultStrict = oStrict.Match([ :rootDir = ".", :files = ["a.ring","b.RING"] ])
	? nl + "5. with Ordinal comparison, **/*.RING matches only: " + oResultStrict.Files.toList()[1].Path

	new Directory().Delete([ :path = cBase, :recursive = True ])

# the files of the program, with their relative paths in sorted order (the order of a disk is not the same on every system)
func showFiles oMatcher,cBase

	oResult = oMatcher.GetResultsInFullPath(cBase)
	aNames = []
	aFullNames = oResult.toList()
	for cFull in aFullNames
		aNames + substr(substr(cFull,cBase + "\",""),cBase + "/","")
	next
	aSortedNames = sort(aNames)
	for cName in aSortedNames
		? "   " + substr(cName,"\","/")
	next
	? "   (" + len(aNames) + " files)"

func makeTree

	oPath = new Path()
	cBase = oPath.Combine([oPath.GetTempPath(),"ringdotnet_globbing"])
	if new Directory().Exists(cBase)
		new Directory().Delete([ :path = cBase, :recursive = True ])
	ok
	for cFile in ["src/main.ring","src/old_main.ring","src/util/tools.ring","tests/test1.ring","docs/readme.md","docs/guide/intro.md","docs/logo.png","build.txt"]
		cFull = oPath.Combine([cBase,substr(cFile,"/",oPath.DirectorySeparatorChar)])
		new Directory().CreateDirectory(oPath.GetDirectoryName(cFull))
		new File().WriteAllText([ :path = cFull, :contents = "x" ])
	next
	return cBase
Output
1. **/*.ring :
   src/main.ring
   src/old_main.ring
   src/util/tools.ring
   tests/test1.ring
   (4 files)

2. **/*.ring without tests/** and old_* :
   src/main.ring
   src/util/tools.ring
   (2 files)

3. src/*.ring (one folder only) and docs/**/*.md :
   docs/guide/intro.md
   docs/readme.md
   src/main.ring
   src/old_main.ring
   (4 files)

4. which of the names are matched: has matches = 1
   src/main.ring
   src/old_main.ring
   docs/guide/intro.md

5. with Ordinal comparison, **/*.RING matches only: b.RING
Note

This program uses a few generic functions (dnNew, dnStatic, callMethod, getProp) where a class cannot be used. The lesson The generic functions explains them.

How it works#

The wildcards#

PatternMatches
*.ringany file name that ends with .ring, in one folder
?exactly one character: file?.txt is file1.txt and fileA.txt
**any number of folders, also none: **/*.ring is a.ring, src/a.ring and src/util/a.ring
src/*.ringfiles in src, not in its sub-folders
docs/**/*.mdevery .md file below docs, at any depth

The separator is always /, on every system.

Include and exclude#

A Matcher collects include rules (AddInclude) and exclude rules (AddExclude). A file is in the result when at least one include rule matches it and no exclude rule does. In step 2, **/*.ring finds four files, then tests/** removes everything in tests and **/old_* removes every file whose name starts with old_, leaving two. Several include rules are joined (step 3: the code of one folder and all the documents).

Files on a disk#

GetResultsInFullPath(matcher, folder) walks the folder and gives the full paths of the matching files. The order is the order of the file system, which is not the same on every system, so the program sorts the names before printing. GetResultsInFullPath and Match are extension methods of MatcherExtensions, so they are called with dnStatic(type, method, [arguments]) (the tutorial Caching); AddInclude and AddExclude are real methods of the object. The class is made with dnNew(type, []) because the namespace has no generated Ring classes.

A list of names#

Match(root, files) applies the patterns to a list of paths that need not exist: the names inside an archive (the tutorial ZIP archives in memory), the files that a version control system reports as changed, the lines of a file. It needs a root (use ".", an empty text is read as a missing value) and a collection of texts: a plain Ring list is accepted where .NET wants an IEnumerable<string>. The result has HasMatches and Files, each file with its Path.

Case#

By default a matcher ignores case: *.ring also finds B.RING. The constructor takes a StringComparison; with Ordinal, **/*.RING matches only names written in capitals (step 5). Use Ordinal for file systems that care about case.

What you learned#

Exercises#

  1. Write findFiles(cFolder, aInclude, aExclude) that returns the relative names as a Ring list.
  2. Read the patterns from a settings file (the tutorial Configuration) and use them for a backup program (the tutorial A project: a backup tool).
  3. Make a matcher that finds the images (**/*.png, **/*.jpg) but not those in a folder thumbs.
  4. Test your patterns on a list of names with Match before you run them on the disk.

Next#

Watching a folder

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.