Commit cf0d4326

cf0d43265ab5Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · +1 added · ~3 modified

Description

runtime,codegen,analyze: File.dirname / .extname / Dir.pwd

File.dirname strips the trailing path component (returns "." when there's no separator, "/" at the root). File.extname returns the dot-prefixed final extension; leading-dot files return "" but trailing-dot paths keep the dot (CRuby >= 2.7). Dir.pwd (and alias getwd) return the current working directory via getcwd.

Fixes #892

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
cf0d43265ab5
Parent
22c0a2700010

lib/sp_runtime.hmodifiedView file

@@ -2975,6 +2975,36 @@
29752975 memcpy(buf, base, n + 1);
29762976 return buf;
29772977 }
2978+/* Issue #892: File.dirname / File.extname / Dir.pwd. */
2979+static const char *sp_file_dirname(const char *path) {
2980+ const char *s = strrchr(path, '/');
2981+ if (!s) { char *r = sp_str_alloc(1); r[0] = '.'; r[1] = 0; return r; }
2982+ if (s == path) { char *r = sp_str_alloc(1); r[0] = '/'; r[1] = 0; return r; }
2983+ size_t n = (size_t)(s - path);
2984+ char *buf = sp_str_alloc(n);
2985+ memcpy(buf, path, n); buf[n] = 0;
2986+ return buf;
2987+}
2988+static const char *sp_file_extname(const char *path) {
2989+ const char *base = strrchr(path, '/');
2990+ base = base ? base + 1 : path;
2991+ const char *dot = strrchr(base, '.');
2992+ /* CRuby: leading-dot files (".bashrc") return "". Trailing-dot
2993+ paths ("foo.") keep the dot since Ruby 2.7. */
2994+ if (!dot || dot == base) return sp_str_empty;
2995+ size_t n = strlen(dot);
2996+ char *buf = sp_str_alloc(n);
2997+ memcpy(buf, dot, n + 1);
2998+ return buf;
2999+}
3000+static const char *sp_dir_pwd(void) {
3001+ char tmp[4096];
3002+ if (!getcwd(tmp, sizeof(tmp))) { return sp_str_empty; }
3003+ size_t n = strlen(tmp);
3004+ char *buf = sp_str_alloc(n);
3005+ memcpy(buf, tmp, n + 1);
3006+ return buf;
3007+}
29783008
29793009 /* Read a file's bytes into a fresh IntArray. Distinct from
29803010 `sp_str_bytes(sp_file_read(path))` because plain sp_str_bytes uses