Plan 9 from Bell Labs’s /usr/web/sources/contrib/de0u/root/sys/src/cmd/divergefs/filepath.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <String.h>
#include "common.h"
#include "string.h"
#include "filepath.h"

void filepath_copy(String **self, String *from)
{
  assert_valid(self);
  assert_valid(from);
  *self = s_reset(*self);
  *self = s_append(*self, s_to_c(from));
}

void filepath_append(String **self, char *name)
{
  assert_valid(self);
  assert_valid(*self);
  *self = s_append(*self, "/");
  *self = s_append(*self, name);
}

char *filepath_append_cstr(char *path, char *name)
{
  String *whole;
  char *result;
  assert_valid(path);
  assert_valid(name);

  whole = s_copy(path);
  filepath_append(&whole, name);
  result = estrdup_fs(s_to_c(whole));
  s_free(whole);
  return result;
}

void filepath_remove_last(String *self)
{
  char *lastslash;
  assert_valid(self);

  lastslash = strrchr(s_to_c(self), '/');
  if(lastslash == nil)
  {
    s_reset(self);
    return;
  }
  *lastslash = '\0';
  self->ptr = lastslash;
}

void filepath_replace_last(String **self, char *newname)
{
  bool hasslash;
  assert_valid(self);
  assert_valid(*self);
  assert_valid(newname);

  hasslash = (strchr(s_to_c(*self), '/') != nil);
  filepath_remove_last(*self);
  if(hasslash)
  {
    filepath_append(self, newname);
  }
  else
  {
    *self = s_append(*self, newname);
  }
}

bool filepath_isabsolute(String *self)
{
  assert_valid(self);
  if(s_len(self) < 1)
  {
    return false;
  }
  return s_to_c(self)[0] == '/';
}

bool filepath_isrelative(String *self)
{
  assert_valid(self);
  return !filepath_isabsolute(self);
}

void filepath_make_absolute(String **self)
{
  char currentdir[FILEPATH_BUFFER_MAX];
  String *relative;
  assert_valid(self);
  assert_valid(*self);

  if(filepath_isabsolute(*self))
  {
    return;
  }

  getwd(currentdir, FILEPATH_BUFFER_MAX);
  relative = *self;
  *self = s_copy(currentdir);
  filepath_append(self, s_to_c(relative));
  s_free(relative);
}

char* filepath_make_absolute_cstr(char *path)
{
  String *s;
  char *result;
  assert_valid(path);

  s =  s_copy(path);
  filepath_make_absolute(&s);
  result = estrdup_fs(s_to_c(s));
  s_free(s);
  return result;
}



Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.