fix(config): write profiles and config atomically and report files that cannot be read

Profile files and ~/.floci/config.yaml are replaced through a temporary file, so an interrupted write leaves the old file intact; an unknown key in config.yaml no longer resets the default product to aws, and an unreadable config.yaml or profile file is reported on stderr instead of being ignored.
This commit is contained in:
Hector Ventura committed 2026-10-09 17:16:47 -05:00
1 parent 0746e1a61c
commit afe712a165
5 files changed
+161 -5

No files matched your search

@@ -0,0 +1,33 @@
package io.floci.cli.config;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
/**
* Replaces a file all at once: the bytes go to a temporary file in the same directory, which is
* then moved over the target. A crash or Ctrl-C mid-write leaves the old file intact rather than a
* truncated one.
*/
final class AtomicFiles {
private AtomicFiles() {}
static void write(Path target, byte[] bytes) throws IOException {
Path dir = target.toAbsolutePath().getParent();
Files.createDirectories(dir);
Path temp = Files.createTempFile(dir, "." + target.getFileName(), ".tmp");
try {
Files.write(temp, bytes);
try {
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
}
} finally {
Files.deleteIfExists(temp); // only still there if the move failed
}
}
}
@@ -1,8 +1,10 @@
package io.floci.cli.config;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.floci.cli.output.Ansi;
import java.io.IOException;
import java.nio.file.Files;
@@ -31,21 +33,25 @@ public class GlobalConfigStore {
if ("oci".equals(config.defaultProduct)) return "oci";
return "aws";
} catch (IOException e) {
// Not silent: every bare command would otherwise switch to AWS without a word.
System.err.println(Ansi.yellow("Warning: ") + "Could not read " + configFile + ", so the default product is aws."
+ "\nFix the file, or run 'floci config default-product <aws|gcp|az|oci>' to rewrite it.");
return "aws";
}
}
public void setDefaultProduct(String product) throws IOException {
Files.createDirectories(configFile.getParent());
GlobalConfig config = new GlobalConfig();
config.defaultProduct = product;
YAML.writeValue(configFile.toFile(), config);
AtomicFiles.write(configFile, YAML.writeValueAsBytes(config));
}
public Path configFilePath() {
return configFile;
}
// Unknown keys are ignored, so a file written by a newer CLI still yields its default product.
@JsonIgnoreProperties(ignoreUnknown = true)
public static class GlobalConfig {
@JsonProperty("default-product")
public String defaultProduct = "aws";
@@ -2,6 +2,7 @@ package io.floci.cli.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.floci.cli.output.Ansi;
import java.io.IOException;
import java.nio.file.Files;
@@ -69,7 +70,12 @@ public class ProfileStore {
.forEach(p -> {
try {
profiles.add(read(p));
} catch (IOException ignored) {}
} catch (IOException e) {
// Skipped, but not silently: --profile on the same name would fail.
System.err.println(Ansi.yellow("Warning: ") + "Skipping profile file " + p
+ ", which is not valid YAML: " + firstLine(e.getMessage())
+ "\nFix the file, or delete it.");
}
});
}
return profiles;
@@ -81,6 +87,12 @@ public class ProfileStore {
return Optional.of(read(file));
}
private static String firstLine(String message) {
if (message == null) return "unreadable";
int newline = message.indexOf('\n');
return newline >= 0 ? message.substring(0, newline) : message;
}
// The one read path, so list and show agree on a profile's name.
private static Profile read(Path file) throws IOException {
Profile profile = YAML.readValue(file.toFile(), Profile.class);
@@ -106,8 +118,7 @@ public class ProfileStore {
}
public void save(Profile profile) throws IOException {
Files.createDirectories(profilesDir);
YAML.writeValue(profileFile(profile.name).toFile(), profile);
AtomicFiles.write(profileFile(profile.name), YAML.writeValueAsBytes(profile));
}
/**
@@ -0,0 +1,73 @@
package io.floci.cli.unit;
import io.floci.cli.config.GlobalConfigStore;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class GlobalConfigStoreTest {
@TempDir
Path tempDir;
private GlobalConfigStore store() {
return new GlobalConfigStore(tempDir.resolve("config.yaml"));
}
@Test
void defaultsToAwsWithoutAFile() {
assertEquals("aws", store().getDefaultProduct());
}
@Test
void remembersTheProductItWasGiven() throws Exception {
store().setDefaultProduct("gcp");
assertEquals("gcp", store().getDefaultProduct());
}
/** BL-042: the write goes through a temporary file, and none is left behind. */
@Test
void writesLeaveNoTemporaryFiles() throws Exception {
store().setDefaultProduct("oci");
store().setDefaultProduct("az");
try (var files = Files.list(tempDir)) {
assertEquals(List.of("config.yaml"), files.map(p -> p.getFileName().toString()).toList());
}
}
/** BL-043: a key this version does not know must not reset the default product. */
@Test
void anUnknownKeyKeepsTheProduct() throws Exception {
Files.writeString(tempDir.resolve("config.yaml"), "default-product: az\nsome-future-key: true\n");
assertEquals("az", store().getDefaultProduct());
}
/** BL-043: an unreadable file still falls back to aws, but says so. */
@Test
void anUnreadableFileWarnsAndFallsBackToAws() throws Exception {
Files.writeString(tempDir.resolve("config.yaml"), "default-product: [unterminated\n");
PrintStream err = System.err;
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setErr(new PrintStream(errBuf));
String product;
try {
product = store().getDefaultProduct();
} finally {
System.setErr(err);
}
assertEquals("aws", product);
assertTrue(errBuf.toString().contains("Could not read"), errBuf.toString());
assertTrue(errBuf.toString().contains("floci config default-product"), errBuf.toString());
}
}
@@ -10,6 +10,8 @@ import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
@@ -232,4 +234,35 @@ class ProfileStoreTest {
.sorted().toList();
assertEquals(fields, Profile.KNOWN_KEYS.stream().sorted().toList());
}
/** BL-042: saving goes through a temporary file, and none is left behind. */
@Test
void saveLeavesNoTemporaryFiles() throws Exception {
store().save(new Profile(ProductProfile.AWS, "one"));
store().save(new Profile(ProductProfile.AWS, "one"));
try (var files = Files.list(tempDir)) {
assertEquals(List.of("one.yaml"), files.map(p -> p.getFileName().toString()).toList());
}
}
/** BL-044: an unreadable profile is skipped by list, but reported. */
@Test
void listReportsAProfileItCannotRead() throws Exception {
Files.createDirectories(tempDir);
Files.writeString(tempDir.resolve("broken.yaml"), "port: [unterminated\n");
Files.writeString(tempDir.resolve("fine.yaml"), "port: 4599\n");
PrintStream err = System.err;
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setErr(new PrintStream(errBuf));
List<Profile> listed;
try {
listed = store().list();
} finally {
System.setErr(err);
}
assertEquals(List.of("fine"), listed.stream().map(p -> p.name).toList());
assertTrue(errBuf.toString().contains("broken.yaml"), errBuf.toString());
}
}