Subversion Repositories HelenOS

Rev

Rev 3277 | Rev 3294 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

/* Automatically generated by mknewcmd on Mon Aug 11 00:22:09 PHT 2008
 * This is machine generated output. The author of mknewcmd claims no
 * copyright over the contents of this file. Where legally permitted, the
 * contents herein are donated to the public domain.
 *
 * You should apply any license and copyright that you wish to this file,
 * replacing this header in its entirety. */

/* Extremely primitive 'ls' implementation. Does not sort or stat files,
 * just here for convenience */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

#include "errors.h"
#include "config.h"
#include "util.h"
#include "entry.h"
#include "ls.h"
#include "cmds.h"

static char *cmdname = "ls";

unsigned int ls_scope(const char *path)
{
    int fd;
    DIR *dirp;

    dirp = opendir(path);
    if (dirp) {
        closedir(dirp);
        return LS_DIR;
    }

    fd = open(path, O_RDONLY);
    if (fd > 0) {
        close(fd);
        return LS_FILE;
    }

    return LS_BOGUS;
}

void ls_print(const char *f)
{
    if (ls_scope(f) == LS_FILE)
        printf("%-40s\n", f);
    else
        printf("%-40s <DIR>\n", f);
    return;
}

/* Dispays help for ls in various levels */
void * help_cmd_ls(unsigned int level)
{
    printf("This is the %s help for '%s'.\n",
        level ? EXT_HELP : SHORT_HELP, cmdname);
    return CMD_VOID;
}

int * cmd_ls(char **argv)
{
    unsigned int argc;
    unsigned int scope;
    char *buff;

    DIR *dirp;
    struct dirent *dp;

    /* Count the arguments */
    for (argc = 0; argv[argc] != NULL; argc ++);

    if (argc > 2) {
        printf("%s - Too many arguments. Try `help %s extended'\n",
            cmdname, cmdname);
        return CMD_FAILURE;
    }

    buff = (char *) malloc(PATH_MAX);
    if (NULL == buff) {
        cli_error(CL_ENOMEM, "%s: ", cmdname);
        return CMD_FAILURE;
    }
    memset(buff, 0, sizeof(buff));

    if (argc == 1)
        getcwd(buff, PATH_MAX);
    else
        strncpy(buff, argv[1], PATH_MAX);

    scope = ls_scope(buff);

    switch (scope) {
    case LS_BOGUS:
        cli_error(CL_ENOENT, buff);
        free(buff);
        return CMD_FAILURE;
    case LS_FILE:
        ls_print(buff);
        break;
    case LS_DIR:
        dirp = opendir(buff);
        while ((dp = readdir(dirp)))
            ls_print(dp->d_name);
        closedir(dirp);
        break;
    }

    free(buff);

    return CMD_SUCCESS;
    
}