| ... | ... | @@ -1182,3 +1182,60 @@ fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []cons |
| 1182 | 1182 | defer testing.allocator.free(result); |
| 1183 | 1183 | testing.expectEqualSlices(u8, expected_output, result); |
| 1184 | 1184 | } |
| 1185 | |
| 1186 | /// Returns the extension of the file name (if any). |
| 1187 | /// This function will search for the file extension (separated by a `.`) and will return the text after the `.`. |
| 1188 | /// Files that end with `.` are considered to have no extension. |
| 1189 | pub fn extension(path: []const u8) ?[]const u8 { |
| 1190 | const filename = basename(path); |
| 1191 | return if (std.mem.lastIndexOf(u8, filename, ".")) |index| |
| 1192 | if (index == filename.len - 1) |
| 1193 | null |
| 1194 | else |
| 1195 | filename[index + 1 ..] |
| 1196 | else |
| 1197 | null; |
| 1198 | } |
| 1199 | |
| 1200 | fn testExtension(path: []const u8, expected: ?[]const u8) void { |
| 1201 | const actual = extension(path); |
| 1202 | |
| 1203 | if (expected) |must_be| { |
| 1204 | std.testing.expect(actual != null); |
| 1205 | std.testing.expectEqualStrings(must_be, actual.?); |
| 1206 | } else { |
| 1207 | std.testing.expectEqual(expected, actual); |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | test "extension" { |
| 1212 | testExtension("", null); |
| 1213 | testExtension(".", null); |
| 1214 | testExtension("a.", null); |
| 1215 | testExtension("abc.", null); |
| 1216 | testExtension(".a", "a"); |
| 1217 | testExtension(".file", "file"); |
| 1218 | testExtension(".gitignore", "gitignore"); |
| 1219 | testExtension("file.gitignore", "gitignore"); |
| 1220 | testExtension("a.gitignore", "gitignore"); |
| 1221 | |
| 1222 | testExtension("/", null); |
| 1223 | testExtension("/.", null); |
| 1224 | testExtension("/a.", null); |
| 1225 | testExtension("/abc.", null); |
| 1226 | testExtension("/.a", "a"); |
| 1227 | testExtension("/.file", "file"); |
| 1228 | testExtension("/.gitignore", "gitignore"); |
| 1229 | testExtension("/file.gitignore", "gitignore"); |
| 1230 | testExtension("/a.gitignore", "gitignore"); |
| 1231 | |
| 1232 | testExtension("/foo/bar/bam/", null); |
| 1233 | testExtension("/foo/bar/bam/.", null); |
| 1234 | testExtension("/foo/bar/bam/a.", null); |
| 1235 | testExtension("/foo/bar/bam/abc.", null); |
| 1236 | testExtension("/foo/bar/bam/.a", "a"); |
| 1237 | testExtension("/foo/bar/bam/.file", "file"); |
| 1238 | testExtension("/foo/bar/bam/.gitignore", "gitignore"); |
| 1239 | testExtension("/foo/bar/bam/file.gitignore", "gitignore"); |
| 1240 | testExtension("/foo/bar/bam/a.gitignore", "gitignore"); |
| 1241 | } |