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

* 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.

* fix(config): warn when the config file cannot be opened and keep long profile names saving

A config.yaml in a directory the user cannot search is no longer taken for a missing file, the profile list warning quotes the real cause instead of calling every failure bad YAML, and the temporary file name no longer grows with the profile name. Adds tests for failed saves.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 15:54:34 -05:00
1 parent fbdc3ef713
commit 522e54ef3c
5 files changed
+320 -10

No files matched your search

@@ -0,0 +1,35 @@
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);
// A short fixed prefix: one built from the target's name would push a name already near
// the file system's length limit over it.
Path temp = Files.createTempFile(dir, ".floci-", ".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,11 +1,15 @@
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.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class GlobalConfigStore {
@@ -23,29 +27,46 @@ public class GlobalConfigStore {
}
public String getDefaultProduct() {
if (!Files.exists(configFile)) return "aws";
try {
GlobalConfig config = YAML.readValue(configFile.toFile(), GlobalConfig.class);
if ("az".equals(config.defaultProduct)) return "az";
if ("gcp".equals(config.defaultProduct)) return "gcp";
if ("oci".equals(config.defaultProduct)) return "oci";
// Read first and ask afterwards: Files.exists also answers false for a file it is not
// allowed to look at, which would skip the warning below.
GlobalConfig config = YAML.readValue(Files.readAllBytes(configFile), GlobalConfig.class);
String product = config == null ? null : config.defaultProduct;
if ("az".equals(product)) return "az";
if ("gcp".equals(product)) return "gcp";
if ("oci".equals(product)) return "oci";
return "aws";
} catch (NoSuchFileException e) {
return "aws"; // never configured
} 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 + " (" + reason(e)
+ "), so the default product is aws."
+ "\nCheck the file and its permissions, or run 'floci config default-product <aws|gcp|az|oci>' to rewrite it.");
return "aws";
}
}
private static String reason(IOException e) {
if (e instanceof AccessDeniedException) return "permission denied";
String message = e.getMessage();
if (message == null) return e.getClass().getSimpleName();
int newline = message.indexOf('\n');
return newline >= 0 ? message.substring(0, newline) : message;
}
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,14 @@ 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.
// The cause is quoted, not guessed: this is a parse error or a
// file that could not be opened.
System.err.println(Ansi.yellow("Warning: ") + "Could not read profile file " + p
+ ": " + firstLine(e.getMessage())
+ "\nCheck the file and its permissions, or delete it.");
}
});
}
return profiles;
@@ -81,6 +89,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 +120,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));
}
/**