binpac: Wrap native dirname() call in ifdef, call std::filesystem on Windows

This commit is contained in:
Tim Wojtulewicz 2022-10-18 13:30:06 -07:00
parent faa1b7abbf
commit d21f99ef2b

View file

@ -22,9 +22,15 @@
#include "pac_utils.h" #include "pac_utils.h"
#include <errno.h> #include <errno.h>
#include <filesystem>
#include <string_view> #include <string_view>
#ifdef MSVC
#include <filesystem>
#else
#include <libgen.h>
#include <memory>
#endif
int line_number = 1; int line_number = 1;
int begin_pac_primitive(int tok); int begin_pac_primitive(int tok);
@ -44,11 +50,24 @@ int char_token(int tok)
void include_file(const char *filename); void include_file(const char *filename);
string dirname(std::string_view path) std::string do_dirname(std::string_view s)
{ {
#ifdef MSVC
return std::filesystem::path(path).parent_path().string(); return std::filesystem::path(path).parent_path().string();
} #else
std::unique_ptr<char[]> tmp{new char[s.size()+1]};
strncpy(tmp.get(), s.data(), s.size());
tmp[s.size()] = '\0';
char* dn = dirname(tmp.get());
if ( !dn )
return "";
std::string res{dn};
return res;
#endif
}
%} %}
/* EC -- embedded code state */ /* EC -- embedded code state */
@ -339,9 +358,7 @@ void include_file(const char *filename)
full_filename = filename; full_filename = filename;
else if ( filename[0] == '.' ) else if ( filename[0] == '.' )
{ {
char* tmp = new char[strlen(input_filename.c_str()) + 1]; string dir = do_dirname(input_filename);
strcpy(tmp, input_filename.c_str());
string dir = dirname(tmp);
if ( ! dir.empty() ) if ( ! dir.empty() )
full_filename = dir + "/" + filename; full_filename = dir + "/" + filename;
@ -350,11 +367,8 @@ void include_file(const char *filename)
fprintf(stderr, "%s:%d error: cannot include file \"%s\": %s\n", fprintf(stderr, "%s:%d error: cannot include file \"%s\": %s\n",
input_filename.c_str(), line_number, filename, input_filename.c_str(), line_number, filename,
strerror(errno)); strerror(errno));
delete [] tmp;
return; return;
} }
delete [] tmp;
} }
else else
{ {