Compare commits

...

4 Commits

Author SHA1 Message Date
Ilya Gorbunov
ec5e96011c Use newly added shorter alternatives from kotlin.io.path API 2020-11-20 17:40:05 +03:00
Ilya Gorbunov
c2c45b7902 Introduce pathString/absolute/absolutePathString
Rename invariantSeparatorsPath to invariantSeparatorsPathString
to have more consistent names of methods returning path strings.
2020-11-20 17:40:05 +03:00
Ilya Gorbunov
762a7de8fa Allow passing null parent directory to createTempFile/Directory
null signifies the default temp directory.
2020-11-20 17:40:05 +03:00
Ilya Gorbunov
131174185c Relax writeText/appendText parameter type to CharSequence 2020-11-20 17:40:05 +03:00
13 changed files with 126 additions and 41 deletions

View File

@@ -27,9 +27,7 @@ import org.junit.Assert
import java.io.File
import java.io.FileWriter
import java.io.IOException
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.Path
import kotlin.io.path.createTempDirectory
import kotlin.io.path.*
import kotlin.test.assertTrue
data class ConfigurationKey(val kind: ConfigurationKind, val jdkKind: TestJdkKind, val configuration: String)
@@ -351,9 +349,9 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
@OptIn(ExperimentalPathApi::class)
@JvmStatic
fun main(args: Array<String>) {
val tmpFolder = createTempDirectory().toAbsolutePath().toString()
val tmpFolder = createTempDirectory().absolutePathString()
println("Created temporary folder for android tests: $tmpFolder")
val rootFolder = Path("").toAbsolutePath().toString()
val rootFolder = Path("").absolutePathString()
val pathManager = PathManager(rootFolder, tmpFolder)
generate(pathManager, true)
println("Android test project is generated into $tmpFolder folder")

View File

@@ -42,7 +42,7 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.invariantSeparatorsPath
import kotlin.io.path.invariantSeparatorsPathString
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.ScriptContents
import kotlin.script.experimental.dependencies.DependenciesResolver
@@ -1004,7 +1004,7 @@ internal val File.loggerCompatiblePath: String
@OptIn(ExperimentalPathApi::class)
internal val Path.loggerCompatiblePath: String
get() = invariantSeparatorsPath
get() = invariantSeparatorsPathString
open class TestKotlinScriptDummyDependenciesResolver : DependenciesResolver {

View File

@@ -254,7 +254,7 @@ class ConnectionsTest : KotlinIntegrationTestBase() {
private fun generateClient(): String {
val file = createTempFile(getTestName(true), ".alive")
clientFiles.add(file)
return file.toAbsolutePath().toString()
return file.absolutePathString()
}
private fun deleteClients() {

View File

@@ -53,7 +53,7 @@ abstract class AbstractJspecifyAnnotationsTest : AbstractDiagnosticsTest() {
appendLine("// FILE: main.kt\n$ktSourceCode")
}
super.doTest(createTempFile().apply { writeText(mergedSourceCode) }.toString())
super.doTest(createTempFile().apply { writeText(mergedSourceCode) }.pathString)
}
private fun makeJavaClassesPublicAndSeparatedByFiles(javaCode: String): String {

View File

@@ -35,7 +35,7 @@ object GeneratorsFileUtil {
val tempFile =
if (useTempFile) createTempDirectory(targetFile.name) / "${targetFile.name}.tmp" else targetFile
tempFile.writeText(newText, Charsets.UTF_8)
println("File written: ${tempFile.toAbsolutePath()}")
println("File written: ${tempFile.absolute()}")
if (useTempFile) {
tempFile.moveTo(targetFile, overwrite = true)
println("Renamed $tempFile to $targetFile")

View File

@@ -477,7 +477,7 @@ class GenerateIrRuntime {
@OptIn(ExperimentalPathApi::class)
private fun doSerializeModule(moduleFragment: IrModuleFragment, bindingContext: BindingContext, files: List<KtFile>, perFile: Boolean = false): String {
val tmpKlibDir = createTempDirectory().also { it.toFile().deleteOnExit() }.toString()
val tmpKlibDir = createTempDirectory().also { it.toFile().deleteOnExit() }.pathString
serializeModuleIntoKlib(
moduleName,
project,

View File

@@ -157,8 +157,8 @@ public fun Path.readText(charset: Charset = Charsets.UTF_8): String =
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
public fun Path.writeText(text: String, charset: Charset = Charsets.UTF_8, vararg options: OpenOption) {
Files.newOutputStream(this, *options).writer(charset).use { it.write(text) }
public fun Path.writeText(text: CharSequence, charset: Charset = Charsets.UTF_8, vararg options: OpenOption) {
Files.newOutputStream(this, *options).writer(charset).use { it.append(text) }
}
/**
@@ -169,8 +169,8 @@ public fun Path.writeText(text: String, charset: Charset = Charsets.UTF_8, varar
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
public fun Path.appendText(text: String, charset: Charset = Charsets.UTF_8) {
Files.newOutputStream(this, StandardOpenOption.APPEND).writer(charset).use { it.write(text) }
public fun Path.appendText(text: CharSequence, charset: Charset = Charsets.UTF_8) {
Files.newOutputStream(this, StandardOpenOption.APPEND).writer(charset).use { it.append(text) }
}
/**

View File

@@ -44,17 +44,66 @@ public val Path.extension: String
get() = fileName?.toString()?.substringAfterLast('.', "") ?: ""
/**
* Returns this path as a [String] using the invariant separator '/' to
* separate the names in the name sequence.
* Returns the string representation of this path.
*
* The returned path string uses the default name [separator][FileSystem.getSeparator]
* to separate names in the path.
*
* This property is a synonym to [Path.toString] function.
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
public val Path.invariantSeparatorsPath: String
@kotlin.internal.InlineOnly
public inline val Path.pathString: String
get() = toString()
/**
* Returns the string representation of this path using the invariant separator '/'
* to separate names in the path.
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
public val Path.invariantSeparatorsPathString: String
get() {
val separator = fileSystem.separator
return if (separator != "/") toString().replace(separator, "/") else toString()
}
// TODO: raise deprecation level and make inline-only
@SinceKotlin("1.4")
@ExperimentalPathApi
@Deprecated("Use invariantSeparatorsPathString property instead.", ReplaceWith("invariantSeparatorsPathString"))
public inline val Path.invariantSeparatorsPath: String
get() = invariantSeparatorsPathString
/**
* Converts this possibly relative path to an absolute path.
*
* If this path is already [absolute][Path.isAbsolute], returns this path unchanged.
* Otherwise, resolves this path, usually against the default directory of the file system.
*
* May throw an exception if the file system is inaccessible or getting the default directory path is prohibited.
*
* See [Path.toAbsolutePath] for further details about the function contract and possible exceptions.
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
@kotlin.internal.InlineOnly
public inline fun Path.absolute(): Path = toAbsolutePath()
/**
* Converts this possibly relative path to an absolute path and returns its string representation.
*
* Basically, this method is a combination of calling [absolute] and [pathString].
*
* May throw an exception if the file system is inaccessible or getting the default directory path is prohibited.
*
* See [Path.toAbsolutePath] for further details about the function contract and possible exceptions.
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
@kotlin.internal.InlineOnly
public inline fun Path.absolutePathString(): String = toAbsolutePath().toString()
/**
* Calculates the relative path for this path from a [base] path.
@@ -785,7 +834,7 @@ public inline fun Path.createFile(vararg attributes: FileAttribute<*>): Path =
* @param attributes an optional list of file attributes to set atomically when creating the file.
* @return the path to the newly created file that did not exist before.
*
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* when creating the file.
*
* @see Files.createTempFile
@@ -800,19 +849,23 @@ public inline fun createTempFile(prefix: String? = null, suffix: String? = null,
* Creates an empty file in the specified [directory], using
* the given [prefix] and [suffix] to generate its name.
*
* @param directory the parent directory in which to create a new file.
* It can be `null`, in that case the new file is created in the default temp directory.
* @param attributes an optional list of file attributes to set atomically when creating the file.
* @return the path to the newly created file that did not exist before.
*
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* when creating the file.
*
* @see Files.createTempFile
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
@kotlin.internal.InlineOnly
public inline fun createTempFile(directory: Path, prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path =
Files.createTempFile(directory, prefix, suffix, *attributes)
public fun createTempFile(directory: Path?, prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path =
if (directory != null)
Files.createTempFile(directory, prefix, suffix, *attributes)
else
Files.createTempFile(prefix, suffix, *attributes)
/**
* Creates a new directory in the default temp directory, using the given [prefix] to generate its name.
@@ -820,7 +873,7 @@ public inline fun createTempFile(directory: Path, prefix: String? = null, suffix
* @param attributes an optional list of file attributes to set atomically when creating the directory.
* @return the path to the newly created directory that did not exist before.
*
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* when creating the directory.
*
* @see Files.createTempDirectory
@@ -834,19 +887,23 @@ public inline fun createTempDirectory(prefix: String? = null, vararg attributes:
/**
* Creates a new directory in the specified [directory], using the given [prefix] to generate its name.
*
* @param directory the parent directory in which to create a new directory.
* It can be `null`, in that case the new directory is created in the default temp directory.
* @param attributes an optional list of file attributes to set atomically when creating the directory.
* @return the path to the newly created directory that did not exist before.
*
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* @throws UnsupportedOperationException if the array contains an attribute that cannot be set atomically
* when creating the directory.
*
* @see Files.createTempDirectory
*/
@SinceKotlin("1.4")
@ExperimentalPathApi
@kotlin.internal.InlineOnly
public inline fun createTempDirectory(directory: Path, prefix: String? = null, vararg attributes: FileAttribute<*>): Path =
Files.createTempDirectory(directory, prefix, *attributes)
public fun createTempDirectory(directory: Path?, prefix: String? = null, vararg attributes: FileAttribute<*>): Path =
if (directory != null)
Files.createTempDirectory(directory, prefix, *attributes)
else
Files.createTempDirectory(prefix, *attributes)
/**
* Resolves the given [other] path against this path.

View File

@@ -38,10 +38,10 @@ class PathExtensionsTest : AbstractPathTest() {
@Test
fun invariantSeparators() {
val path = Path("base") / "nested" / "leaf"
assertEquals("base/nested/leaf", path.invariantSeparatorsPath)
assertEquals("base/nested/leaf", path.invariantSeparatorsPathString)
val path2 = Path("base", "nested", "leaf")
assertEquals("base/nested/leaf", path2.invariantSeparatorsPath)
val path2 = Path("base", "nested", "terminal")
assertEquals("base/nested/terminal", path2.invariantSeparatorsPathString)
}
@Test
@@ -59,6 +59,24 @@ class PathExtensionsTest : AbstractPathTest() {
assertFailsWith<FileAlreadyExistsException> { file.createFile() }
}
@Test
fun createTempFileDefaultDir() {
val file1 = createTempFile().cleanup()
val file2 = createTempFile(directory = null).cleanup()
assertEquals(file1.parent, file2.parent)
}
@Test
fun createTempDirectoryDefaultDir() {
val dir1 = createTempDirectory().cleanup()
val dir2 = createTempDirectory(directory = null).cleanupRecursively()
val dir3 = createTempDirectory(dir2)
assertEquals(dir1.parent, dir2.parent)
assertNotEquals(dir2.parent, dir3.parent)
}
@Test
fun copyTo() {
val root = createTempDirectory("copyTo-root").cleanupRecursively()
@@ -131,7 +149,7 @@ class PathExtensionsTest : AbstractPathTest() {
@Test
fun copyToNameWithoutParent() {
val currentDir = Path("").toAbsolutePath()
val currentDir = Path("").absolute()
val srcFile = createTempFile().cleanup()
val dstFile = createTempFile(directory = currentDir).cleanup()
@@ -562,4 +580,11 @@ class PathExtensionsTest : AbstractPathTest() {
testRelativeTo("foo/bar", "../../foo/bar", "../../sub/../.")
testRelativeTo(null, "../../foo/bar", "../../sub/../..")
}
@Test
fun absolutePaths() {
val relative = Path("./example")
assertTrue(relative.absolute().isAbsolute)
assertEquals(relative.absolute().pathString, relative.absolutePathString())
}
}

View File

@@ -15,8 +15,8 @@ class PathReadWriteTest : AbstractPathTest() {
fun appendText() {
val file = createTempFile().cleanup()
file.writeText("Hello\n")
file.appendText("World\n")
file.writeText("Again", Charsets.US_ASCII, StandardOpenOption.APPEND)
file.appendText("World\n" as CharSequence)
file.writeText(StringBuilder("Again"), Charsets.US_ASCII, StandardOpenOption.APPEND)
assertEquals("Hello\nWorld\nAgain", file.readText())
assertEquals(listOf("Hello", "World", "Again"), file.readLines(Charsets.UTF_8))

View File

@@ -2,11 +2,16 @@ public abstract interface annotation class kotlin/io/path/ExperimentalPathApi :
}
public final class kotlin/io/path/PathsKt {
public static final fun appendText (Ljava/nio/file/Path;Ljava/lang/String;Ljava/nio/charset/Charset;)V
public static synthetic fun appendText$default (Ljava/nio/file/Path;Ljava/lang/String;Ljava/nio/charset/Charset;ILjava/lang/Object;)V
public static final fun appendText (Ljava/nio/file/Path;Ljava/lang/CharSequence;Ljava/nio/charset/Charset;)V
public static synthetic fun appendText$default (Ljava/nio/file/Path;Ljava/lang/CharSequence;Ljava/nio/charset/Charset;ILjava/lang/Object;)V
public static final fun createTempDirectory (Ljava/nio/file/Path;Ljava/lang/String;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/file/Path;
public static synthetic fun createTempDirectory$default (Ljava/nio/file/Path;Ljava/lang/String;[Ljava/nio/file/attribute/FileAttribute;ILjava/lang/Object;)Ljava/nio/file/Path;
public static final fun createTempFile (Ljava/nio/file/Path;Ljava/lang/String;Ljava/lang/String;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/file/Path;
public static synthetic fun createTempFile$default (Ljava/nio/file/Path;Ljava/lang/String;Ljava/lang/String;[Ljava/nio/file/attribute/FileAttribute;ILjava/lang/Object;)Ljava/nio/file/Path;
public static final fun fileAttributeViewNotAvailable (Ljava/nio/file/Path;Ljava/lang/Class;)Ljava/lang/Void;
public static final fun getExtension (Ljava/nio/file/Path;)Ljava/lang/String;
public static final fun getInvariantSeparatorsPath (Ljava/nio/file/Path;)Ljava/lang/String;
public static final fun getInvariantSeparatorsPathString (Ljava/nio/file/Path;)Ljava/lang/String;
public static final fun getName (Ljava/nio/file/Path;)Ljava/lang/String;
public static final fun getNameWithoutExtension (Ljava/nio/file/Path;)Ljava/lang/String;
public static final fun listDirectoryEntries (Ljava/nio/file/Path;Ljava/lang/String;)Ljava/util/List;
@@ -16,8 +21,8 @@ public final class kotlin/io/path/PathsKt {
public static final fun relativeTo (Ljava/nio/file/Path;Ljava/nio/file/Path;)Ljava/nio/file/Path;
public static final fun relativeToOrNull (Ljava/nio/file/Path;Ljava/nio/file/Path;)Ljava/nio/file/Path;
public static final fun relativeToOrSelf (Ljava/nio/file/Path;Ljava/nio/file/Path;)Ljava/nio/file/Path;
public static final fun writeText (Ljava/nio/file/Path;Ljava/lang/String;Ljava/nio/charset/Charset;[Ljava/nio/file/OpenOption;)V
public static synthetic fun writeText$default (Ljava/nio/file/Path;Ljava/lang/String;Ljava/nio/charset/Charset;[Ljava/nio/file/OpenOption;ILjava/lang/Object;)V
public static final fun writeText (Ljava/nio/file/Path;Ljava/lang/CharSequence;Ljava/nio/charset/Charset;[Ljava/nio/file/OpenOption;)V
public static synthetic fun writeText$default (Ljava/nio/file/Path;Ljava/lang/CharSequence;Ljava/nio/charset/Charset;[Ljava/nio/file/OpenOption;ILjava/lang/Object;)V
}
public final class kotlin/jdk7/AutoCloseableKt {

View File

@@ -81,10 +81,10 @@ class MainKtsIT {
// run generated jar with java
val javaExecutable = File(File(System.getProperty("java.home"), "bin"), "java")
val args = listOf(javaExecutable.absolutePath, "-jar", cacheFile!!.toString())
val args = listOf(javaExecutable.absolutePath, "-jar", cacheFile!!.pathString)
runAndCheckResults(
args, OUT_FROM_IMPORT_TEST,
additionalEnvVars = listOf(COMPILED_SCRIPTS_CACHE_DIR_ENV_VAR to cache.toAbsolutePath().toString())
additionalEnvVars = listOf(COMPILED_SCRIPTS_CACHE_DIR_ENV_VAR to cache.absolutePathString())
)
// this run should use the cached script

View File

@@ -327,7 +327,7 @@ class JvmIdeServicesTest : TestCase() {
private data class CliCompilationResult(val exitCode: ExitCode, val outputJarPath: String)
private fun compileFile(inputKtFileName: String, outputJarName: String): CliCompilationResult {
val jarPath = outputJarDir.resolve(outputJarName).toAbsolutePath().invariantSeparatorsPath
val jarPath = outputJarDir.resolve(outputJarName).absolute().invariantSeparatorsPathString
val compilerArgs = arrayOf(
"$MODULE_PATH/testData/$inputKtFileName",