formatter/format-command.spice
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // Copyright (c) 2021-2026 ChilliBits. All rights reserved. | ||
| 2 | |||
| 3 | // Std imports | ||
| 4 | import "std/data/vector"; | ||
| 5 | import "std/io/dir"; | ||
| 6 | import "std/io/file"; | ||
| 7 | import "std/io/filepath"; | ||
| 8 | import "std/os/cmd"; | ||
| 9 | import "std/os/filesystem"; | ||
| 10 | import "std/os/os"; | ||
| 11 | import "std/type/type-conversion"; | ||
| 12 | |||
| 13 | // Package imports | ||
| 14 | import "@/spice_packages/manifest/manifest-file"; | ||
| 15 | |||
| 16 | // Own imports | ||
| 17 | import "@/driver"; | ||
| 18 | import "@/exception/cli-error"; | ||
| 19 | import "@/exception/compiler-error"; | ||
| 20 | import "@/exception/fatal-error"; | ||
| 21 | import "@/formatter/format-config"; | ||
| 22 | import "@/formatter/formatter"; | ||
| 23 | import "@/global/global-resource-manager"; | ||
| 24 | import "@/util/common-util"; | ||
| 25 | import "@/util/manifest"; | ||
| 26 | import "@/util/test-util"; | ||
| 27 | |||
| 28 | // External functions | ||
| 29 | ext f<int> getchar(); | ||
| 30 | |||
| 31 | // Constants | ||
| 32 | const string STDIN_PATH = "-"; | ||
| 33 | const string STDIN_DISPLAY_NAME = "<stdin>"; | ||
| 34 | const string SOURCE_FILE_EXTENSION = ".spice"; | ||
| 35 | const string PACKAGES_DIR_NAME = "spice_packages"; | ||
| 36 | const int EOF_CHAR = -1; | ||
| 37 | // Suffix of the backup file, that holds the original code of a source file, while the formatted code is written to it | ||
| 38 | const string BACKUP_FILE_SUFFIX = ".format-backup"; | ||
| 39 | |||
| 40 | /** | ||
| 41 | * Run the 'format' subcommand: format the given source file, all source files in the given directory or the source code from | ||
| 42 | * stdin. Reformatted files are written back and their paths are printed. In check mode, the files are left as they are and | ||
| 43 | * the paths of the files, that are not formatted, are printed instead. Each file is formatted with the configuration of the | ||
| 44 | * manifest (spice.toml) of its project, i.e. the nearest one in its dir or a parent dir. The source code from stdin is | ||
| 45 | * formatted with the one of the working dir. | ||
| 46 | * | ||
| 47 | * @param cliOptions Command line options | ||
| 48 | * @param formatOptions Options of the format subcommand | ||
| 49 | * @return Exit code: 0 on success, 1 if a file is not formatted in check mode | ||
| 50 | */ | ||
| 51 | 18 | public f<int> runFormatCommand(CliOptions& cliOptions, const FormatOptions& formatOptions) { | |
| 52 | 18 | const String pathStr = String(formatOptions.path.toString()); | |
| 53 | |||
| 54 | // Source code from stdin. The formatted code goes to stdout, unless only checking | ||
| 55 | 18 | if pathStr == STDIN_PATH { | |
| 56 | ✗ | const String sourceCode = readStdin(); | |
| 57 | ✗ | const FilePath displayPath = FilePath(STDIN_DISPLAY_NAME); | |
| 58 | ✗ | const FilePath workingDir = FilePath(getCurrentWorkingDir()); | |
| 59 | ✗ | const FormatConfig config = readFormatConfig(findManifest(workingDir), workingDir); | |
| 60 | ✗ | const String formattedCode = formatWithOwnResourceManager(cliOptions, sourceCode, displayPath, config); | |
| 61 | ✗ | if formatOptions.check { | |
| 62 | ✗ | if formattedCode != sourceCode { | |
| 63 | ✗ | printf("%s\n", STDIN_DISPLAY_NAME); | |
| 64 | ✗ | return EXIT_CODE_ERROR; | |
| 65 | } | ||
| 66 | ✗ | return EXIT_CODE_SUCCESS; | |
| 67 | } | ||
| 68 | ✗ | printf("%s", formattedCode.getRaw()); | |
| 69 | ✗ | return EXIT_CODE_SUCCESS; | |
| 70 | ✗ | } | |
| 71 | |||
| 72 | // Collect the source files | ||
| 73 | 18 | Vector<FilePath> sourceFiles; | |
| 74 | 18 | if dirExists(formatOptions.path.toString()) { | |
| 75 | 2 | if formatOptions.toStdout { | |
| 76 | ✗ | const CliError cliError = CliError(CliErrorType::INCOMPATIBLE_OPTIONS, "--stdout only works with a single source file"); | |
| 77 | ✗ | abortWithError(cliError.getMessage()); | |
| 78 | ✗ | } | |
| 79 | 2 | String unreadablePath; | |
| 80 | 2 | if !collectSourceFiles(formatOptions.path, sourceFiles, unreadablePath) { | |
| 81 | ✗ | const String message = "Path '" + unreadablePath + "' cannot be read"; | |
| 82 | ✗ | const CompilerError error = CompilerError(CompilerErrorType::IO_ERROR, message.getRaw()); | |
| 83 | ✗ | abortWithError(error.getMessage()); | |
| 84 | ✗ | } | |
| 85 | 18 | } else if fileExists(formatOptions.path.toString()) { | |
| 86 | 16 | sourceFiles.pushBack(formatOptions.path); | |
| 87 | 16 | } else { | |
| 88 | ✗ | const String message = "File or directory '" + pathStr + "' does not exist"; | |
| 89 | ✗ | const CompilerError error = CompilerError(CompilerErrorType::SOURCE_FILE_NOT_FOUND, message.getRaw()); | |
| 90 | ✗ | abortWithError(error.getMessage()); | |
| 91 | 16 | } | |
| 92 | |||
| 93 | // Format them one after another. Check mode takes precedence over printing the formatted code | ||
| 94 | 18 | unsigned long unformattedCount = 0l; | |
| 95 | 18 | const FilePath workingDir = FilePath(getCurrentWorkingDir()); // The paths of the manifests are printed relative to it | |
| 96 | 18 | FilePath configManifestPath; // Manifest, that the current configuration comes from. Neighboring files mostly share it | |
| 97 | 18 | FormatConfig config; | |
| 98 | 32 | foreach const FilePath& sourceFile : sourceFiles { | |
| 99 | 14 | const FilePath manifestPath = findManifest(sourceFile); | |
| 100 | 14 | if manifestPath != configManifestPath { | |
| 101 | 2 | config = readFormatConfig(manifestPath, workingDir); | |
| 102 | 2 | configManifestPath = manifestPath; | |
| 103 | 2 | } | |
| 104 | 14 | const String sourceCode = readSourceFile(sourceFile); | |
| 105 | 14 | const String formattedCode = formatWithOwnResourceManager(cliOptions, sourceCode, sourceFile, config); | |
| 106 | 14 | const bool isFormatted = formattedCode == sourceCode; | |
| 107 | 14 | if !isFormatted { | |
| 108 | 5 | unformattedCount++; | |
| 109 | 5 | } | |
| 110 | 14 | if formatOptions.check { | |
| 111 | ✗ | if !isFormatted { | |
| 112 | ✗ | printf("%s\n", sourceFile.toString()); | |
| 113 | ✗ | } | |
| 114 | 14 | } else if formatOptions.toStdout { | |
| 115 | 14 | printf("%s", formattedCode.getRaw()); | |
| 116 | 14 | } else if !isFormatted { | |
| 117 | ✗ | writeSourceFile(sourceFile, sourceCode, formattedCode); | |
| 118 | ✗ | printf("%s\n", sourceFile.toString()); | |
| 119 | 14 | } | |
| 120 | 14 | } | |
| 121 | |||
| 122 | 14 | return formatOptions.check && unformattedCount > 0l ? EXIT_CODE_ERROR : EXIT_CODE_SUCCESS; | |
| 123 | 14 | } | |
| 124 | |||
| 125 | /** | ||
| 126 | * Format the given source code with a resource manager of its own. It owns the syntax tree, so this releases the syntax tree | ||
| 127 | * of each file, before the next one is formatted. | ||
| 128 | * | ||
| 129 | * @param cliOptions Command line options | ||
| 130 | * @param sourceCode Source code to format | ||
| 131 | * @param filePath Path of the source file, which errors refer to | ||
| 132 | * @param config Formatter configuration | ||
| 133 | * @return Formatted source code | ||
| 134 | */ | ||
| 135 | 15 | f<String> formatWithOwnResourceManager(CliOptions& cliOptions, const String& sourceCode, const FilePath& filePath, const FormatConfig& config) { | |
| 136 | 15 | GlobalResourceManager resourceManager = GlobalResourceManager(cliOptions); | |
| 137 | 30 | return formatSourceCode(resourceManager, sourceCode, filePath, config); | |
| 138 | 15 | } | |
| 139 | |||
| 140 | /** | ||
| 141 | * Collect all Spice source files in the given directory and its subdirectories, sorted by path. Hidden directories and the | ||
| 142 | * directories of installed packages are left out. The directory listing leaves out the contents of directories, that cannot | ||
| 143 | * be read or searched, so the collection fails for them instead of silently skipping their source files. | ||
| 144 | * | ||
| 145 | * @param dir Directory to search | ||
| 146 | * @param sourceFiles Vector to append the paths of the source files to | ||
| 147 | * @param unreadablePath Set to the path, that cannot be read, if the collection fails | ||
| 148 | * @return Whether all directories could be read | ||
| 149 | */ | ||
| 150 | 3 | f<bool> collectSourceFiles(const FilePath& dir, Vector<FilePath>& sourceFiles, String& unreadablePath) { | |
| 151 | 3 | Result<Vector<String>> entriesResult = listDirRecursive(dir.toString()); | |
| 152 | 3 | if !entriesResult.isOk() || !isAccessible(dir.toString()) { | |
| 153 | ✗ | unreadablePath = String(dir.toString()); | |
| 154 | ✗ | return false; | |
| 155 | ✗ | } | |
| 156 | 3 | const Vector<String> entries = entriesResult.unwrap(); | |
| 157 | |||
| 158 | // Keep the source files | ||
| 159 | 3 | Vector<String> relativePaths; | |
| 160 | 12 | foreach const String& entry : entries { | |
| 161 | // Skip the entries within the directories, that are left out | ||
| 162 | 11 | if isExcludedPath(entry) { | |
| 163 | ✗ | continue; | |
| 164 | } | ||
| 165 | |||
| 166 | // An entry, that is left out itself, e.g. a hidden directory, does not have to be accessible | ||
| 167 | 11 | const FilePath entryPath = dir / entry; | |
| 168 | 11 | const string entryPathStr = entryPath.toString(); | |
| 169 | 11 | const bool isLeftOut = isExcludedPath(entry + "/"); | |
| 170 | 11 | if !isLeftOut && fileExists(entryPathStr) && !isAccessible(entryPathStr) { | |
| 171 | 2 | unreadablePath = String(entryPathStr); | |
| 172 | 2 | return false; | |
| 173 | 2 | } | |
| 174 | |||
| 175 | 9 | if entry.endsWith(SOURCE_FILE_EXTENSION) && !dirExists(entryPathStr) { | |
| 176 | 3 | relativePaths.pushBack(entry); | |
| 177 | 3 | } | |
| 178 | 11 | } | |
| 179 | |||
| 180 | // Sort them, so that the order does not depend on the file system. This sorts the indices of the paths (insertion sort) | ||
| 181 | 1 | const unsigned long pathCount = relativePaths.getSize(); | |
| 182 | 1 | Vector<unsigned long> order; | |
| 183 | 3 | for unsigned long i = 0l; i < pathCount; i++ { | |
| 184 | 2 | order.pushBack(i); | |
| 185 | 2 | } | |
| 186 | 2 | for unsigned long i = 1l; i < pathCount; i++ { | |
| 187 | 1 | unsigned long j = i; | |
| 188 | 1 | while j > 0l && isStringLess(relativePaths.get(order.get(j)), relativePaths.get(order.get(j - 1l))) { | |
| 189 | ✗ | unsigned long& current = order.get(j); | |
| 190 | ✗ | unsigned long& previous = order.get(j - 1l); | |
| 191 | ✗ | const unsigned long tmp = current; | |
| 192 | ✗ | current = previous; | |
| 193 | ✗ | previous = tmp; | |
| 194 | ✗ | j--; | |
| 195 | ✗ | } | |
| 196 | 1 | } | |
| 197 | |||
| 198 | 3 | foreach unsigned long idx : order { | |
| 199 | 2 | sourceFiles.pushBack(dir / relativePaths.get(idx)); | |
| 200 | 2 | } | |
| 201 | 1 | return true; | |
| 202 | 3 | } | |
| 203 | |||
| 204 | /** | ||
| 205 | * Check if the given file or directory can be read. A directory has to be searchable as well (except on Windows, which has | ||
| 206 | * no search permission), so that the entries within it can be accessed. | ||
| 207 | * | ||
| 208 | * @param path Path of the file or directory | ||
| 209 | * @return Accessible or not | ||
| 210 | */ | ||
| 211 | 14 | f<bool> isAccessible(string path) { | |
| 212 | 14 | if !isFileReadable(path) { | |
| 213 | 1 | return false; | |
| 214 | } | ||
| 215 | 13 | return isWindows() || !dirExists(path) || isFileExecutable(path); | |
| 216 | } | ||
| 217 | |||
| 218 | /** | ||
| 219 | * Check if the given relative path lies within a hidden directory or a directory of installed packages | ||
| 220 | * | ||
| 221 | * @param relativePath Path relative to the searched directory, with '/' as separator | ||
| 222 | * @return Excluded or not | ||
| 223 | */ | ||
| 224 | 28 | f<bool> isExcludedPath(const String& relativePath) { | |
| 225 | 28 | const unsigned long length = relativePath.getLength(); | |
| 226 | 28 | unsigned long segmentStart = 0l; | |
| 227 | 434 | for unsigned long i = 0l; i <= length; i++ { | |
| 228 | 434 | if i < length && relativePath[i] != '/' { | |
| 229 | 375 | continue; | |
| 230 | } | ||
| 231 | // Only the directories count, not the file name | ||
| 232 | 59 | if i == length { | |
| 233 | 25 | break; | |
| 234 | } | ||
| 235 | 34 | const String segment = relativePath.getSubstring(segmentStart, cast<long>(i - segmentStart)); | |
| 236 | 34 | if segment.startsWith(".") || segment == PACKAGES_DIR_NAME { | |
| 237 | 3 | return true; | |
| 238 | } | ||
| 239 | 31 | segmentStart = i + 1l; | |
| 240 | 34 | } | |
| 241 | 25 | return false; | |
| 242 | } | ||
| 243 | |||
| 244 | /** | ||
| 245 | * Read the source code from stdin until its end | ||
| 246 | * | ||
| 247 | * @return Source code | ||
| 248 | */ | ||
| 249 | ✗ | f<String> readStdin() { | |
| 250 | ✗ | String sourceCode; | |
| 251 | ✗ | while true { | |
| 252 | ✗ | const int c = getchar(); | |
| 253 | ✗ | if c == EOF_CHAR { | |
| 254 | ✗ | break; | |
| 255 | } | ||
| 256 | ✗ | sourceCode += cast<char>(c); | |
| 257 | ✗ | } | |
| 258 | ✗ | return sourceCode; | |
| 259 | } | ||
| 260 | |||
| 261 | /** | ||
| 262 | * Read the given source file | ||
| 263 | * | ||
| 264 | * @param filePath Path of the source file | ||
| 265 | * @return Source code | ||
| 266 | */ | ||
| 267 | 15 | f<String> readSourceFile(const FilePath& filePath) { | |
| 268 | 15 | Result<String> readResult = readFile(filePath.toString()); | |
| 269 | 15 | if !readResult.isOk() { | |
| 270 | ✗ | const String message = "Source file at path '" + String(filePath.toString()) + "' cannot be opened"; | |
| 271 | ✗ | const CompilerError error = CompilerError(CompilerErrorType::IO_ERROR, message.getRaw()); | |
| 272 | ✗ | abortWithError(error.getMessage()); | |
| 273 | ✗ | } | |
| 274 | 30 | return readResult.unwrap(); | |
| 275 | 15 | } | |
| 276 | |||
| 277 | /** | ||
| 278 | * Write the formatted code to the given source file. The source file is overwritten in place, so that it keeps its permissions, | ||
| 279 | * its owner and its links. The original code is backed up next to the source file first, so that it is not lost, if writing | ||
| 280 | * fails, e.g. on a full disk. The backup is removed afterwards. Its name contains the process id, so that concurrent runs do | ||
| 281 | * not share it. See writeBackupFile() for how the backup is protected. | ||
| 282 | * | ||
| 283 | * @param filePath Path of the source file | ||
| 284 | * @param originalCode Original code of the source file | ||
| 285 | * @param formattedCode Formatted code | ||
| 286 | */ | ||
| 287 | ✗ | p writeSourceFile(const FilePath& filePath, const String& originalCode, const String& formattedCode) { | |
| 288 | ✗ | const String path = String(filePath.toString()); | |
| 289 | ✗ | const String backupPath = path + "." + toString(getPID()) + BACKUP_FILE_SUFFIX; | |
| 290 | ✗ | if !writeBackupFile(backupPath, originalCode) { | |
| 291 | ✗ | String message = "Source file at path '" + path + "' cannot be backed up at '" + backupPath + "'. It was left unchanged"; | |
| 292 | ✗ | if fileExists(backupPath.getRaw()) { | |
| 293 | ✗ | message += ". The backup path exists already, e.g. from an earlier run, that failed"; | |
| 294 | ✗ | } | |
| 295 | ✗ | const CompilerError error = CompilerError(CompilerErrorType::IO_ERROR, message.getRaw()); | |
| 296 | ✗ | abortWithError(error.getMessage()); | |
| 297 | ✗ | } | |
| 298 | ✗ | if !writeTextFile(path, formattedCode) { | |
| 299 | ✗ | const String message = "Source file at path '" + path + "' cannot be written. Its original code is in '" + backupPath + "'"; | |
| 300 | ✗ | const CompilerError error = CompilerError(CompilerErrorType::IO_ERROR, message.getRaw()); | |
| 301 | ✗ | abortWithError(error.getMessage()); | |
| 302 | ✗ | } | |
| 303 | ✗ | const bool _ = deleteFile(backupPath.getRaw()); | |
| 304 | ✗ | } | |
| 305 | |||
| 306 | /** | ||
| 307 | * Write the given text to the given file, replacing its content | ||
| 308 | * | ||
| 309 | * @param path Path of the file | ||
| 310 | * @param text Text to write | ||
| 311 | * @return Whether the text was written completely | ||
| 312 | */ | ||
| 313 | ✗ | f<bool> writeTextFile(const String& path, const String& text) { | |
| 314 | ✗ | Result<File> openResult = openFile(path, MODE_WRITE); | |
| 315 | ✗ | if !openResult.isOk() { | |
| 316 | ✗ | return false; | |
| 317 | } | ||
| 318 | ✗ | File file = openResult.unwrap(); | |
| 319 | ✗ | return writeAndCloseFile(file, text); | |
| 320 | } | ||
| 321 | |||
| 322 | /** | ||
| 323 | * Write the original code of a source file to a new backup file. The backup is created exclusively, so that it neither replaces | ||
| 324 | * an existing file, e.g. the backup of an earlier run, that failed, nor writes through a symbolic link at its predictable path. | ||
| 325 | * Only its owner can read it, because the source file might not be readable for others. | ||
| 326 | * | ||
| 327 | * @param backupPath Path of the backup file | ||
| 328 | * @param originalCode Original code of the source file | ||
| 329 | * @return Whether the backup was written completely | ||
| 330 | */ | ||
| 331 | 3 | f<bool> writeBackupFile(const String& backupPath, const String& originalCode) { | |
| 332 | 3 | Result<File> openResult = openNewFile(backupPath, S_IRUSR | S_IWUSR); | |
| 333 | 3 | if !openResult.isOk() { | |
| 334 | 2 | return false; // Whatever exists at the path, does not belong to this run, so it is left as it is | |
| 335 | } | ||
| 336 | 1 | File file = openResult.unwrap(); | |
| 337 | 1 | if !writeAndCloseFile(file, originalCode) { | |
| 338 | ✗ | const bool _ = deleteFile(backupPath.getRaw()); // Best effort. This run created the file, so it may remove it | |
| 339 | ✗ | return false; | |
| 340 | } | ||
| 341 | 1 | return true; | |
| 342 | } | ||
| 343 | |||
| 344 | /** | ||
| 345 | * Write the given text to the given open file and close it | ||
| 346 | * | ||
| 347 | * @param file Open file | ||
| 348 | * @param text Text to write | ||
| 349 | * @return Whether the text was written completely | ||
| 350 | */ | ||
| 351 | 1 | f<bool> writeAndCloseFile(File& file, const String& text) { | |
| 352 | 1 | const bool isWritten = file.write(text); | |
| 353 | // Closing flushes the buffered text, which can fail as well, e.g. on a full disk | ||
| 354 | 1 | const bool isClosed = file.close(); | |
| 355 | 1 | return isWritten && isClosed; | |
| 356 | } | ||
| 357 | |||
| 358 | // ============================================================== Tests ============================================================== | ||
| 359 | |||
| 360 | 1 | #[test] | |
| 361 | f<bool> testFormatCommandFailsOnInaccessibleDirs() { | ||
| 362 | // Windows has no POSIX permissions | ||
| 363 | 1 | if isWindows() { | |
| 364 | ✗ | return true; | |
| 365 | } | ||
| 366 | |||
| 367 | // One directory, that cannot be read, and one, that can be read, but not searched | ||
| 368 | 1 | const FilePath testDir = makeUniqueTestDir("spice-format-test"); | |
| 369 | 1 | const FilePath unreadableDir = testDir / "unreadable"; | |
| 370 | 1 | const FilePath unsearchableDir = testDir / "unsearchable"; | |
| 371 | 1 | createTestDirs(unreadableDir / "sub"); | |
| 372 | 1 | createTestDirs(unsearchableDir / "sub"); | |
| 373 | 1 | writeTestFile(unreadableDir / "sub" / "a.spice", "f<int> main() {}\n"); | |
| 374 | 1 | writeTestFile(unsearchableDir / "sub" / "b.spice", "f<int> main() {}\n"); | |
| 375 | |||
| 376 | // Collect from each directory with only the other one locked | ||
| 377 | 1 | const bool lockedUnreadable = changeFilePermissions(unreadableDir.toString(), 0o000s); | |
| 378 | 1 | Vector<FilePath> filesWithUnreadable; | |
| 379 | 1 | String unreadablePath; | |
| 380 | 1 | const bool unreadableCollected = collectSourceFiles(testDir, filesWithUnreadable, unreadablePath); | |
| 381 | 1 | const bool unlockedUnreadable = changeFilePermissions(unreadableDir.toString(), 0o755s); | |
| 382 | |||
| 383 | 1 | const bool lockedUnsearchable = changeFilePermissions(unsearchableDir.toString(), 0o444s); | |
| 384 | // The superuser bypasses the permissions, so the locks only take effect for other users | ||
| 385 | 1 | const bool permissionsEnforced = !isFileExecutable(unsearchableDir.toString()); | |
| 386 | 1 | Vector<FilePath> filesWithUnsearchable; | |
| 387 | 1 | String unsearchablePath; | |
| 388 | 1 | const bool unsearchableCollected = collectSourceFiles(testDir, filesWithUnsearchable, unsearchablePath); | |
| 389 | 1 | const bool unlockedUnsearchable = changeFilePermissions(unsearchableDir.toString(), 0o755s); | |
| 390 | |||
| 391 | // Without locks, both source files are found | ||
| 392 | 1 | Vector<FilePath> allFiles; | |
| 393 | 1 | String noUnreadablePath; | |
| 394 | 1 | const bool allCollected = collectSourceFiles(testDir, allFiles, noUnreadablePath); | |
| 395 | |||
| 396 | // Clean up before asserting, so that a failure does not leave the files behind | ||
| 397 | 1 | removeTestDir(testDir); | |
| 398 | 1 | assert lockedUnreadable && unlockedUnreadable && lockedUnsearchable && unlockedUnsearchable; | |
| 399 | 1 | assert allCollected && allFiles.getSize() == 2l; | |
| 400 | 1 | if permissionsEnforced { | |
| 401 | 1 | assert !unreadableCollected && unreadablePath.endsWith("unreadable"); | |
| 402 | 1 | assert !unsearchableCollected && unsearchablePath.endsWith("unsearchable"); | |
| 403 | 1 | } | |
| 404 | 1 | return true; | |
| 405 | 1 | } | |
| 406 | |||
| 407 | 1 | #[test] | |
| 408 | f<bool> testFormatCommandWritesBackupForOwnerOnly() { | ||
| 409 | // Windows has no POSIX permissions and creating symlinks needs special privileges there | ||
| 410 | 1 | if isWindows() { | |
| 411 | ✗ | return true; | |
| 412 | } | ||
| 413 | 1 | const FilePath testDir = makeUniqueTestDir("spice-format-test"); | |
| 414 | 1 | const String backupPath = String((testDir / "a.spice.1.format-backup").toString()); | |
| 415 | 1 | const FilePath linkTarget = testDir / "target.spice"; | |
| 416 | 1 | const FilePath linkPath = testDir / "b.spice.1.format-backup"; | |
| 417 | |||
| 418 | // The backup holds the original code and only its owner can read and write it | ||
| 419 | 1 | const bool backupWritten = writeBackupFile(backupPath, String("f<int> main() {}\n")); | |
| 420 | 1 | const String backupContent = readTestFile(FilePath(backupPath)); | |
| 421 | 1 | const String backupPermissions = getTestFilePermissions(FilePath(backupPath)); | |
| 422 | |||
| 423 | // An existing file at the backup path is neither overwritten nor removed | ||
| 424 | 1 | const bool existingOverwritten = writeBackupFile(backupPath, String("other code")); | |
| 425 | 1 | const String keptContent = readTestFile(FilePath(backupPath)); | |
| 426 | |||
| 427 | // A symlink at the backup path is not written through, even if its target does not exist | ||
| 428 | 1 | const bool linkCreated = createTestSymlink(linkTarget, linkPath); | |
| 429 | 1 | const bool linkWrittenThrough = writeBackupFile(String(linkPath.toString()), String("f<int> main() {}\n")); | |
| 430 | 1 | const bool linkTargetCreated = fileExists(linkTarget.toString()); | |
| 431 | |||
| 432 | // Clean up before asserting, so that a failure does not leave the files behind | ||
| 433 | 1 | removeTestDir(testDir); | |
| 434 | 1 | assert backupWritten && backupContent == "f<int> main() {}\n"; | |
| 435 | 1 | assert backupPermissions == "-rw-------"; | |
| 436 | 1 | assert !existingOverwritten && keptContent == "f<int> main() {}\n"; | |
| 437 | 1 | assert linkCreated && !linkWrittenThrough && !linkTargetCreated; | |
| 438 | 1 | return true; | |
| 439 | 1 | } | |
| 440 | |||
| 441 | 1 | #[test] | |
| 442 | f<bool> testFormatCommandExcludedPaths() { | ||
| 443 | 1 | assert isExcludedPath(String(".git/")); // A directory itself | |
| 444 | 1 | assert !isExcludedPath(String("main.spice")); | |
| 445 | 1 | assert !isExcludedPath(String("src/main.spice")); | |
| 446 | 1 | assert !isExcludedPath(String(".hidden.spice")); // Only directories are excluded | |
| 447 | 1 | assert isExcludedPath(String(".git/main.spice")); | |
| 448 | 1 | assert isExcludedPath(String("src/spice_packages/llvm/llvm.spice")); | |
| 449 | 1 | return true; | |
| 450 | 1 | } | |
| 451 |