path_unix.odin 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //+build linux, darwin
  2. package path
  3. foreign import libc "system:c"
  4. import "core:os"
  5. import "core:strings"
  6. MAX :: 4096; // @note(bp): apparently PATH_MAX is bullshit
  7. SEPARATOR :: '/';
  8. SEPARATOR_STRING :: "/";
  9. @(private)
  10. null_term :: proc(str: string) -> string {
  11. for c, i in str {
  12. if c == '\x00' {
  13. return str[:i];
  14. }
  15. }
  16. return str;
  17. }
  18. full :: proc(path: string, allocator := context.temp_allocator) -> string {
  19. cpath := strings.clone_to_cstring(path, context.temp_allocator);
  20. foreign libc {
  21. realpath :: proc(path: cstring, resolved_path: ^u8) -> cstring ---;
  22. }
  23. buf := make([dynamic]u8, MAX, MAX, allocator);
  24. cstr := realpath(cpath, &buf[0]);
  25. for cstr == nil && os.get_last_error() == int(os.ENAMETOOLONG) {
  26. resize(&buf, len(buf) + MAX);
  27. cstr = realpath(cpath, &buf[0]);
  28. }
  29. return null_term(string(buf[:]));
  30. }
  31. current :: proc(allocator := context.temp_allocator) -> string {
  32. foreign libc{
  33. getcwd :: proc(buf: ^u8, size: int) -> cstring ---;
  34. }
  35. buf := make([dynamic]u8, MAX, MAX, allocator);
  36. cstr := getcwd(&buf[0], len(buf));
  37. for cstr == nil && os.get_last_error() == int(os.ENAMETOOLONG) {
  38. resize(&buf, len(buf) + MAX);
  39. cstr = getcwd(&buf[0], len(buf));
  40. }
  41. return null_term(string(buf[:]));
  42. }
  43. exists :: proc(path: string) -> bool {
  44. if _, ok := os.stat(path); ok {
  45. return true;
  46. }
  47. return false;
  48. }
  49. is_dir :: proc(path: string) -> bool {
  50. if stat, ok := os.stat(path); ok {
  51. return os.S_ISDIR(u32(stat.mode));
  52. }
  53. return false;
  54. }
  55. is_file :: proc(path: string) -> bool {
  56. if stat, ok := os.stat(path); ok {
  57. return os.S_ISREG(u32(stat.mode));
  58. }
  59. return false;
  60. }