Skip to content

Commit

Permalink
Add shorthand helper methods for constructing fansi.Strs with various…
Browse files Browse the repository at this point in the history
… errormodes set #41

This should make it much less verbose for folks who want to e.g. not crash when parsing a `fansi.Str`
  • Loading branch information
lihaoyi committed Dec 8, 2021
1 parent ee6363f commit 0819379
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
8 changes: 8 additions & 0 deletions fansi/src/fansi/Fansi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,14 @@ object Str{
*/
val ansiRegex = "(\u009b|\u001b\\[)[0-?]*[ -\\/]*[@-~]".r.pattern

/** Shorthand constructor with ErrorMode.Sanitize */
def Sanitize(raw: CharSequence) = apply(raw, ErrorMode.Sanitize)

/** Shorthand constructor with ErrorMode.Strip */
def Strip(raw: CharSequence) = apply(raw, ErrorMode.Strip)

/** Shorthand constructor with ErrorMode.Throw */
def Throw(raw: CharSequence) = apply(raw, ErrorMode.Throw)
/**
* Creates an [[fansi.Str]] from a non-fansi `java.lang.String` or other
* `CharSequence`.
Expand Down
8 changes: 8 additions & 0 deletions fansi/test/src/fansi/FansiTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -378,14 +378,22 @@ object FansiTests extends TestSuite{
fansi.Str(s, errorMode = fansi.ErrorMode.Throw)
}
assert(thrownError.getMessage.contains(msg))
val thrownError2 = intercept[IllegalArgumentException]{
fansi.Str.Throw(s)
}
assert(thrownError2.getMessage.contains(msg))
// If I ask it to sanitize, the escape character is gone but the
// rest of each escape sequence remains
val sanitized = fansi.Str(s, errorMode = fansi.ErrorMode.Sanitize)
assert(sanitized.plainText == ("Hello" + msg + "World"))
val sanitized2 = fansi.Str.Sanitize(s)
assert(sanitized2.plainText == ("Hello" + msg + "World"))

// If I ask it to strip, everything is gone
val stripped = fansi.Str(s, errorMode = fansi.ErrorMode.Strip)
assert(stripped.plainText == "HelloWorld")
val stripped2 = fansi.Str.Strip(s)
assert(stripped2.plainText == "HelloWorld")
}

test("cursorUp") - check("Hello\u001b[2AWorld", "[2A")
Expand Down

0 comments on commit 0819379

Please sign in to comment.