Skip to content

Commit 16d34b4

Browse files
committed
refacto
1 parent a7eaaa5 commit 16d34b4

File tree

1 file changed

+62
-58
lines changed

1 file changed

+62
-58
lines changed

sbt-plugin/src/main/scala/ch/epfl/scala/SubmitDependencyGraph.scala

Lines changed: 62 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -23,22 +23,31 @@ import sjsonnew.support.scalajson.unsafe.{Parser => JsonParser, _}
2323

2424
object SubmitDependencyGraph {
2525
val Submit = "githubSubmitDependencyGraph"
26-
val Generate = "generateDependencyGraph"
27-
val usage: String = s"""$Submit {"projects":[], "scalaVersions":[]}"""
2826
val brief = "Submit the dependency graph to Github Dependency API."
2927
val detail = "Submit the dependency graph of a set of projects and scala versions to Github Dependency API"
28+
val Generate = "generateDependencyGraph"
3029
val briefGenerate = "Generate the dependency graph"
3130
val detailGenerate = "Generate the dependency graph of a set of projects and scala versions"
31+
val commands = Seq(
32+
new SubmitDependencyGraph(true, Generate, briefGenerate, detailGenerate),
33+
new SubmitDependencyGraph(false, Submit, brief, detail)
34+
).flatMap(_.commands)
35+
}
36+
37+
class SubmitDependencyGraph(
38+
val local: Boolean,
39+
val command: String,
40+
val brief: String,
41+
val detail: String
42+
) {
43+
val usage: String = s"""$command {"projects":[], "scalaVersions":[]}"""
3244

33-
val SubmitInternal: String = s"${Submit}Internal"
34-
val SubmitInternalLocal: String = s"${Submit}InternalLocal"
45+
val internalCommand = s"${command}Internal"
3546
val internalOnly = "internal usage only"
3647

3748
val commands: Seq[Command] = Seq(
38-
Command(Submit, (usage, brief), detail)(inputParser)(submit(false)),
39-
Command(Generate, (usage, briefGenerate), detailGenerate)(inputParser)(submit(true)),
40-
Command.command(SubmitInternal, internalOnly, internalOnly)(submitInternal(false)),
41-
Command.command(SubmitInternalLocal, internalOnly, internalOnly)(submitInternal(true))
49+
Command(command, (usage, brief), detail)(inputParser)(submit),
50+
Command.command(internalCommand, internalOnly, internalOnly)(submitInternal)
4251
)
4352

4453
private lazy val http: HttpClient = Gigahorse.http(Gigahorse.config)
@@ -51,8 +60,8 @@ object SubmitDependencyGraph {
5160
.get
5261
}.failOnException
5362

54-
private def submit(local: Boolean)(state: State, input: SubmitInput): State = {
55-
checkGithubEnv(local) // fail fast if the Github CI environment is incomplete
63+
private def submit(state: State, input: SubmitInput): State = {
64+
checkGithubEnv() // fail fast if the Github CI environment is incomplete
5665
val loadedBuild = state.setting(Keys.loadedBuild)
5766
// all project refs that have a Scala version
5867
val projectRefs = loadedBuild.allProjectRefs
@@ -64,7 +73,7 @@ object SubmitDependencyGraph {
6473
.distinct
6574

6675
val root = Paths.get(loadedBuild.root).toAbsolutePath
67-
val workspace = Paths.get(githubWorkspace(local)).toAbsolutePath
76+
val workspace = Paths.get(githubWorkspace()).toAbsolutePath
6877
val buildFile =
6978
if (root.startsWith(workspace)) workspace.relativize(root).resolve("build.sbt")
7079
else root.resolve("build.sbt")
@@ -79,16 +88,13 @@ object SubmitDependencyGraph {
7988
val storeAllManifests = scalaVersions.flatMap { scalaVersion =>
8089
Seq(s"++$scalaVersion", s"Global/${githubStoreDependencyManifests.key} $scalaVersion")
8190
}
82-
val commands = storeAllManifests :+ {
83-
if (local) { SubmitInternalLocal }
84-
else { SubmitInternal }
85-
}
91+
val commands = storeAllManifests :+ internalCommand
8692
commands.toList ::: initState
8793
}
8894

89-
private def submitInternal(local: Boolean)(state: State): State = {
90-
val snapshot = githubDependencySnapshot(local)(state)
91-
val snapshotUrl = s"${githubApiUrl(local)}/repos/${githubRepository(local)}/dependency-graph/snapshots"
95+
private def submitInternal(state: State): State = {
96+
val snapshot = githubDependencySnapshot(state)
97+
val snapshotUrl = s"${githubApiUrl()}/repos/${githubRepository()}/dependency-graph/snapshots"
9298

9399
val snapshotJson = CompactPrinter(Converter.toJsonUnsafe(snapshot))
94100

@@ -98,7 +104,8 @@ object SubmitDependencyGraph {
98104
file
99105
}
100106

101-
if (!local) {
107+
if (local) state
108+
else {
102109

103110
val request = Gigahorse
104111
.url(snapshotUrl)
@@ -107,6 +114,7 @@ object SubmitDependencyGraph {
107114
"Content-Type" -> "application/json",
108115
"Authorization" -> s"token ${githubToken()}"
109116
)
117+
110118
state.log.info(s"Submiting dependency snapshot of job ${snapshot.job} to $snapshotUrl")
111119
val result = for {
112120
httpResp <- Try(Await.result(http.processFull(request), Duration.Inf))
@@ -120,17 +128,14 @@ object SubmitDependencyGraph {
120128
)
121129
state
122130
}
131+
123132
result.get
124-
} else {
125-
state.log.info(s"Local mode: skipping submission")
126-
state
127133
}
128-
129134
}
130135

131136
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-output-parameter
132137
private def setGithubOutputs(outputs: (String, String)*): Unit = IO.writeLines(
133-
file(githubOutput(false)),
138+
file(githubOutput),
134139
outputs.toSeq.map { case (name, value) => s"${name}=${value}" },
135140
append = true
136141
)
@@ -147,7 +152,7 @@ object SubmitDependencyGraph {
147152
throw new MessageOnlyException(message)
148153
}
149154

150-
private def githubDependencySnapshot(local: Boolean)(state: State): DependencySnapshot = {
155+
private def githubDependencySnapshot(state: State): DependencySnapshot = {
151156
val detector = DetectorMetadata(
152157
SbtGithubDependencySubmission.name,
153158
SbtGithubDependencySubmission.homepage.map(_.toString).getOrElse(""),
@@ -157,19 +162,19 @@ object SubmitDependencyGraph {
157162
val manifests = state.get(githubManifestsKey).get
158163
DependencySnapshot(
159164
0,
160-
githubJob(local),
161-
githubSha(local),
162-
githubRef(local),
165+
githubJob(),
166+
githubSha(),
167+
githubRef(),
163168
detector,
164169
Map.empty[String, JValue],
165170
manifests,
166171
scanned.toString
167172
)
168173
}
169174

170-
private def githubJob(local: Boolean): Job = {
171-
val correlator = s"${githubWorkflow(local)}_${githubJobName(local)}_${githubAction(local)}"
172-
val id = githubRunId(local)
175+
private def githubJob(): Job = {
176+
val correlator = s"${githubWorkflow()}_${githubJobName()}_${githubAction()}"
177+
val id = githubRunId
173178
val html_url =
174179
for {
175180
serverUrl <- Properties.envOrNone("GITHUB_SERVER_URL")
@@ -178,34 +183,33 @@ object SubmitDependencyGraph {
178183
Job(correlator, id, html_url)
179184
}
180185

181-
private def checkGithubEnv(local: Boolean = false): Unit = {
182-
githubWorkspace(local)
183-
githubWorkflow(local)
184-
githubJobName(local)
185-
githubAction(local)
186-
githubRunId(local)
187-
githubSha(local)
188-
githubRef(local)
189-
githubApiUrl(local)
190-
githubRepository(local)
191-
githubToken(local)
186+
private def checkGithubEnv(): Unit = {
187+
githubWorkspace()
188+
githubWorkflow()
189+
githubJobName()
190+
githubAction()
191+
githubRunId()
192+
githubSha()
193+
githubRef()
194+
githubApiUrl()
195+
githubRepository()
196+
githubToken()
192197
}
193198

194-
private def githubWorkspace(local: Boolean = false): String = githubCIEnv("GITHUB_WORKSPACE", local)
195-
private def githubWorkflow(local: Boolean = false): String = githubCIEnv("GITHUB_WORKFLOW", local)
196-
private def githubJobName(local: Boolean = false): String = githubCIEnv("GITHUB_JOB", local)
197-
private def githubAction(local: Boolean = false): String = githubCIEnv("GITHUB_ACTION", local)
198-
private def githubRunId(local: Boolean = false): String = githubCIEnv("GITHUB_RUN_ID", local)
199-
private def githubSha(local: Boolean = false): String = githubCIEnv("GITHUB_SHA", local)
200-
private def githubRef(local: Boolean = false): String = githubCIEnv("GITHUB_REF", local)
201-
private def githubApiUrl(local: Boolean = false): String = githubCIEnv("GITHUB_API_URL", local)
202-
private def githubRepository(local: Boolean = false): String = githubCIEnv("GITHUB_REPOSITORY", local)
203-
private def githubToken(local: Boolean = false): String = githubCIEnv("GITHUB_TOKEN", local)
204-
private def githubOutput(local: Boolean = false): String = githubCIEnv("GITHUB_OUTPUT", local)
205-
206-
private def githubCIEnv(name: String, local: Boolean = false): String =
207-
Properties.envOrNone(name).getOrElse {
208-
if (local) ""
209-
else throw new MessageOnlyException(s"Missing environment variable $name. This task must run in a Github Action.")
199+
private def githubWorkspace(): String = githubCIEnv("GITHUB_WORKSPACE")
200+
private def githubWorkflow(): String = githubCIEnv("GITHUB_WORKFLOW")
201+
private def githubJobName(): String = githubCIEnv("GITHUB_JOB")
202+
private def githubAction(): String = githubCIEnv("GITHUB_ACTION")
203+
private def githubRunId(): String = githubCIEnv("GITHUB_RUN_ID")
204+
private def githubSha(): String = githubCIEnv("GITHUB_SHA")
205+
private def githubRef(): String = githubCIEnv("GITHUB_REF")
206+
private def githubApiUrl(): String = githubCIEnv("GITHUB_API_URL")
207+
private def githubRepository(): String = githubCIEnv("GITHUB_REPOSITORY")
208+
private def githubToken(): String = githubCIEnv("GITHUB_TOKEN")
209+
private def githubOutput(): String = githubCIEnv("GITHUB_OUTPUT")
210+
211+
private def githubCIEnv(name: String): String =
212+
Properties.envOrNone(name).orElse(Some("").find(_ => local)).getOrElse {
213+
throw new MessageOnlyException(s"Missing environment variable $name. This task must run in a Github Action.")
210214
}
211215
}

0 commit comments

Comments
 (0)