Unverified Commit c3fe0e77 authored by Axel Kohlmeyer's avatar Axel Kohlmeyer
Browse files

expose guesspath function and add unit test

parent 84ee52a6
Loading
Loading
Loading
Loading
+6 −9
Original line number Diff line number Diff line
@@ -109,14 +109,11 @@ std::string utils::getsyserror()
  return std::string(strerror(errno));
}

/** \brief try to detect pathname from FILE pointer. Currently only supported on Linux, otherwise will report "(unknown)".
 *
 *  \param buf  storage buffer for pathname. output will be truncated if not large enough
 *  \param len  size of storage buffer. output will be truncated to this length - 1
 *  \param fp   FILE pointer structe from STDIO library for which we want to detect the name
 *  \return pointer to the storage buffer, i.e. buf
/*
 * On Linux the folder /proc/self/fd holds symbolic links to the actual
 * pathnames associated with each open file descriptor of the current process.
 */
static const char *guesspath(char *buf, int len, FILE *fp)
const char *utils::guesspath(char *buf, int len, FILE *fp)
{
  memset(buf,0,len);

@@ -124,9 +121,9 @@ static const char *guesspath(char *buf, int len, FILE *fp)
  int fd = fileno(fp);
  // get pathname from /proc or copy (unknown)
  if (readlink(fmt::format("/proc/self/fd/{}",fd).c_str(),buf,len-1) <= 0)
    strcpy(buf,"(unknown)");
    strncpy(buf,"(unknown)",len-1);
#else
  strcpy(buf,"(unknown)");
  strncpy(buf,"(unknown)",len-1);
#endif
  return buf;
}
+11 −0
Original line number Diff line number Diff line
@@ -210,6 +210,17 @@ namespace LAMMPS_NS {
     */
    bool is_double(const std::string & str);

    /** \brief try to detect pathname from FILE pointer.
     *
     * Currently only supported on Linux, otherwise will report "(unknown)".
     *
     *  \param buf  storage buffer for pathname. output will be truncated if not large enough
     *  \param len  size of storage buffer. output will be truncated to this length - 1
     *  \param fp   FILE pointer structe from STDIO library for which we want to detect the name
     *  \return pointer to the storage buffer, i.e. buf
     */
    const char *guesspath(char *buf, int len, FILE *fp);

    /**
     * \brief Strip off leading part of path, return just the filename
     * \param path file path
+15 −0
Original line number Diff line number Diff line
@@ -22,6 +22,7 @@

using namespace LAMMPS_NS;
using ::testing::Eq;
using ::testing::EndsWith;

TEST(Utils, trim_comment)
{
@@ -277,6 +278,20 @@ TEST(Utils, strmatch_opt_range)
    ASSERT_TRUE(utils::strmatch("rigid", "^[0-9]*[p-s]igid"));
}

TEST(Utils, guesspath)
{
    char buf[128];
    FILE *fp = fopen("test_guesspath.txt","w");
#if defined(__linux__)
    const char *path = utils::guesspath(buf,sizeof(buf),fp);
    ASSERT_THAT(path,EndsWith("test_guesspath.txt"));
#else
    const char *path = utils::guesspath(buf,sizeof(buf),fp);
    ASSERT_THAT(path,EndsWith("(unknown)"));
#endif
    fclose(fp);
}

TEST(Utils, path_join)
{
#if defined(_WIN32)