All pastes #13874 Raw Edit

Miscellany

public text v1 · immutable
#13874 ·published 2005-06-10 06:05 UTC
rendered paste body
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

/*
Command format: ${command parameters}
Commands:
  getenv string         Prints the environment variable "string"
  echo string ...       Prints all arguments out separated by one space each

Any commands not recognized will be executed with the shell. (Not implemented yet)
*/

void process_command();
int read_token(char * buf, int maxlen);
void OH_CRAP(char * msg);
int uhp_readchar(char * c);

static int line = 1;
static int column = 1;

int main(int argc, char * argv[])
{
  int state = 0;
  char c;

  while (uhp_readchar(&c) == 1) {
    if (c == '$' && state == 0) {
      state = 1;
      continue;
    }
    if (state == 1 && c == '{') {
      process_command();
      state = 0;
      continue;
    }
    if (state == 1 && c != '{') {
      state = 0;
      fwrite("$", 1, 1, stdout);
    }
    fwrite(&c, 1, 1, stdout);
  }

	return 0;
}

#define MAX_CMD_SIZE 256
void process_command() {
  char buf[MAX_CMD_SIZE];
  int nomore = 0;

  read_token(buf, MAX_CMD_SIZE);
  //echo--------------------------
  if (!strcmp(buf, "echo")) {
    while (1) {
      nomore = read_token(buf, MAX_CMD_SIZE);
      printf("%s ", buf);
      if (nomore) break;
    }
    return;
  }
  //getenv--------------------------
  if (!strcmp(buf, "getenv")) {
    nomore = read_token(buf, MAX_CMD_SIZE);
    printf("%s", getenv(buf));
    while (!nomore) nomore = read_token(buf, MAX_CMD_SIZE);
    return;
  }
  OH_CRAP("Unrecognized command");
}

//Returns 1 if we hit a } to end the string
int read_token(char * buf, int maxlen) {
  char c;
  int pos = 0;
  //Skip whitespace
  do {
    if (uhp_readchar(&c) != 1) OH_CRAP("Error while reading token");
  } while (c == ' ' || c == '\t' || c == '\n' || c == '\r');
  if (c == '}') {
    buf[0] = 0; return 1;
  }
  //First character here
  while (1) {
    if (c != '}' && c != ' ' && c != '\t' && c != '\n' && c != '\r') {
      buf[pos] = c;
      pos++;
      if (pos == maxlen) OH_CRAP("Token too long");
    }
    else {
      break;
    }
    if (uhp_readchar(&c) != 1) OH_CRAP("Error while reading token");
  }
  buf[pos] = 0;
  if (c == '}') return 1;
  return 0;
}

int uhp_readchar(char * c) {
  int i = fread(c, 1, 1, stdin);
  if (*c == '\n') {
    line++; column = 0;
  }
  column++;
  return i;
}

void OH_CRAP(char * msg) {
  printf("uHP parsing error: %s at line %i, column %i\nErrno message: %m", msg, line, column, errno);
  exit(1);
}