Skip to content

Commit

Permalink
[Configuration] Remove file header restoration on file modification
Browse files Browse the repository at this point in the history
  • Loading branch information
NEZNAMY committed Jan 18, 2025
1 parent d6cdace commit 152c04e
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ protected ConfigurationFile(@Nullable InputStream source, @NonNull File destinat
if (source == null) throw new IllegalStateException("File does not exist and source is null");
Files.copy(source, file.toPath());
}
detectHeader();
}

/**
Expand Down Expand Up @@ -373,40 +372,6 @@ private String getRealKey(@NonNull Map<?, ?> map, @NonNull String key) {
return key;
}

/**
* Detects header of a file (first lines of file starting with #).
*
* @throws IOException
* if I/O operation fails
*/
private void detectHeader() throws IOException {
header = new ArrayList<>();
for (String line : Files.readAllLines(file.toPath())) {
if (line.startsWith("#")) {
header.add(line);
} else {
break;
}
}
}

/**
* Inserts header back into file. This is required after calling {@link #save()}, because
* it destroys the header.
*
* @throws IOException
* if I/O operation fails
*/
public void fixHeader() throws IOException {
if (header == null) return;
List<String> content = new ArrayList<>(header);
content.addAll(Files.readAllLines(file.toPath()));
Files.delete(file.toPath());
if (file.createNewFile()) {
Files.write(file.toPath(), content);
}
}

/**
* Sets value to specified key if key does not exist.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,15 @@ public YamlConfigurationFile(@Nullable InputStream source, @NonNull File destina
}

@Override
public void save() {
public synchronized void save() {
try {
Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8);
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
new Yaml(options).dump(values, writer);
writer.close();
fixHeader();
} catch (IOException e) {
TAB.getInstance().getPlatform().logWarn(TabComponent.fromColoredText("Failed to save yaml file " + file.getPath() + " with content " + values.toString()));
TAB.getInstance().getPlatform().logWarn(TabComponent.fromColoredText("Failed to save yaml file " + file.getPath() + " with content " + values.toString() + ": " + e.getMessage()));
}
}
}

0 comments on commit 152c04e

Please sign in to comment.