File:  [Local Repository] / solidite / utils / basename.c
Revision 1.1.1.1 (vendor branch): download - view: text, annotated - select for diffs
Tue Sep 8 00:37:30 2026 UTC (11 days, 2 hours ago) by user
Branches: none, MAIN
CVS tags: notag, HEAD
Migrate host

/* Copyright (c) 2026 The Solidite Developers
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>. */

#include <locale.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "include/text.h"

int main(int argc, char *argv[]) {
  setlocale(LC_ALL, "");

  if (argc == 1) {
    const char OUTPUT[] = ".\n";
    (void)write(STDOUT_FILENO, OUTPUT, sizeof(OUTPUT) - 1);
    return 0; // step 1
  }
  if (argv[1][0] == '\0')
    return 0;

  int non_slash_char_found = 0;
  for (size_t i = 0; i < strlen(argv[1]); ++i) {
    if (argv[1][i] != '/') {
      non_slash_char_found = 1;
      break;
    } else
      continue;
  }
  if (non_slash_char_found == 0) {
    const char OUTPUT[] = "/\n";
    (void)write(STDOUT_FILENO, OUTPUT, sizeof(OUTPUT) - 1);
    return 0;
  } // step 3

  size_t real_strlen = strlen(argv[1]);
  // count the actual strlen when null terms replaced
  while (argv[1][real_strlen - 1] == '/') {
    argv[1][real_strlen - 1] = '\0';
    --real_strlen;
  } // step 4

  char *final_slash = strrchr(argv[1], '/');
  if (final_slash != NULL)
    argv[1] = final_slash + 1;
  // step 5
  
  if (argc == 3 && ends_with(argv[1], argv[2]) == 0)
    argv[1][strlen(argv[1]) - strlen(argv[2])] = '\0'; 

  if (argv[1][0] == '\0')
    return 0;

  size_t output_length = strlen(argv[1]);
  argv[1][output_length] = '\n';
  // argv[1] isn't valid C string anymore, be careful
  (void)write(STDOUT_FILENO, argv[1], output_length + 1);
  return 0;
}

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>