Skip to content

Commit

Permalink
Various improvements (#473)
Browse files Browse the repository at this point in the history
* Refactor errors

* Improve pagination
  • Loading branch information
reibitto authored Jul 15, 2023
1 parent ba46ed9 commit 907ea1b
Show file tree
Hide file tree
Showing 56 changed files with 209 additions and 202 deletions.
7 changes: 0 additions & 7 deletions application.conf
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,6 @@ commands: [
{zoneId: "Europe/Berlin", displayName: "Berlin"}
{zoneId: "UTC", displayName: "UTC"}
]}
{type: "StocksCommand", tickers: [
{ticker: "FB"}
{ticker: "AMZN"}
{ticker: "AAPL"}
{ticker: "NFLX"}
{ticker: "GOOGL"}
]}
{type: "FindFileCommand"}
{type: "FindInFileCommand"}
{type: "FileNavigationCommand"}
Expand Down
4 changes: 2 additions & 2 deletions core-ui/src/main/scala/commandcenter/ui/CliTerminal.scala
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,12 @@ final case class CliTerminal[T <: Terminal](
ZIO.foreach(results.previews.lift(cursorIndex)) { preview =>
for {
_ <- preview.moreResults match {
case MoreResults.Remaining(p @ PreviewResults.Paginated(rs, pageSize, totalRemaining))
case MoreResults.Remaining(p @ PreviewResults.Paginated(rs, _, pageSize, totalRemaining))
if totalRemaining.forall(_ > 0) =>
for {
// TODO: Log defects (need file logging for this)
_ <- preview.onRun.absorb.forkDaemon
(results, restStream) <- ZIO.scoped {
(results, restStream) <- Scope.global.use {
rs.peel(ZSink.take[PreviewResult[Any]](pageSize)).mapError(_.toThrowable)
}
_ <- showMore(
Expand Down
4 changes: 4 additions & 0 deletions core/src/main/resources/powershell/system/speak.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Add-Type -AssemblyName System.Speech;
$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;
$speak.SelectVoice('{0}');
$speak.Speak('{1}');
4 changes: 2 additions & 2 deletions core/src/main/scala/commandcenter/Conf.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ final case class ConfigLive(configRef: Ref[Option[ReloadableConfig]]) extends Co

def load: RIO[Scope & Env, CCConfig] =
(for {
(release, config) <- CCConfig.load.withEarlyRelease.provideSome[Env](ZLayer.succeed(Scope.global))
(release, config) <- Scope.global.use(CCConfig.load.withEarlyRelease)
_ <- configRef.set(Some(ReloadableConfig(config, release)))
} yield config).withFinalizer { _ =>
ZIO.whenCaseZIO(configRef.get) { case Some(reloadableConfig) =>
Expand All @@ -40,7 +40,7 @@ final case class ConfigLive(configRef: Ref[Option[ReloadableConfig]]) extends Co
_ <- ZIO.whenCaseZIO(configRef.get) { case Some(reloadableConfig) =>
reloadableConfig.release
}
(release, config) <- CCConfig.load.withEarlyRelease.provideSome(ZLayer.succeed(Scope.global))
(release, config) <- Scope.global.use(CCConfig.load.withEarlyRelease)
_ <- configRef.set(Some(ReloadableConfig(config, release)))
} yield config
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ final case class CalculatorCommand(parameters: Parameters) extends Command[BigDe
)
} yield PreviewResults.one(
Preview(BigDecimal(0.0))
.score(Scores.high(searchInput.context))
.score(Scores.veryHigh(searchInput.context))
.rendered(Renderer.renderDefault(helpTitle, message))
)

Expand All @@ -56,7 +56,7 @@ final case class CalculatorCommand(parameters: Parameters) extends Command[BigDe
Preview(evaluatedValue)
.renderedAnsi(parameters.format(evaluatedValue))
.onRun(Tools.setClipboard(parameters.format(evaluatedValue)))
.score(Scores.high(searchInput.context))
.score(Scores.veryHigh(searchInput.context))
)
}

Expand Down
15 changes: 9 additions & 6 deletions core/src/main/scala/commandcenter/command/Command.scala
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ object Command {
.flatMap {
case PreviewResults.Single(r) => ZIO.succeed(Chunk.single(r))
case PreviewResults.Multiple(rs) => ZIO.succeed(rs)
case p @ PreviewResults.Paginated(rs, pageSize, totalRemaining) =>
case p @ PreviewResults.Paginated(rs, pageSize, _, totalRemaining) =>
for {
(results, restStream) <- ZIO.scoped {
(results, restStream) <- Scope.global.use {
rs.peel(ZSink.take[PreviewResult[A]](pageSize))
}
} yield results match {
Expand All @@ -110,7 +110,7 @@ object Command {
case chunk => chunk
}
}
.catchAllDefect(t => ZIO.fail(CommandError.UnexpectedException(t)))
.catchAllDefect(t => ZIO.fail(CommandError.UnexpectedError(t, command)))
.either

}
Expand All @@ -129,8 +129,11 @@ object Command {
SearchResults(input, results, errors)
}).tap { r =>
ZIO.foreachDiscard(r.errors) {
case CommandError.UnexpectedException(t) =>
ZIO.logWarningCause(s"Command encountered an unexpected exception with input: $input", Cause.die(t))
case CommandError.UnexpectedError(t, source) =>
ZIO.logWarningCause(
s"Command `${source.commandType}` encountered an unexpected exception with input: $input",
Cause.die(t)
)

case _ => ZIO.unit
}
Expand Down Expand Up @@ -172,7 +175,7 @@ object Command {
case CommandType.SearchMavenCommand => SearchMavenCommand.make(config)
case CommandType.SearchUrlCommand => SearchUrlCommand.make(config)
case CommandType.SnippetsCommand => SnippetsCommand.make(config)
case CommandType.StocksCommand => StocksCommand.make(config)
case CommandType.SpeakCommand => SpeakCommand.make(config)
case CommandType.SuspendProcessCommand => SuspendProcessCommand.make(config)
case CommandType.SwitchWindowCommand => SwitchWindowCommand.make(config)
case CommandType.SystemCommand => SystemCommand.make(config)
Expand Down
12 changes: 9 additions & 3 deletions core/src/main/scala/commandcenter/command/CommandError.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@ object CommandError {
override def toThrowable: Throwable = new Exception(s"Show message: $rendered")
}

final case class UnexpectedException(throwable: Throwable) extends CommandError {
final case class UnexpectedError[A](throwable: Throwable, source: Command[A]) extends CommandError {
def toThrowable: Throwable = throwable
}

final case class InternalError(message: String) extends CommandError {
def toThrowable: Throwable = new Exception(message)
object UnexpectedError {

def apply[A](source: Command[A])(throwable: Throwable): UnexpectedError[A] =
UnexpectedError(throwable, source)

def fromMessage[A](source: Command[A])(message: String): UnexpectedError[A] =
UnexpectedError(new Exception(message), source)
}

final case class CliError(help: Help) extends CommandError {
Expand All @@ -30,4 +35,5 @@ object CommandError {
case object NotApplicable extends CommandError {
override def toThrowable: Throwable = new Exception("Not applicable")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ object CommandType extends Enum[CommandType] {
case object SearchMavenCommand extends CommandType
case object SearchUrlCommand extends CommandType
case object SnippetsCommand extends CommandType
case object StocksCommand extends CommandType
case object SpeakCommand extends CommandType
case object SuspendProcessCommand extends CommandType
case object SwitchWindowCommand extends CommandType
case object SystemCommand extends CommandType
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ final case class DecodeBase64Command(commandNames: List[String]) extends Command
(valueToDecode, charset) <- ZIO.fromEither(parsedCommand).mapError(CommandError.CliError)
decoded = new String(Base64.getDecoder.decode(valueToDecode.getBytes(charset)), charset)
} yield PreviewResults.one(
Preview(decoded).onRun(Tools.setClipboard(decoded)).score(Scores.high(input.context))
Preview(decoded).onRun(Tools.setClipboard(decoded)).score(Scores.veryHigh(input.context))
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ final case class DecodeUrlCommand(commandNames: List[String]) extends Command[St
all = (stringArg, encodingOpt).tupled
parsedCommand = decline.Command("", s"URL decodes the given string")(all).parse(input.args)
(valueToDecode, charset) <- ZIO.fromEither(parsedCommand).mapError(CommandError.CliError)
decoded <- ZIO.attempt(URLDecoder.decode(valueToDecode, charset)).mapError(CommandError.UnexpectedException)
decoded <- ZIO.attempt(URLDecoder.decode(valueToDecode, charset)).mapError(CommandError.UnexpectedError(this))
} yield PreviewResults.one(
Preview(decoded).onRun(Tools.setClipboard(decoded)).score(Scores.high(input.context))
Preview(decoded).onRun(Tools.setClipboard(decoded)).score(Scores.veryHigh(input.context))
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ final case class EncodeBase64Command(commandNames: List[String]) extends Command
(valueToEncode, charset) <- ZIO.fromEither(parsedCommand).mapError(CommandError.CliError)
encoded = Base64.getEncoder.encodeToString(valueToEncode.getBytes(charset))
} yield PreviewResults.one(
Preview(encoded).onRun(Tools.setClipboard(encoded)).score(Scores.high(input.context))
Preview(encoded).onRun(Tools.setClipboard(encoded)).score(Scores.veryHigh(input.context))
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ final case class EncodeUrlCommand(commandNames: List[String]) extends Command[St
(valueToEncode, charset) <- ZIO.fromEither(parsedCommand).mapError(CommandError.CliError)
encoded = URLEncoder.encode(valueToEncode, charset)
} yield PreviewResults.one(
Preview(encoded).onRun(Tools.setClipboard(encoded)).score(Scores.high(input.context))
Preview(encoded).onRun(Tools.setClipboard(encoded)).score(Scores.veryHigh(input.context))
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ final case class EpochMillisCommand(commandNames: List[String]) extends Command[
for {
input <- ZIO.fromOption(searchInput.asPrefixed).orElseFail(CommandError.NotApplicable)
(output, score) <- if (input.rest.trim.isEmpty) {
Clock.currentTime(TimeUnit.MILLISECONDS).map(time => (time.toString, Scores.high))
Clock.currentTime(TimeUnit.MILLISECONDS).map(time => (time.toString, Scores.veryHigh))
} else {
input.rest.toLongOption match {
case Some(millis) =>
Expand All @@ -28,13 +28,13 @@ final case class EpochMillisCommand(commandNames: List[String]) extends Command[
.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM))

val score = if (millis < 100000000000L) {
Scores.high(input.context) * 0.9
Scores.veryHigh(input.context) * 0.9
} else {
Scores.high(input.context)
Scores.veryHigh(input.context)
}

(formatted, score)
}.mapError(CommandError.UnexpectedException)
}.mapError(CommandError.UnexpectedError(this))

case None => ZIO.fail(CommandError.NotApplicable)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ final case class EpochUnixCommand(commandNames: List[String]) extends Command[St
for {
input <- ZIO.fromOption(searchInput.asPrefixed).orElseFail(CommandError.NotApplicable)
(output, score) <- if (input.rest.trim.isEmpty) {
Clock.currentTime(TimeUnit.SECONDS).map(time => (time.toString, Scores.high))
Clock.currentTime(TimeUnit.SECONDS).map(time => (time.toString, Scores.veryHigh))
} else {
input.rest.toLongOption match {
case Some(seconds) =>
Expand All @@ -28,13 +28,13 @@ final case class EpochUnixCommand(commandNames: List[String]) extends Command[St
.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM))

val score = if (seconds < 100000000000L) {
Scores.high(input.context)
Scores.veryHigh(input.context)
} else {
Scores.high(input.context) * 0.9
Scores.veryHigh(input.context) * 0.9
}

(formatted, score)
}.mapError(CommandError.UnexpectedException)
}.mapError(CommandError.UnexpectedError(this))

case None => ZIO.fail(CommandError.NotApplicable)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ final case class ExitCommand(commandNames: List[String]) extends Command[Unit] {
} yield PreviewResults.one(
Preview.unit
.rendered(Renderer.renderDefault(title, ""))
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
.runOption(RunOption.Exit)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ final case class ExternalIPCommand(commandNames: List[String]) extends Command[S
externalIP <- getExternalIP
} yield PreviewResults.one(
Preview(externalIP)
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
.onRun(Tools.setClipboard(externalIP))
)

Expand All @@ -29,11 +29,12 @@ final case class ExternalIPCommand(commandNames: List[String]) extends Command[S
lines <- PCommand("nslookup", "myip.opendns.com", "resolver1.opendns.com").lines
} yield lines.filter(_.startsWith("Address:")).drop(1).headOption.map { a =>
a.drop(prefix.length).trim
}).mapError(CommandError.UnexpectedException)
.someOrFail(CommandError.InternalError("Could not parse nslookup results"))
}).mapError(CommandError.UnexpectedError(this))
.someOrFail(CommandError.UnexpectedError.fromMessage(this)("Could not parse nslookup results"))
case _ =>
PCommand("dig", "+short", "myip.opendns.com", "@resolver1.opendns.com").string
.mapBoth(CommandError.UnexpectedException, _.trim)
.mapError(CommandError.UnexpectedError(this))
.map(_.trim)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ final case class FileNavigationCommand(homeDirectory: Option[String]) extends Co
.renderedAnsi(fansi.Color.Blue(f.getAbsolutePath) ++ fansi.Str(" Open file location"))
.onRun(ProcessUtil.browseToFile(f))
},
pageSize = 10
initialPageSize = 10,
morePageSize = 20
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ final case class FindFileCommand(commandNames: List[String]) extends Command[Fil
Preview(file)
.rendered(Renderer.renderDefault(shortenedPath, "Open file"))
.onRun(PCommand("open", file.getAbsolutePath).exitCode.unit)
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
}
} yield PreviewResults.fromIterable(results)).mapError(UnexpectedException)
} yield PreviewResults.fromIterable(results)).mapError(CommandError.UnexpectedError(this))
} yield result
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ final case class FindInFileCommand(commandNames: List[String]) extends Command[F
Preview(file)
.rendered(Renderer.renderDefault(file.getAbsolutePath, "Open file"))
.onRun(PCommand("open", file.getAbsolutePath).exitCode.unit)
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
}
} yield PreviewResults.fromIterable(results)).mapError(UnexpectedException)
} yield PreviewResults.fromIterable(results)).mapError(CommandError.UnexpectedError(this))
} yield result
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ final case class Foobar2000Command(commandNames: List[String], foobarPath: File)
ZIO
.fromEither(foobarCommand.parse(input.args))
.mapBoth(
help => CommandError.ShowMessage(Rendered.Ansi(HelpMessage.formatted(help)), Scores.high(input.context)),
help =>
CommandError.ShowMessage(Rendered.Ansi(HelpMessage.formatted(help)), Scores.veryHigh(input.context)),
_.getOrElse(Opt.Show)
)
run = opt match {
Expand Down Expand Up @@ -93,7 +94,7 @@ final case class Foobar2000Command(commandNames: List[String], foobarPath: File)
} yield PreviewResults.one(
Preview.unit
.onRun(run.unit)
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
.rendered(Renderer.renderDefault(title, message))
)

Expand Down
4 changes: 2 additions & 2 deletions core/src/main/scala/commandcenter/command/HashCommand.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ final case class HashCommand(algorithm: String) extends Command[String] {
(valueToHash, charset) <- ZIO.fromEither(parsedCommand).mapError(CommandError.CliError)
hashResult <- ZIO
.fromEither(HashUtil.hash(algorithm)(valueToHash, charset))
.mapError(CommandError.UnexpectedException)
.mapError(CommandError.UnexpectedError(this))
} yield PreviewResults.one(
Preview(hashResult)
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
.onRun(Tools.setClipboard(hashResult))
.rendered(Renderer.renderDefault(algorithm, hashResult))
)
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/scala/commandcenter/command/HoogleCommand.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ final case class HoogleCommand(commandNames: List[String]) extends Command[Unit]
.send(request)
.map(_.body)
.absolve
.mapError(CommandError.UnexpectedException)
.mapError(CommandError.UnexpectedError(this))
results <- ZIO
.fromEither(
response.as[List[HoogleResult]]
)
.mapError(CommandError.UnexpectedException)
.mapError(CommandError.UnexpectedError(this))
} yield PreviewResults.fromIterable(results.map { result =>
Preview.unit
.onRun(ProcessUtil.openBrowser(result.url))
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
.renderedAnsi(
fansi.Color.Magenta(result.item) ++ " " ++ fansi.Color.Yellow(result.module.name) ++ " " ++ fansi.Color
.Cyan(result.`package`.name) ++ "\n" ++ result.docs
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/scala/commandcenter/command/ITunesCommand.scala
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ final case class ITunesCommand(commandNames: List[String], cache: Cache[String,

case _ => fansi.Str("not playing")
}
} yield detailsFormatted).mapError(CommandError.UnexpectedException)
} yield detailsFormatted).mapError(CommandError.UnexpectedError(this))
}
)
} yield {
Expand All @@ -116,7 +116,7 @@ final case class ITunesCommand(commandNames: List[String], cache: Cache[String,
PreviewResults.one(
Preview.unit
.onRun(run)
.score(Scores.high(input.context))
.score(Scores.veryHigh(input.context))
.rendered(Renderer.renderDefault(title, message))
)
}
Expand Down
Loading

0 comments on commit 907ea1b

Please sign in to comment.