Skip to content

Commit

Permalink
refactor: improve code
Browse files Browse the repository at this point in the history
  • Loading branch information
tassiluca committed Feb 29, 2024
1 parent bc68884 commit 14b0fd1
Show file tree
Hide file tree
Showing 20 changed files with 83 additions and 47 deletions.
4 changes: 0 additions & 4 deletions analyzer-commons/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,3 @@ dependencies {
implementation(libs.sttp.upickle)
api(project(":commons"))
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package io.github.tassiLuca.analyzer.commons.client

import io.github.tassiLuca.analyzer.commons.lib.RepositoryReport

type OrganizationReport = (Map[String, Long], Set[RepositoryReport])

trait AnalyzerView:
def run(): Unit
def update(result: OrganizationReport): Unit
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
package io.github.tassiLuca.analyzer.commons.client

import io.github.tassiLuca.analyzer.commons.lib.RepositoryReport

type OrganizationReport = (Map[String, Long], Set[RepositoryReport])

trait AppController:
def runSession(organizationName: String): Unit
def stopSession(): Unit

extension (organizationReport: OrganizationReport)
def mergeWith(report: RepositoryReport): OrganizationReport =
(organizationReport._1.aggregatedTo(report), organizationReport._2 + report)

extension (m: Map[String, Long])
def aggregatedTo(report: RepositoryReport): Map[String, Long] =
m ++ report.contributions.map(c => c.user -> (m.getOrElse(c.user, 0L) + c.contributions))
2 changes: 1 addition & 1 deletion analyzer-direct-kt/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ plugins {
}

dependencies {
api(project(":analyzer-commons"))
implementation(project(":analyzer-commons"))
implementation(libs.okttp)
implementation(libs.retrofit)
implementation(libs.retrofit.serialization.converter)
Expand Down
2 changes: 1 addition & 1 deletion analyzer-direct/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ dependencies {
implementation(libs.sttp.upickle)
implementation("eu.monniot:scala3mock_3:0.6.0")
implementation("eu.monniot:scala3mock-scalatest_3:0.6.0")
api(project(":analyzer-commons"))
implementation(project(":analyzer-commons"))
}

tasks.test {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,13 @@ object AppController:

view.run()

override def stopSession(): Unit = currentComputation.foreach(_.cancel())

override def runSession(organizationName: String): Unit =
var organizationReport: OrganizationReport = (Map(), Set())
val f = Future:
analyzer.analyze(organizationName) { report =>
organizationReport = (organizationReport._1.aggregatedTo(report), organizationReport._2 + report)
organizationReport = organizationReport.mergeWith(report)
view.update(organizationReport)
} match { case Left(e) => view.error(e); case _ => view.endComputation() }
currentComputation = Some(f)

extension (m: Map[String, Long])
private def aggregatedTo(report: RepositoryReport): Map[String, Long] =
m ++ report.contributions.map(c => c.user -> (m.getOrElse(c.user, 0L) + c.contributions))
override def stopSession(): Unit = currentComputation.foreach(_.cancel())
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package io.github.tassiLuca.analyzer.lib
import gears.async.Future.Collector
import gears.async.{Async, Future}
import io.github.tassiLuca.analyzer.commons.lib.{Repository, RepositoryReport}
import io.github.tassiLuca.boundaries.EitherConversions.given
import io.github.tassiLuca.boundaries.either
import io.github.tassiLuca.boundaries.either.?
import io.github.tassiLuca.boundaries.EitherConversions.given
import io.github.tassiLuca.pimping.ChannelsPimping.tryable
import io.github.tassiLuca.pimping.ChannelsPimping.toTry

import scala.util.boundary.Label

private class BasicAnalyzer(repositoryService: RepositoryService) extends Analyzer:

Expand All @@ -15,7 +17,7 @@ private class BasicAnalyzer(repositoryService: RepositoryService) extends Analyz
)(using Async): Either[String, Seq[RepositoryReport]] = either:
val reposInfo = repositoryService.repositoriesOf(organizationName).?.map(_.performAnalysis)
val collector = Collector[RepositoryReport](reposInfo.toList*)
for _ <- reposInfo.indices do updateResults(collector.results.read().tryable.?.awaitResult.?)
for _ <- reposInfo.indices do updateResults(collector.results.read().toTry().?.awaitResult.?)
reposInfo.map(_.await)

extension (r: Repository)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import io.github.tassiLuca.analyzer.commons.lib.{Repository, RepositoryReport}
import io.github.tassiLuca.boundaries.either
import io.github.tassiLuca.boundaries.either.?
import io.github.tassiLuca.boundaries.EitherConversions.given
import io.github.tassiLuca.pimping.ChannelsPimping.tryable
import io.github.tassiLuca.pimping.ChannelsPimping.toTry

private class IncrementalAnalyzer(repositoryService: RepositoryService) extends Analyzer:

Expand All @@ -22,7 +22,7 @@ private class IncrementalAnalyzer(repositoryService: RepositoryService) extends
}
var allReports = Seq[RepositoryReport]()
for _ <- 0 until collectedRepositories do
val report = collector.results.read().tryable.?.awaitResult.?
val report = collector.results.read().toTry().?.awaitResult.?
updateResults(report)
allReports = allReports :+ report
allReports
Expand Down
36 changes: 33 additions & 3 deletions analyzer-monadic/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,39 @@ dependencies {
implementation(libs.cats.core)
implementation("com.softwaremill.sttp.client3:async-http-client-backend-monix_3:3.9.3")
implementation("io.monix:monix_3:3.4.1")
api(project(":analyzer-commons"))
implementation(project(":analyzer-commons"))
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
tasks.test {
loadProjectEnvironmentVariables().forEach(environment::put)
}

tasks.create<JavaExec>("run") {
group = "Application"
description = "Runs the client application."
loadProjectEnvironmentVariables().forEach(environment::put)
mainClass.set("io.github.tassiLuca.analyzer.client.monadicAnalyzerLauncher")
classpath = sourceSets["main"].runtimeClasspath
}

fun loadProjectEnvironmentVariables(): Map<String, String> {
val envs = if (System.getenv().containsKey("GH_TOKEN")) {
mapOf("GH_TOKEN" to System.getenv("GH_TOKEN"))
} else {
file(rootDir.path).resolveAll("analyzer-commons", ".env").loadEnvironmentVariables()
}
return envs.also {
require(it.contains("GH_TOKEN")) {
"`GH_TOKEN` env variable is required either via `.env` file (in analyzer-commons) or system environment."
}
}
}

fun File.resolveAll(vararg paths: String): File = paths.fold(this) { f, s -> f.resolve(s) }

fun File.loadEnvironmentVariables(): Map<String, String> = runCatching {
readLines().associate {
val (key, value) = it.split("=")
key to value
}
}.getOrElse { emptyMap() }
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,9 @@ object AppController:
override def runSession(organizationName: String): Unit =
var organizationReport: OrganizationReport = (Map(), Set())
val f = analyzer.analyze(organizationName) { report =>
organizationReport = (organizationReport._1.aggregatedTo(report), organizationReport._2 + report)
organizationReport = organizationReport.mergeWith(report)
view.update(organizationReport)
}.value.runToFuture.map { case Left(value) => view.error(value); case Right(_) => view.endComputation() }
currentComputation = Some(f)

override def stopSession(): Unit = currentComputation foreach (_.cancel())

extension (m: Map[String, Long])
private def aggregatedTo(report: RepositoryReport): Map[String, Long] =
m ++ report.contributions.map(c => c.user -> (m.getOrElse(c.user, 0L) + c.contributions))
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ object Analyzer:
def ofGitHub(): Analyzer = AnalyzerImpl()

private class AnalyzerImpl extends Analyzer:
private val gitHubService = GitHubService()
private val gitHubService = RepositoryService()

override def analyze(organizationName: String)(
updateResult: RepositoryReport => Unit,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import cats.data.EitherT
import io.github.tassiLuca.analyzer.commons.lib.{Contribution, Release, Repository}
import monix.eval.Task

trait GitHubService:
trait RepositoryService:
def repositoriesOf(organizationName: String): EitherT[Task, String, Seq[Repository]]
def contributorsOf(organizationName: String, repositoryName: String): EitherT[Task, String, Seq[Contribution]]
def lastReleaseOf(organizationName: String, repositoryName: String): EitherT[Task, String, Release]

object GitHubService:
def apply(): GitHubService = GitHubServiceImpl()
object RepositoryService:
def apply(): RepositoryService = GitHubServiceImpl()

private class GitHubServiceImpl extends GitHubService:
private class GitHubServiceImpl extends RepositoryService:
import sttp.client3.httpclient.monix.HttpClientMonixBackend
import sttp.client3.{UriContext, basicRequest}
import sttp.model.Uri
Expand Down
2 changes: 1 addition & 1 deletion blog-ws-monadic/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
dependencies {
api(project(":blog-ws-commons"))
implementation(project(":blog-ws-commons"))
}
4 changes: 4 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,8 @@ allprojects {
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
}
}

tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ object either:
boundary(Right(body))

/** Quickly break to the enclosing boundary with a [[Left]] filled with [[l]]. */
inline def left[L, R](l: L)(using Label[Left[L, Nothing]]): Either[L, R] = break(Left(l))
inline def left[L, R](l: L)(using Label[Left[L, Nothing]]): Nothing = break(Left(l))

extension [L, R](e: Either[L, R])
/** @return this [[Right]] value or break to the enclosing boundary with the [[Left]] value. */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package io.github.tassiLuca
package io.github.tassiLuca.examples

import gears.async.default.given
import gears.async.TaskSchedule.Every
import gears.async.{Async, BufferedChannel, Channel, ChannelMultiplexer, Future, SendableChannel, Task}
import gears.async.default.given
import gears.async.*

import java.time.LocalTime
import scala.util.{Random, Try}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package io.github.tassiLuca
package io.github.tassiLuca.examples

import gears.async.default.given
import gears.async.AsyncOperations.sleep
import gears.async.TaskSchedule.Every
import gears.async.{Async, BufferedChannel, ReadableChannel, SendableChannel, Task, TaskSchedule}
import gears.async.default.given
import gears.async.*

import java.time.LocalTime

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package io.github.tassiLuca.pimping

import gears.async.{Async, Channel, ReadableChannel, SendableChannel}
import gears.async.{Async, Channel, ChannelClosedException, ReadableChannel, SendableChannel}
import io.github.tassiLuca.boundaries.either.?
import io.github.tassiLuca.boundaries.EitherConversions.given

import scala.annotation.tailrec
import scala.reflect.ClassTag
import scala.util.boundary.Label
import scala.util.{Failure, Success, Try}

object ChannelsPimping:
Expand Down Expand Up @@ -37,6 +40,6 @@ object ChannelsPimping:
results

extension [T](e: Either[Channel.Closed, T])
def tryable: Try[T] = e match
case Left(Channel.Closed) => Failure(IllegalStateException("Closed Channel!"))
def toTry(): Try[T] = e match
case Left(Channel.Closed) => Failure(ChannelClosedException())
case Right(t) => Success[T](t)
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package io.github.tassiLuca.rears

import gears.async.TaskSchedule.RepeatUntilFailure
import gears.async.{Async, ChannelMultiplexer, ReadableChannel, Task}
import io.github.tassiLuca.pimping.ChannelsPimping.tryable
import io.github.tassiLuca.pimping.ChannelsPimping.toTry

object Controller:

Expand All @@ -16,7 +16,7 @@ object Controller:
): Task[Unit] =
val transformedChannel = transformation(publisherChannel)
Task {
consumer.listeningChannel.send(transformedChannel.read().tryable)
consumer.listeningChannel.send(transformedChannel.read().toTry())
}.schedule(RepeatUntilFailure())

/** Creates a runnable [[Task]] forwarding the items read from the [[publisherChannel]] to
Expand Down
3 changes: 1 addition & 2 deletions smart-hub-direct/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ plugins {
}

dependencies {
api(project(":commons"))
api(project(":rears"))
implementation(project(":rears"))
}

application {
Expand Down

0 comments on commit 14b0fd1

Please sign in to comment.