Skip to content

Commit 1cce68d

Browse files
committed
minro fixes, prmopt changes, bump version
1 parent 64e16b8 commit 1cce68d

File tree

11 files changed

+402
-79
lines changed

11 files changed

+402
-79
lines changed

src/main/java/com/dtsx/astra/cli/commands/SetupCmd.java

Lines changed: 32 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
import java.util.List;
2727
import java.util.Optional;
2828
import java.util.function.Supplier;
29+
import java.util.stream.Collectors;
30+
import java.util.stream.Stream;
2931

3032
import static com.dtsx.astra.cli.core.output.ExitCode.INVALID_TOKEN;
3133
import static com.dtsx.astra.cli.core.output.ExitCode.UNSUPPORTED_EXECUTION;
@@ -155,6 +157,14 @@ protected Operation<SetupResult> mkOperation() {
155157
}
156158

157159
private void assertShouldSetup(Path existing) {
160+
assertShouldSetup(existing, true);
161+
}
162+
163+
private void assertShouldContinueIfAlreadySetup(Path existing) {
164+
assertShouldSetup(existing, false);
165+
}
166+
167+
private void assertShouldSetup(Path path, boolean newUser) {
158168
ctx.log().banner();
159169

160170
if (ctx.isNotTty()) {
@@ -170,57 +180,39 @@ private void assertShouldSetup(Path existing) {
170180
}
171181

172182
val prompt = """
173-
@|bold Welcome to the Astra CLI setup!|@
174-
175-
@|faint A configuration file with your profile will be created at|@ @|faint,italic %s|@
183+
@|bold Welcome to the interactive Astra CLI setup!|@
176184
177-
If you'd prefer to provide credentials on a per-command basis rather than storing them in a file, you can either:
178-
- Use the per-command @'!--token!@ flag to pass your existing @!AstraCS!@ token directly.
179-
- Use the per-command @'!--config-file!@ flag to specify an existing @!.astrarc!@ file.
180-
181-
%s
182-
%s
185+
@|faint Your configuration file %s at|@ @|faint,italic %s|@
183186
""".formatted(
184-
existing,
185-
renderComment(ctx.colors(), "Example:"),
186-
renderCommand(ctx.colors(), "${cli.name} db list --token <your_token>")
187+
(newUser) ? "will be created" : "already exists",
188+
path
187189
);
188190

189-
ctx.console().println(trimIndent(prompt));
191+
val addendum = (!newUser)
192+
? NL + NL + "Do you want to continue and create a new profile?"
193+
: mkArgsAddendum();
194+
195+
ctx.console().println(trimIndent(prompt) + addendum);
190196
ctx.console().println();
191197
ctx.console().unsafeReadLine(ctx.colors().format("Press @!Enter!@ to continue, or use @!Ctrl+C!@ to cancel. "), false);
192198
ctx.console().println();
193199
}
194200

195-
private void assertShouldContinueIfAlreadySetup(Path existing) {
196-
ctx.log().banner();
201+
private String mkArgsAddendum() {
202+
if ($env.isEmpty() && $token.isEmpty()) {
203+
if ($name.isPresent()) {
204+
return "%n%n@|faint The profile will be called '%s'.|@".formatted($name.get());
205+
}
206+
return "";
207+
}
197208

198-
val prompt = """
199-
@|bold Looks like you're already set up!|@
200-
201-
@|faint Your config file already exists at|@ @|faint,italic %s|@
202-
203-
Hint: You can use the @'!${cli.name} config!@ commands to manage your profiles.
204-
205-
%s
206-
%s
207-
208-
Do you want to continue and create a new profile?
209-
""".formatted(
210-
existing,
211-
renderComment(ctx.colors(), "Example:"),
212-
renderCommand(ctx.colors(), "${cli.name} config list")
209+
return "%n%n@|faint %s will be created%s.|@".formatted(
210+
$name.map(n -> "Profile '" + n + "'").orElse("The profile"),
211+
Stream.concat(
212+
$token.stream().map(t -> " with token " + t),
213+
$env.stream().map(e -> " in env '" + e.name().toLowerCase() + "'")
214+
).collect(Collectors.joining(""))
213215
);
214-
215-
val shouldContinue = ctx.console().confirm(prompt)
216-
.defaultYes()
217-
.fallbackFlag("")
218-
.fix(List.of(), "")
219-
.clearAfterSelection();
220-
221-
if (!shouldContinue) {
222-
throw new ExecutionCancelledException();
223-
}
224216
}
225217

226218
private void assertShouldOverwriteExistingProfile(Profile existing) {

src/main/java/com/dtsx/astra/cli/commands/UpgradeCmd.java

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import com.dtsx.astra.cli.AstraCli;
44
import com.dtsx.astra.cli.core.datatypes.Unit;
5-
import com.dtsx.astra.cli.core.exceptions.internal.cli.ExecutionCancelledException;
65
import com.dtsx.astra.cli.core.help.Example;
76
import com.dtsx.astra.cli.core.models.Version;
87
import com.dtsx.astra.cli.core.output.formats.OutputHuman;
@@ -68,12 +67,6 @@ public static class VersionMod {
6867
public boolean $includePreReleases;
6968
}
7069

71-
@Option(
72-
names = { "-y", "--yes" },
73-
description = "Install the upgrade without any confirmation prompting"
74-
)
75-
public boolean $yes;
76-
7770
@Option(
7871
names = { "--allow-reinstall" },
7972
description = "Allow re-installing the same version"
@@ -115,20 +108,6 @@ protected void confirmUpgrade(Version version, String moveCommand) {
115108
);
116109

117110
ctx.console().println(trimIndent(infoMsg));
118-
119-
if ($yes) {
120-
return;
121-
}
122-
123-
val proceed = ctx.console().confirm(NL + NL + "Do you want to proceed?")
124-
.defaultYes()
125-
.fallbackFlag("--yes")
126-
.fix(originalArgs(), "--yes")
127-
.clearAfterSelection();
128-
129-
if (!proceed) {
130-
throw new ExecutionCancelledException();
131-
}
132111
}
133112

134113
@Override

src/main/java/com/dtsx/astra/cli/core/models/Version.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
@EqualsAndHashCode
1616
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
1717
public class Version implements Highlightable, Comparable<Version> {
18-
private static final Pattern VERSION_PATTERN = Pattern.compile("^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-zA-Z0-9-_]+\\.\\d+))?$");
18+
private static final Pattern VERSION_PATTERN = Pattern.compile("^v?(\\d+)\\.(\\d+)(?:\\.(\\d+))?(?:-([a-zA-Z0-9-_]+\\.\\d+))?$");
1919

2020
private final int major;
2121
private final int minor;
@@ -29,7 +29,7 @@ public static Either<String, Version> parse(String version) {
2929
if (matcher.matches()) {
3030
val major = Integer.parseInt(matcher.group(1));
3131
val minor = Integer.parseInt(matcher.group(2));
32-
val patch = Integer.parseInt(matcher.group(3));
32+
val patch = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;
3333

3434
val preRelease = Optional.ofNullable(matcher.group(4))
3535
.map((pr) -> {
@@ -39,7 +39,7 @@ public static Either<String, Version> parse(String version) {
3939

4040
return Either.pure(new Version(major, minor, patch, preRelease));
4141
} else {
42-
return Either.left("Invalid version format: " + trimmed + " (expected format: x.y.z[-<label>.n])");
42+
return Either.left("Invalid version format: " + trimmed + " (expected format: x.y[.z][-<label>.n])");
4343
}
4444
});
4545
}

src/main/java/com/dtsx/astra/cli/core/upgrades/UpgradeNotifier.java

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,13 @@ public static String buildAnnoyingText(CliContext ctx, UpgradeStatus status) {
4949
val latestVersion = status.latestVersion().orElseThrow().toString();
5050

5151
val versionMsg = "Update available! " + ctx.colors().NEUTRAL_400.use(currentVersion) + " -> " + ctx.colors().YELLOW_300.use(latestVersion);
52-
val commandMsg = mkUpgradeCommandMsg(ctx);
52+
val commandMsg = ctx.colors().format(mkUpgradeCommandMsg(ctx));
5353

5454
val versionMsgLength = stripAnsi(versionMsg).length();
5555
val commandMsgLength = stripAnsi(commandMsg).length();
5656

5757
val maxTextWidth = Math.max(versionMsgLength, commandMsgLength);
58-
val boxWidth = Math.max(versionMsgLength, commandMsgLength) + PADDING * 2;
58+
val boxWidth = Math.max(versionMsgLength, commandMsgLength) + PADDING * 2 + 2;
5959

6060
val main = new StringBuilder();
6161
val blue = ctx.colors().BLUE_300;
@@ -84,14 +84,18 @@ private static String mkUpgradeCommandMsg(CliContext ctx) {
8484
}
8585

8686
private static void appendFillerLine(StringBuilder main, int boxWidth, AstraColor blue, char l, char m, char r) {
87-
main.append(blue.on()).append(l).repeat(m, boxWidth).append(r).append(blue.off()).append(NL);
87+
main.append(blue.on()).append(l).repeat(m, boxWidth - 2).append(r).append(blue.off()).append(NL);
8888
}
8989

9090
private static void appendTextualLine(StringBuilder main, String text, int maxTextWidth, int actualLength, AstraColor blue) {
91+
int leftPadding = PADDING + Math.floorDiv(maxTextWidth - actualLength, 2);
92+
int contentWidth = maxTextWidth + 2 * PADDING;
93+
int rightPadding = contentWidth - actualLength - leftPadding;
94+
9195
main.append(blue.on()).append("│").append(blue.off())
92-
.repeat(' ', PADDING + Math.floorDiv(maxTextWidth - actualLength, 2))
96+
.repeat(' ', leftPadding)
9397
.append(text)
94-
.repeat(' ', PADDING + Math.ceilDiv(maxTextWidth - actualLength, 2))
98+
.repeat(' ', rightPadding)
9599
.append(blue.on()).append("│").append(blue.off())
96100
.append(NL);
97101
}

src/main/java/com/dtsx/astra/cli/core/upgrades/UpgradeStatus.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,14 @@ private static Optional<UpgradeStatus> loadFromExistingPath(Properties propertie
3838
val rawLastChecked = properties.getProperty(LAST_CHECKED_KEY);
3939
val rawLastNotified = properties.getProperty(LAST_NOTIFIED_KEY);
4040

41-
if (rawLatestVersion == null || rawLastChecked == null) {
41+
if (rawLatestVersion == null || rawLastChecked == null || rawLastNotified == null) {
4242
ctx.log().exception("Upgrade notifier properties file is missing required keys. Recreating it.");
4343
return createNewStatusFile(properties, ctx, path);
4444
}
4545

4646
val version = Optional.of(rawLatestVersion).filter(s -> !s.isEmpty()).map(Version::parse);
4747
val lastChecked = Either.tryCatch(() -> Long.parseLong(rawLastChecked), Exception::getMessage);
48-
val lastNotified = Either.tryCatch(() -> Long.parseLong(rawLastNotified), Exception::getMessage);
48+
val lastNotified = Either.tryCatch(() -> Long.parseLong(rawLastNotified), Exception::getMessage);
4949

5050
if (version.isPresent() && version.get().isLeft()) {
5151
ctx.log().exception("Upgrade notifier properties file has invalid latest version value '" + rawLatestVersion + "'. Recreating it.");

src/main/java/com/dtsx/astra/cli/core/upgrades/UpgradeStatusKeeper.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ private static String runUnix(CliContext ctx, UpgradeStatus status, Path path, b
9494
# update properties file
9595
echo "LATEST_VERSION=$latest_version
9696
LAST_CHECKED=$last_checked
97-
LAST_NOTIFIED=$last_notified" > "$(printf %%q '%s')"
97+
LAST_NOTIFIED=$last_notified" > '%s'
9898
""").formatted(pathStr);
9999

100100
return script;

src/main/java/com/dtsx/astra/cli/gateways/upgrade/UpgradeGatewayImpl.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ private Version fetchLatestFullRelease() {
4848

4949
val json = JsonUtils.readTree(response.body());
5050

51+
System.out.println(json.get("tag_name").asText());
52+
5153
return Version.mkUnsafe(json.get("tag_name").asText());
5254
});
5355
}
@@ -57,17 +59,17 @@ private Version fetchLatestIncPreRelease() {
5759
var attempt = 1;
5860

5961
while (true) {
60-
val endpoint = ctx.properties().cliGithubApiReposUrl() + "/releases?per_page=1";
62+
val endpoint = ctx.properties().cliGithubApiReposUrl() + "/releases?per_page=1&page=" + attempt;
6163

6264
val response = HttpUtils.GET(endpoint, c -> c, r -> r);
6365

6466
if (response.statusCode() >= 400 && response.statusCode() != 404) {
6567
throw new AstraCliException(ExitCode.RELEASE_NOT_FOUND, """
6668
@|bold,red An error occurred while fetching the latest release from %s|@
67-
69+
6870
Status:
6971
@!%d!@
70-
72+
7173
Body:
7274
%s
7375
""".formatted(endpoint, response.statusCode(), response.body()));
@@ -81,6 +83,7 @@ private Version fetchLatestIncPreRelease() {
8183
""".formatted(endpoint));
8284
}
8385

86+
// very, very unlikely to happen
8487
if (json.isArray() && json.get(0).get("draft").asBoolean()) {
8588
updateMsg.accept("Resolving latest release of @!astra!@ (attempt %d)".formatted(++attempt));
8689
continue;

src/main/java/com/dtsx/astra/cli/operations/UpgradeOperation.java

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public Unit execute() {
5858
}
5959

6060
val backupMvCmd = ctx.isWindows()
61-
? "rename %s %s".formatted(newExePath.getRight(), currentExePath)
61+
? "move /Y \"%s\" \"%s\"".formatted(newExePath.getRight(), currentExePath)
6262
: "mv %s %s".formatted(newExePath.getRight(), currentExePath);
6363

6464
request.confirmUpgrade().accept(version, backupMvCmd);
@@ -147,7 +147,7 @@ case SpecificVersion(var version) -> {
147147
""".formatted(version));
148148
}
149149

150-
if (version.equals(ctx.properties().version()) && !request.allowSameVersion()) {
150+
if (version.equals(ctx.properties().version()) && !request.allowSameVersion) {
151151
throw new AstraCliException(ExitCode.RELEASE_NOT_FOUND, """
152152
@|bold,red Error: You are already using Astra CLI v%s|@
153153
""".formatted(version));
@@ -159,7 +159,13 @@ case SpecificVersion(var version) -> {
159159
case LatestVersion(var includePreReleases) -> {
160160
val latest = upgradeGateway.latestVersion(includePreReleases);
161161

162-
if (latest.compareTo(ctx.properties().version()) < 1) {
162+
if (latest.equals(ctx.properties().version()) && !request.allowSameVersion) {
163+
throw new AstraCliException(ExitCode.RELEASE_NOT_FOUND, """
164+
@|bold,red Error: You are already using the latest Astra CLI version (v%s)|@
165+
""".formatted(latest));
166+
}
167+
168+
if (latest.compareTo(ctx.properties().version()) < 0) {
163169
throw new AstraCliException(ExitCode.RELEASE_NOT_FOUND, """
164170
@|bold,red Error: No newer version available (latest is v%s, you have v%s)|@
165171
""".formatted(latest, ctx.properties().version()));

src/test/java/com/dtsx/astra/cli/unit/core/models/VersionTest.java

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,29 @@ private void gt(String v1, String v2) {
6969
assertThat(Version.mkUnsafe(v1)).isGreaterThan(Version.mkUnsafe(v2));
7070
}
7171

72-
public void eq(String v1, String v2) {
72+
private void eq(String v1, String v2) {
7373
assertThat(Version.mkUnsafe(v1)).isEqualTo(Version.mkUnsafe(v2));
7474
}
7575
}
7676

77+
@Group
78+
public class short_version_format {
79+
@Example
80+
public void parses_two_part_versions_as_zero_patch() {
81+
assertThat(Version.mkUnsafe("0.6").toString()).isEqualTo("0.6.0");
82+
assertThat(Version.mkUnsafe("1.2").toString()).isEqualTo("1.2.0");
83+
assertThat(Version.mkUnsafe("v1.5").toString()).isEqualTo("1.5.0");
84+
}
85+
86+
@Example
87+
public void compares_short_versions_correctly() {
88+
assertThat(Version.mkUnsafe("0.6")).isEqualTo(Version.mkUnsafe("0.6.0"));
89+
assertThat(Version.mkUnsafe("1.2")).isEqualTo(Version.mkUnsafe("1.2.0"));
90+
assertThat(Version.mkUnsafe("1.2")).isGreaterThan(Version.mkUnsafe("1.1.0"));
91+
assertThat(Version.mkUnsafe("1.2")).isGreaterThan(Version.mkUnsafe("1.1"));
92+
}
93+
}
94+
7795
@Provide
7896
private Arbitrary<String> version() {
7997
return Arbitraries.integers().greaterOrEqual(0).list().ofSize(4).flatMap((nums) -> {

0 commit comments

Comments
 (0)