Skip to content

Commit

Permalink
feat(core): add a method to help getting a file extension
Browse files Browse the repository at this point in the history
  • Loading branch information
loicmathieu committed Jul 25, 2023
1 parent 426814d commit dd68b56
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
23 changes: 23 additions & 0 deletions core/src/main/java/io/kestra/core/runners/RunContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import io.micronaut.inject.qualifiers.Qualifiers;
import lombok.NoArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.URI;
Expand Down Expand Up @@ -480,6 +482,17 @@ public URI putTempFile(File file, String name) throws IOException {
return this.putTempFile(file, this.storageOutputPrefix.toString(), name);
}

/**
* Put the temporary file on storage and delete it after.
* This method is meant to be used by polling triggers, the name of the destination file is derived from the
* executionId and the trigger passed as parameters.
*
* @param file the temporary file to upload to storage
* @param executionId overwrite file name
* @param trigger the trigger
* @return the {@code StorageObject} created
* @throws IOException If the temporary file can't be read
*/
public URI putTempFile(File file, String executionId, AbstractTrigger trigger) throws IOException {
return this.putTempFile(
file,
Expand Down Expand Up @@ -680,6 +693,16 @@ public Path tempFile(byte[] content, String suffix) throws IOException {
return tempFile;
}

/**
* Get the file extension including the '.' to be used with the various methods that took a suffix.
* @param fileName the name of the file
* @return the file extension including the '.' or null
*/
public String fileExtension(String fileName) {
String extension = FilenameUtils.getExtension(fileName);
return StringUtils.isEmpty(extension) ? null : "." + extension;
}

public void cleanup() {
try {
this.cleanTemporaryDirectory();
Expand Down
10 changes: 10 additions & 0 deletions core/src/test/java/io/kestra/core/runners/RunContextTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,14 @@ void metricsIncrement() {
assertThat(runContext.metrics().get(3).getValue(), is(Duration.ofSeconds(123)));
assertThat(runContext.metrics().get(3).getTags().size(), is(1));
}

@Test
void fileExtension() {
RunContext runContext = runContextFactory.of();

assertThat(runContext.fileExtension(null), nullValue());
assertThat(runContext.fileExtension(""), nullValue());
assertThat(runContext.fileExtension("/file/hello"), nullValue());
assertThat(runContext.fileExtension("/file/hello.txt"), is(".txt"));
}
}

0 comments on commit dd68b56

Please sign in to comment.