Exemplo n.º 1
0
Arquivo: main.c Projeto: gaibo/C
int main(int argc, char *argv[])
{
  int quit = 0;
  bst *address_book = NULL;
  char *curr_file = (char *)malloc(0);
  fprintf(stdout,"Welcome to adrbook!\n\n");
  fflush(stdout);
  if (argc == 2) {
    free(curr_file);
    curr_file = strdup(argv[1]);
    address_book = addr_book_from_file(curr_file);
    printf("Read file %s.\n", curr_file);
    putchar('\n');
    fflush(stdout);
  }
  char buf[BUF_SZ];
  /* interactive i/o loop */
  help_text();
  short_prompt();
  while (1) {
    char *cmd;
    cmd = fgets(buf, BUF_SZ, stdin);
    cmd = trim_newline(cmd);
    /* printf("cmd=%s\n", cmd); */
    putchar('\n');
    if (!process_cmd(&curr_file, cmd, &address_book, &quit))
      fprintf(stdout, "unknown command: \"%s\"\n", cmd);
    free(cmd);
    if (quit)
      break;
    short_prompt();
  }
  return 0;
}
Exemplo n.º 2
0
/// Extracts the result reason from the input file.
///
/// \pre This can only be called for those result types that require a reason.
///
/// \param [in,out] input The file from which to read.
/// \param first_line The first line of the reason.  Because this is part of the
///     same line in which the result status is printed, this line has already
///     been read by the caller and thus must be provided here.
/// \param [out] output Buffer to which to write the full reason.
/// \param output_size Size of the output buffer.
///
/// \return An error if there was no reason in the input or if there is a
/// problem reading it.
static kyua_error_t
read_reason(FILE* input, const char* first_line, char* output,
            size_t output_size)
{
    if (first_line == NULL || *first_line == '\0')
        return kyua_generic_error_new("Test case should have reported a "
                                      "failure reason but didn't");

    snprintf(output, output_size, "%s", first_line);
    advance(&output, &output_size);

    bool had_newline = true;
    while (!is_really_eof(input)) {
        if (had_newline) {
            snprintf(output, output_size, "<<NEWLINE>>");
            advance(&output, &output_size);
        }

        if (fgets(output, output_size, input) == NULL) {
            assert(ferror(input));
            return kyua_libc_error_new(errno, "Failed to read reason from "
                                       "result file");
        }
        had_newline = trim_newline(output);
        advance(&output, &output_size);
    }

    return kyua_error_ok();
}
Exemplo n.º 3
0
void handle_user_input(connection_info *connection)
{
  char input[255];
  fgets(input, 255, stdin);
  trim_newline(input);

  // message msg;
  SBCP_message msg = initSBCP( SEND );
  // msg.type = PUBLIC_MESSAGE;
  pushAttr(&msg, Username, connection->username);

  // strncpy(msg.username, connection->username, 20);

  //clear_stdin_buffer();

  if(strlen(input) == 0) {
      return;
  }
  


  // strncpy(msg.data, input, 255);
  pushAttr(&msg, Message, input );

  //Send some data
  if(send(connection->socket, &msg, sizeof(msg), 0) < 0)
  {
      perror("Send failed");
      exit(1);
  }
}
Exemplo n.º 4
0
/*
 *  read_string()
 *
 *  Ask the user a question and prompt for a string answer
 *  max = size of "answer" including NULL terminating character
 *  Note:  The answer parameter is MODIFIED by the function
 */
void read_string(char prompt[], char answer[], int max)
{
	fputs(prompt, stdout);
	fflush(stdin);
	fgets(answer, max, stdin);

    trim_newline(answer);
}
Exemplo n.º 5
0
/// Parses a results file written by an ATF test case.
///
/// \param input_name Path to the result file to parse.
/// \param [out] status Type of result.
/// \param [out] status_arg Optional integral argument to the status.
/// \param [out] reason Textual explanation of the result, if any.
/// \param reason_size Length of the reason output buffer.
///
/// \return An error if the input_name file has an invalid syntax; OK otherwise.
static kyua_error_t
read_atf_result(const char* input_name, enum atf_status* status,
                int* status_arg, char* const reason, const size_t reason_size)
{
    kyua_error_t error = kyua_error_ok();

    FILE* input = fopen(input_name, "r");
    if (input == NULL) {
        error = kyua_generic_error_new("Premature exit");
        goto out;
    }

    char line[1024];
    if (fgets(line, sizeof(line), input) == NULL) {
        if (ferror(input)) {
            error = kyua_libc_error_new(errno, "Failed to read result from "
                                        "file %s", input_name);
            goto out_input;
        } else {
            assert(feof(input));
            error = kyua_generic_error_new("Empty result file %s", input_name);
            goto out_input;
        }
    }

    if (!trim_newline(line)) {
        error = kyua_generic_error_new("Missing newline in result file");
        goto out_input;
    }

    char* reason_start = strstr(line, ": ");
    if (reason_start != NULL) {
        *reason_start = '\0';
        *(reason_start + 1) = '\0';
        reason_start += 2;
    }

    bool need_reason = false;  // Initialize to shut up gcc warning.
    error = parse_status(line, status, status_arg, &need_reason);
    if (kyua_error_is_set(error))
        goto out_input;

    if (need_reason) {
        error = read_reason(input, reason_start, reason, reason_size);
    } else {
        if (reason_start != NULL || !is_really_eof(input)) {
            error = kyua_generic_error_new("Found unexpected reason in passed "
                                           "test result");
            goto out_input;
        }
        reason[0] = '\0';
    }

out_input:
    fclose(input);
out:
    return error;
}
Exemplo n.º 6
0
void handle_user_input(connection_info clients[])
{
  char input[255];
  fgets(input, sizeof(input), stdin);
  trim_newline(input);

  if(input[0] == 'q') {
    stop_server(clients);
  }
}
Exemplo n.º 7
0
static char *
find_obppath (const char *sysfs_path_orig)
{
  char *sysfs_path, *path;
  size_t path_size = strlen (sysfs_path_orig) + sizeof ("/obppath");

  sysfs_path = xstrdup (sysfs_path_orig);
  path = xmalloc (path_size);

  while (1)
    {
      int fd;
      char *of_path;
      struct stat st;
      size_t size;

      snprintf(path, path_size, "%s/obppath", sysfs_path);
#if 0
      printf("Trying %s\n", path);
#endif

      fd = open(path, O_RDONLY);
      if (fd < 0 || fstat (fd, &st) < 0)
	{
	  snprintf(path, path_size, "%s/devspec", sysfs_path);
	  fd = open(path, O_RDONLY);
	}

      if (fd < 0 || fstat (fd, &st) < 0)
	{
	  kill_trailing_dir(sysfs_path);
	  if (!strcmp(sysfs_path, "/sys"))
	    {
	      grub_util_info (_("`obppath' not found in parent dirs of `%s',"
				" no IEEE1275 name discovery"),
			      sysfs_path_orig);
	      free (path);
	      free (sysfs_path);
	      return NULL;
	    }
	  continue;
	}
      size = st.st_size;
      of_path = xmalloc (size + MAX_DISK_CAT + 1);
      memset(of_path, 0, size + MAX_DISK_CAT + 1);
      read(fd, of_path, size);
      close(fd);

      trim_newline(of_path);
      free (path);
      free (sysfs_path);
      return of_path;
    }
}
Exemplo n.º 8
0
/*  Reads a value from the text table.
    Exits  with non-zero status
    if the table is erroneous in some way.
*/
int
read_value(unsigned int *outval, FILE*file)
{
    char *res = 0;
    unsigned long lval;
    char *strout = 0;
    boolean bBlankLine = TRUE;

    ++linecount;
    *outval = 0;

    while (bBlankLine) {
        res = fgets(line_in, sizeof(line_in), file);
        if (res == 0) {
            if (ferror(file)) {
                fprintf(stderr,
                    "tag_attr: Error reading table, %d lines read\n",
                    linecount);
                exit(FAILED);
            }

            if (feof(file)) {
                return IS_EOF;
            }

            /* Impossible */
            fprintf(stderr, "tag_attr: Impossible error reading table, "
                "%d lines read\n", linecount);
            exit(FAILED);
        }

        bBlankLine = is_skippable_line(line_in);
    }

    trim_newline(line_in, sizeof(line_in));
    errno = 0;
    lval = strtoul(line_in, &strout, 0);

    if (strout == line_in) {
        bad_line_input("bad number input!");
    }

    if (errno != 0) {
        int myerr = errno;

        fprintf(stderr, "tag_attr errno %d\n", myerr);
        bad_line_input("invalid number on line");
    }

    *outval = (int) lval;

    return NOT_EOF;
}
Exemplo n.º 9
0
/*
 *  read_dyn_string()
 *
 *  Ask the user a question and prompt for a string answer
 *  The string is dynamically allocated (and so should be freed)
 *  The absolute maximum size that a string can ever be is given by
 *  the #define MAX
 */
char *read_dyn_string(char prompt[])
{
    char    buffer[MAX];

	fputs(prompt, stdout);
	fflush(stdin);
	fgets(buffer, sizeof buffer, stdin);

    trim_newline(buffer);

    return strdup(buffer);
}
Exemplo n.º 10
0
Arquivo: evidence.c Projeto: gaibo/C
int main(void) {
    printf("*****testing hash table*****\n\n");
    htbl* t = ht_new(&good_hash, 10);
    
    FILE* cnets2015 = fopen("cnets2015", "r");
    while (!feof(cnets2015)) {
        char* s = alloc_str(256);
        fgets(s, 256, cnets2015);
        char* l = trim_newline(s);
        free(s);
        if (strlen(l) > 0) {
            ht_ins(l, t);
        }
        free(l);
    }
    fclose(cnets2015);
    
    ht_show(t);
    printf("The hash table has %u buckets with %u entries (load factor %lg).\n\n",
        t->n_buckets, 
        ht_n_entries(t),
        ht_load_factor(t));
    printf("The bucket with the most items in it contains %u items.\n\n",
        ht_max_bucket(t));
    printf("ht_member:\n");
    printf("membership of cnet \"aardvark\" : %i\n", ht_member("aardvark", t));
    printf("membership of cnet \"borja\"    : %i\n", ht_member("borja", t));
    printf("\n");
    
    // resize
    printf("***now resizing***\n");
    ht_resize(&t);
    printf("***resizing complete***\n\n");
    
    // do everything again
    ht_show(t);
    printf("The hash table has %u buckets with %u entries (load factor %lg).\n\n",
        t->n_buckets, 
        ht_n_entries(t),
        ht_load_factor(t));
    printf("The bucket with the most items in it contains %u items.\n\n",
        ht_max_bucket(t));
    printf("ht_member:\n");
    printf("membership of cnet \"aardvark\" : %i\n", ht_member("aardvark", t));
    printf("membership of cnet \"borja\"    : %i\n", ht_member("borja", t));
    printf("\n");
    
    ht_free(t);
    return 0;
}
Exemplo n.º 11
0
// output in human-readable form
//
char* short_jd_string(double jd) {
    static char buf[256];
    time_t tmptime;
#ifdef USE_MANUAL_CALLSTACK
    call_stack.enter("short_jd_string()");
#endif /* USE_MANUAL_CALLSTACK */

    if ( jd > JD0) {
        tmptime=jd_to_time_t(jd);
        strlcpy(buf, asctime(gmtime(&tmptime)),sizeof(buf));
        trim_newline(buf);
    } else {
        strlcpy(buf,"Unknown",sizeof(buf));
    }
#ifdef USE_MANUAL_CALLSTACK
    call_stack.exit();
#endif /* USE_MANUAL_CALLSTACK */
    return buf;
}
Exemplo n.º 12
0
char* jd_string(double jd) {
    static char buf[256], datestr[64];
    time_t tmptime;
#ifdef USE_MANUAL_CALLSTACK
    call_stack.enter("jd_string");
#endif /* USE_MANUAL_CALLSTACK */

    if ( jd > JD0 ) {
        tmptime=jd_to_time_t(jd);
        strlcpy(datestr, asctime(gmtime(&tmptime)), sizeof(datestr));
        trim_newline(datestr);
        sprintf(buf, "%14.5f (%s)", jd, datestr);
    } else {
        sprintf(buf,"%14.5f",jd);
    }
#ifdef USE_MANUAL_CALLSTACK
    call_stack.exit();
#endif /* USE_MANUAL_CALLSTACK */
    return buf;
}
Exemplo n.º 13
0
static void
find_obppath(char *of_path, const char *sysfs_path_orig)
{
    char *sysfs_path, *path;

    sysfs_path = xmalloc (PATH_MAX);
    path = xmalloc (PATH_MAX);

    strcpy(sysfs_path, sysfs_path_orig);
    while (1)
    {
        int fd;

        snprintf(path, PATH_MAX, "%s/obppath", sysfs_path);
#if 0
        printf("Trying %s\n", path);
#endif

        fd = open(path, O_RDONLY);
        if (fd < 0)
        {
            kill_trailing_dir(sysfs_path);
            if (!strcmp(sysfs_path, "/sys"))
                grub_util_error("'obppath' not found in parent dirs of %s",
                                sysfs_path_orig);
            continue;
        }
        memset(of_path, 0, OF_PATH_MAX);
        read(fd, of_path, OF_PATH_MAX);
        close(fd);

        trim_newline(of_path);
        break;
    }

    free (path);
    free (sysfs_path);
}
Exemplo n.º 14
0
zmqpp::message reader::Json::read() {
    zmqpp::message msg;
    msg << target;
    ::Json::Value value;
    ::Json::Reader reader;
    if (!reader.parse(Plain::read_input_str(), value)) {
        throw std::runtime_error(reader.getFormatedErrorMessages());
    }
    if (!value.isArray()) {
        throw std::runtime_error("Must be array");
    }
    for (size_t i = 0; i < value.size(); ++i) {
        auto val = value.get(i, "");
        std::string param = (val.isString() ? val.asString() : val.toStyledString());
        if (!val.isString()) {
            if (verbose) {
                std::cerr << "Item #" << i << " is not string!" << std::endl;
            }
            param = trim_newline(param);
        }
        msg << param;
    }
    return msg;
}
Exemplo n.º 15
0
Arquivo: grep.c Projeto: darius/ung
/* Show any matching lines from 'in'. Return true on success. */
static int grep (const char *regexp, FILE *in, const char *opt_filename) {
  int found = 0;
  unsigned line_num = 0;
  char line[line_capacity];

  char folded_regexp[line_capacity];
  if (!matching_case) {
    if (line_capacity <= strlen (regexp))
      panic ("regexp too long");
    fold_case (folded_regexp, regexp);
    regexp = folded_regexp;
  }

  while (fgets (line, sizeof line, in)) {
    trim_newline (line, opt_filename);
    ++line_num;
    if (matching_positively == matches (regexp, line)) {
      found = 1;
      show (opt_filename, line_num, line);
    }
  }
  must_not_ferror (in, opt_filename ? opt_filename : "<stdin>");
  return found;
}
Exemplo n.º 16
0
static int decode_file (idn_resconf_t conf1, idn_resconf_t conf2, FILE * fp, int flags)
{
    idn_result_t r;

    idnconv_strbuf_t buf1, buf2;

    idn_action_t actions1, actions2;

    int nl_trimmed;

    int local_ace_hack, idn_ace_hack;

    idn_converter_t conv;

    /*
     * See if the input codeset is an ACE.
     */
    conv = idn_resconf_getidnconverter (conf1);
    if (conv != NULL && idn_converter_isasciicompatible (conv) && (flags & FLAG_SELECTIVE))
        idn_ace_hack = 1;
    else
        idn_ace_hack = 0;
    if (conv != NULL)
        idn_converter_destroy (conv);

    conv = idn_resconf_getlocalconverter (conf1);
    if (conv != NULL && idn_converter_isasciicompatible (conv) && (flags & FLAG_SELECTIVE))
        local_ace_hack = 1;
    else
        local_ace_hack = 0;
    if (conv != NULL)
        idn_converter_destroy (conv);

    actions1 = IDN_IDNCONV;

    if (local_ace_hack)
    {
        actions2 = IDN_IDNCONV;
        if (flags & FLAG_MAP)
            actions2 |= IDN_MAP;
        if (flags & FLAG_NORMALIZE)
            actions2 |= IDN_NORMALIZE;
        if (flags & FLAG_PROHIBITCHECK)
            actions2 |= IDN_PROHCHECK;
        if (flags & FLAG_UNASSIGNCHECK)
            actions2 |= IDN_UNASCHECK;
        if (flags & FLAG_BIDICHECK)
            actions2 |= IDN_BIDICHECK;
        if (flags & FLAG_ASCIICHECK)
            actions2 |= IDN_ASCCHECK;
        if (flags & FLAG_LENGTHCHECK)
            actions2 |= IDN_LENCHECK;
    }
    else
    {
        actions2 = IDN_LOCALCONV;
    }

    if (flags & FLAG_DELIMMAP)
        actions1 |= IDN_DELIMMAP;
    if (flags & FLAG_MAP)
        actions1 |= IDN_MAP;
    if (flags & FLAG_NORMALIZE)
        actions1 |= IDN_NORMALIZE;
    if (flags & FLAG_NORMALIZE)
        actions1 |= IDN_NORMALIZE;
    if (flags & FLAG_PROHIBITCHECK)
        actions1 |= IDN_PROHCHECK;
    if (flags & FLAG_UNASSIGNCHECK)
        actions1 |= IDN_UNASCHECK;
    if (flags & FLAG_BIDICHECK)
        actions1 |= IDN_BIDICHECK;
    if (flags & FLAG_ASCIICHECK)
        actions1 |= IDN_ASCCHECK;
    if (flags & FLAG_ROUNDTRIPCHECK)
        actions1 |= IDN_RTCHECK;

    strbuf_init (&buf1);
    strbuf_init (&buf2);
    line_number = 1;
    while (strbuf_getline (&buf1, fp) != NULL)
    {
        /*
         * Trim newline at the end.  This is needed for
         * those ascii-comatible encodings such as UTF-5 or RACE
         * not to try converting newlines, which will result
         * in `invalid encoding' error.
         */
        nl_trimmed = trim_newline (&buf1);

        /*
         * Treat input line as the string encoded in local
         * encoding and convert it to UTF-8 encoded string.
         */
        if (local_ace_hack)
        {
            if (strbuf_copy (&buf2, strbuf_get (&buf1)) == NULL)
                r = idn_nomemory;
            else
                r = idn_success;
        }
        else
        {
            r = convert_line (&buf1, &buf2, conf1, IDN_LOCALCONV, 0);
        }
        if (r != idn_success)
        {
            errormsg ("conversion failed at line %d: %s\n", line_number, idn_result_tostring (r));
            goto error;
        }

        /*
         * Convert internationalized domain names in the line.
         */
        if (idn_ace_hack)
        {
            r = convert_line (&buf2, &buf1, conf1, actions1, FLAG_REVERSE | FLAG_SELECTIVE);
        }
        else
        {
            r = convert_line (&buf2, &buf1, conf1, actions1, FLAG_REVERSE);
        }
        if (r != idn_success)
        {
            errormsg ("conversion failed at line %d: %s\n", line_number, idn_result_tostring (r));
            goto error;
        }
        if (!idn_utf8_isvalidstring (strbuf_get (&buf1)))
        {
            errormsg ("conversion to utf-8 failed at line %d\n", line_number);
            goto error;
        }

        /*
         * Perform round trip check and convert to the output
         * codeset.
         */
        if (local_ace_hack)
        {
            r = convert_line (&buf1, &buf2, conf2, actions2, FLAG_SELECTIVE);
        }
        else
        {
            r = convert_line (&buf1, &buf2, conf1, actions2, FLAG_REVERSE);
        }

        if (r != idn_success)
        {
            errormsg ("error in nameprep or output conversion "
                      "at line %d: %s\n", line_number, idn_result_tostring (r));
            goto error;
        }

        fputs (strbuf_get (&buf2), stdout);
        if (nl_trimmed)
            putc ('\n', stdout);

        if (flush_every_line)
            fflush (stdout);

        line_number++;
    }
    strbuf_reset (&buf1);
    strbuf_reset (&buf2);
    return (0);

  error:
    strbuf_reset (&buf1);
    strbuf_reset (&buf2);
    return (1);
}
Exemplo n.º 17
0
/* main:
 * read an optional size argument for hash table,
 * read in strings from standard input,
 * build hash table,
 * display hash table and a few statistics */
int main(int argc, char *argv[])
{
  htbl *t;
  int sz = DEFAULT_SIZE;
  int use_bad_hash = 0;
  char c;
  /* note: read about "getopt" to learn about command-line arg processing */
  while ((c=getopt(argc,argv,"bs:"))!=-1) {
    switch (c) {
    case 'b':
      use_bad_hash = 1;
      break;
    case 's':
      sz = atoi(optarg);
      if (sz<1) {
	fprintf(stderr,"%s error: nonpositive table size %d\n",*argv,sz);
	exit(1);
      }
      break;
    case '?':
      usage(*argv);
      exit(1);
    }
  }
  /* build a new empty hash table */
  t = htbl_new(use_bad_hash?&bad_hash:&good_hash,sz);
  /* read a line at a time from stdin, add non-empty strings to the table */
  while (!feof(stdin)) {
    char *s = alloc_str(MAX_LINE_LEN);
    char *l;
    unsigned int n;
    fgets(s,MAX_LINE_LEN,stdin);
    l = trim_newline(s);
    free(s);

    if (strlen(l)>0)
      htbl_ins(l,t,&n);
    free(l);
  }
    /*unsigned int n = 0; 
    char* s = "FORK"; 
    htbl_ins(s, t, &n);  */ 
  htbl_show(stdout,t);
  printf("\nThe hash table has %i buckets with %i entries (load factor %lg).\n",
	 t->n_buckets, 
	 htbl_num_entries(t),
	 htbl_load_factor(t));
  unsigned int max, max_index;
  htbl_max_bucket(t,&max,&max_index);
  printf("\nThe bucket with the most items in it contains %u items (bucket %u).\n",
	 max,max_index);
  /* test hash table membership */
  /* "aardvark" is not in the cnet file; "borja" is */
  printf("\ntesting htbl_member:\n");
  printf("membership of cnet \"aardvark\" (expecting 0): %i\n", 
	 htbl_member("aardvark",t));
  printf("membership of cnet \"borja\"    (expecting 1): %i\n", 
	 htbl_member("borja",t));
  htbl_free(t);
  return 0;
}
Exemplo n.º 18
0
void handle_user_input(connection_info *connection) {
	char input[255];
	fgets(input, 255, stdin);
	trim_newline(input);

	if (strcmp(input, "/q") == 0 || strmp(input, "/quit") == 0) {
		stop_client(connection);
	} else if (strcmp(input, "/l") == 0 || strcmp(input, "/quit") == 0) {
		message msg;
		msg.type = GET_USERS;

		if (send(connection->socket, &msg, sizeof(message), 0) < 0) {
			perror("Send failed");
			exit(1);
		}
	} else if (strcmp(input, "/h") == 0 || strcmp(input, "/help") == 0) {
		puts("/quit or /q: Exit the program");
		puts("/help or /h: Displays help information");
		puts("/list or /l: Displays list of users in chatroom");
		puts("/m <username> <message> Send a private message to <username>");
	} else if (strcmp(input, "/m", 2) == 0) {
		message msg;
		msg.type = PRIVATE_MESSAGE;

		char * toUsername, *chatMsg;

		toUsername = strtok(input+3, " ");

		if (toUsername == NULL) {
			puts(KRED, "Format for private messages is: /, <username> <message" RESET);
			return;
		}
		if (toUsername == 0) {
			puts(KRED, "You must enter a username for a private message" RESET);
			return;
		}
		if (toUsername > 20) {
			puts(KRED, "The username must be between 1 and 20 characters" RESET);
			return;
		}

		chatMsg = strtok(NULL, "");

		if (chatMsg == NULL) {
			puts(KRED, "You must enter a message to send to the specified user" RESET);
			return;
		}
		strncpy(msg.username, toUsername, 20);
		strncpy(msg.data, chatMsg, 255);

		if (send(connection->socket, $msg, sizeof(message), 0) < 0) {
			perror("Send failed");
			exit(1);
		}
	} else {
		// Regular public message
		message msg;
		msg.type = PUBLIC_MESSAGE;
		strncpy(msg.username, connection->username, 20);

		if (strlen(input) == 0);

		// Send the data
		if (send(connection->socket, &msg, sizeof(message), 0) < 0) {
			perror("Send failed");
			exit(1);
		}
	}
}
Exemplo n.º 19
0
/*
 Standart behaviour:
   if malformed or missing subtitle id - calculate, continue.
   if malformer or missing timing - skip event competely, text without timing is useless.
   if missing text - skip event, empty event also useless.
 */
bool
parse_srt_file(FILE *infile, srt_file * const file)
  {
    char line[MAXLINE] = "";
    char text_buf[MAXLINE] = "";
    int s_len = 0;
    bool skip_event = false;
    uint16_t parsed = 0; /* num events parsed */
    uint8_t t_detect = 3; /* number of first timing strings to analyze */
    srt_event *event = (srt_event *) 0;
    srt_event **elist_tail = &file->events;

    if (!infile) return false;

    curr_line = unknown;

    while(!feof(infile))
      {
        fgets(line, MAXLINE, infile);
        line_num++;

        /* unicode handle */
        if (line_num == 1)
          charset_type = unicode_check(line, 0);

        prev_line = curr_line;
        curr_line = unknown;

        trim_newline(line);
        log_msg(raw, "%s", line);
        trim_spaces(line, LINE_START | LINE_END);
        s_len = strlen(line);

        if      (s_len == 0)          curr_line = blank;
        else if (strstr(line, "-->")) curr_line = timing;
        else if (prev_line == blank ||
                 prev_line == unknown) curr_line = id;  /* at least, expected */
        else /* prev_line == timing*/ curr_line = text; /* also expected */


        if (feof(infile)) curr_line = blank;

        if (feof(infile) && s_len != 0)
          {
            log_msg(warn, MSG_F_UNEXPEOF, line_num);
            if (prev_line == text)
              append_string(text_buf, line, "\n", MAXLINE, 0);
            else
              strncpy(text_buf, line, MAXLINE);
          }

        log_msg(debug, "Line type: %i", curr_line);

        if (curr_line == id || (curr_line == timing && prev_line == blank))
          {
            CALLOC(event, 1, sizeof(srt_event));
            memset(text_buf, 0x0, MAXLINE);

            if (curr_line != id)
              {
                log_msg(warn, _("Missing subtitle id at line '%u'."), line_num);
                event->id = ++parsed;
              }
          }

        if (prev_line == timing && curr_line == blank)
          {
            log_msg(warn, _("Empty subtitle text at line %u. Event will be skipped."), line_num);
            skip_event = true;
          }

        if (prev_line == id && curr_line == blank)
          {
            log_msg(warn, _("Lonely subtitle id without timing or text. :-("));
            skip_event = true;
          }

        switch (curr_line)
          {
            case id     :
              /* See header for comments */
              event->id = ++parsed;
              /* if ((event->id = atoi(line)) != 0) parsed++; */
              break;
            case timing :
              if (t_detect-- && !(file->flags & SRT_E_STRICT))
                analyze_srt_timing(line, &file->flags);
              skip_event = !parse_srt_timing(event, line, &file->flags);
              if (event->start > event->end)
                {
                  log_msg(warn, _("Negative duration of event at line '%u'. Event will be skipped."), line_num);
                  skip_event = true;
                }
              /*printf("%f --> %f\n", event->start, event->end);*/
              break;
            case text :
              /* TODO: wrapping handling here   */
              if (prev_line == text)
                append_string(text_buf, line, "\n", MAXLINE, 0);
              else
                strncpy(text_buf, line, MAXLINE);
              break;
            case blank :
              if (!skip_event && prev_line != blank)
                {
                  if ((event->text = strndup(text_buf, MAXLINE)) == NULL)
                    log_msg(error, MSG_M_OOM);
                  srt_event_append(&file->events, &elist_tail, event, opts.i_sort);
                  memset(text_buf, 0, MAXLINE);
                }
            case unknown :
            default      :
              continue;
              break;
          }

        if (skip_event)
          {
            /* clean parsed stuff & skip calloc() next time */
            memset(event, 0, sizeof(srt_event));
            memset(text_buf, 0, MAXLINE);
            parsed--;
          }
     }

    return true; /* if we reach this line, no error happens */
  }
Exemplo n.º 20
0
/*
** Read the git-fast-import format from pIn and insert the corresponding
** content into the database.
*/
static void git_fast_import(FILE *pIn){
  ImportFile *pFile, *pNew;
  int i, mx;
  char *z;
  char *zUuid;
  char *zName;
  char *zPerm;
  char *zFrom;
  char *zTo;
  char zLine[1000];

  gg.xFinish = finish_noop;
  while( fgets(zLine, sizeof(zLine), pIn) ){
    if( zLine[0]=='\n' || zLine[0]=='#' ) continue;
    if( memcmp(zLine, "blob", 4)==0 ){
      gg.xFinish();
      gg.xFinish = finish_blob;
    }else
    if( memcmp(zLine, "commit ", 7)==0 ){
      gg.xFinish();
      gg.xFinish = finish_commit;
      trim_newline(&zLine[7]);
      z = &zLine[7];

      /* The argument to the "commit" line might match either of these
      ** patterns:
      **
      **   (A)  refs/heads/BRANCHNAME
      **   (B)  refs/tags/TAGNAME
      **
      ** If pattern A is used, then the branchname used is as shown.
      ** Except, the "master" branch which is the default branch name in
      ** Git is changed to "trunk" which is the default name in Fossil.
      ** If the pattern is B, then the new commit should be on the same
      ** branch as its parent.  And, we might need to add the TAGNAME
      ** tag to the new commit.  However, if there are multiple instances
      ** of pattern B with the same TAGNAME, then only put the tag on the
      ** last commit that holds that tag.
      **
      ** None of the above is explained in the git-fast-export
      ** documentation.  We had to figure it out via trial and error.
      */
      for(i=strlen(z)-1; i>=0 && z[i]!='/'; i--){}
      gg.tagCommit = memcmp(&z[i-4], "tags", 4)==0;  /* True for pattern B */
      if( z[i+1]!=0 ) z += i+1;
      if( fossil_strcmp(z, "master")==0 ) z = "trunk";
      gg.zBranch = fossil_strdup(z);
      gg.fromLoaded = 0;
    }else
    if( memcmp(zLine, "tag ", 4)==0 ){
      gg.xFinish();
      gg.xFinish = finish_tag;
      trim_newline(&zLine[4]);
      gg.zTag = fossil_strdup(&zLine[4]);
    }else
    if( memcmp(zLine, "reset ", 4)==0 ){
      gg.xFinish();
    }else
    if( memcmp(zLine, "checkpoint", 10)==0 ){
      gg.xFinish();
    }else
    if( memcmp(zLine, "feature", 7)==0 ){
      gg.xFinish();
    }else
    if( memcmp(zLine, "option", 6)==0 ){
      gg.xFinish();
    }else
    if( memcmp(zLine, "progress ", 9)==0 ){
      gg.xFinish();
      trim_newline(&zLine[9]);
      fossil_print("%s\n", &zLine[9]);
      fflush(stdout);
    }else
    if( memcmp(zLine, "data ", 5)==0 ){
      fossil_free(gg.aData); gg.aData = 0;
      gg.nData = atoi(&zLine[5]);
      if( gg.nData ){
        int got;
        gg.aData = fossil_malloc( gg.nData+1 );
        got = fread(gg.aData, 1, gg.nData, pIn);
        if( got!=gg.nData ){
          fossil_fatal("short read: got %d of %d bytes", got, gg.nData);
        }
        gg.aData[got] = 0;
        if( gg.zComment==0 && gg.xFinish==finish_commit ){
          gg.zComment = gg.aData;
          gg.aData = 0;
          gg.nData = 0;
        }
      }
    }else
    if( memcmp(zLine, "author ", 7)==0 ){
      /* No-op */
    }else
    if( memcmp(zLine, "mark ", 5)==0 ){
      trim_newline(&zLine[5]);
      fossil_free(gg.zMark);
      gg.zMark = fossil_strdup(&zLine[5]);
    }else
    if( memcmp(zLine, "tagger ", 7)==0 || memcmp(zLine, "committer ",10)==0 ){
      sqlite3_int64 secSince1970;
      for(i=0; zLine[i] && zLine[i]!='<'; i++){}
      if( zLine[i]==0 ) goto malformed_line;
      z = &zLine[i+1];
      for(i=i+1; zLine[i] && zLine[i]!='>'; i++){}
      if( zLine[i]==0 ) goto malformed_line;
      zLine[i] = 0;
      fossil_free(gg.zUser);
      gg.zUser = fossil_strdup(z);
      secSince1970 = 0;
      for(i=i+2; fossil_isdigit(zLine[i]); i++){
        secSince1970 = secSince1970*10 + zLine[i] - '0';
      }
      fossil_free(gg.zDate);
      gg.zDate = db_text(0, "SELECT datetime(%lld, 'unixepoch')", secSince1970);
      gg.zDate[10] = 'T';
    }else
    if( memcmp(zLine, "from ", 5)==0 ){
      trim_newline(&zLine[5]);
      fossil_free(gg.zFromMark);
      gg.zFromMark = fossil_strdup(&zLine[5]);
      fossil_free(gg.zFrom);
      gg.zFrom = resolve_committish(&zLine[5]);
    }else
    if( memcmp(zLine, "merge ", 6)==0 ){
      trim_newline(&zLine[6]);
      if( gg.nMerge>=gg.nMergeAlloc ){
        gg.nMergeAlloc = gg.nMergeAlloc*2 + 10;
        gg.azMerge = fossil_realloc(gg.azMerge, gg.nMergeAlloc*sizeof(char*));
      }
      gg.azMerge[gg.nMerge] = resolve_committish(&zLine[6]);
      if( gg.azMerge[gg.nMerge] ) gg.nMerge++;
    }else
    if( memcmp(zLine, "M ", 2)==0 ){
      import_prior_files();
      z = &zLine[2];
      zPerm = next_token(&z);
      zUuid = next_token(&z);
      zName = rest_of_line(&z);
      dequote_git_filename(zName);
      i = 0;
      pFile = import_find_file(zName, &i, gg.nFile);
      if( pFile==0 ){
        pFile = import_add_file();
        pFile->zName = fossil_strdup(zName);
      }
      pFile->isExe = (fossil_strcmp(zPerm, "100755")==0);
      pFile->isLink = (fossil_strcmp(zPerm, "120000")==0);
      fossil_free(pFile->zUuid);
      pFile->zUuid = resolve_committish(zUuid);
      pFile->isFrom = 0;
    }else
    if( memcmp(zLine, "D ", 2)==0 ){
      import_prior_files();
      z = &zLine[2];
      zName = rest_of_line(&z);
      dequote_git_filename(zName);
      i = 0;
      while( (pFile = import_find_file(zName, &i, gg.nFile))!=0 ){
        if( pFile->isFrom==0 ) continue;
        fossil_free(pFile->zName);
        fossil_free(pFile->zPrior);
        fossil_free(pFile->zUuid);
        *pFile = gg.aFile[--gg.nFile];
        i--;
      }
    }else
    if( memcmp(zLine, "C ", 2)==0 ){
      int nFrom;
      import_prior_files();
      z = &zLine[2];
      zFrom = next_token(&z);
      zTo = rest_of_line(&z);
      i = 0;
      mx = gg.nFile;
      nFrom = strlen(zFrom);
      while( (pFile = import_find_file(zFrom, &i, mx))!=0 ){
        if( pFile->isFrom==0 ) continue;
        pNew = import_add_file();
        pFile = &gg.aFile[i-1];
        if( strlen(pFile->zName)>nFrom ){
          pNew->zName = mprintf("%s%s", zTo, pFile->zName[nFrom]);
        }else{
          pNew->zName = fossil_strdup(pFile->zName);
        }
        pNew->isExe = pFile->isExe;
        pNew->isLink = pFile->isLink;
        pNew->zUuid = fossil_strdup(pFile->zUuid);
        pNew->isFrom = 0;
      }
    }else
    if( memcmp(zLine, "R ", 2)==0 ){
      int nFrom;
      import_prior_files();
      z = &zLine[2];
      zFrom = next_token(&z);
      zTo = rest_of_line(&z);
      i = 0;
      nFrom = strlen(zFrom);
      while( (pFile = import_find_file(zFrom, &i, gg.nFile))!=0 ){
        if( pFile->isFrom==0 ) continue;
        pNew = import_add_file();
        pFile = &gg.aFile[i-1];
        if( strlen(pFile->zName)>nFrom ){
          pNew->zName = mprintf("%s%s", zTo, pFile->zName[nFrom]);
        }else{
          pNew->zName = fossil_strdup(pFile->zName);
        }
        pNew->zPrior = pFile->zName;
        pNew->isExe = pFile->isExe;
        pNew->isLink = pFile->isLink;
        pNew->zUuid = pFile->zUuid;
        pNew->isFrom = 0;
        gg.nFile--;
        *pFile = *pNew;
        memset(pNew, 0, sizeof(*pNew));
      }
      fossil_fatal("cannot handle R records, use --full-tree");
    }else
    if( memcmp(zLine, "deleteall", 9)==0 ){
      gg.fromLoaded = 1;
    }else
    if( memcmp(zLine, "N ", 2)==0 ){
      /* No-op */
    }else

    {
      goto malformed_line;
    }
  }
  gg.xFinish();
  if( gg.hasLinks ){
    db_set_int("allow-symlinks", 1, 0);
  }
  import_reset(1);
  return;

malformed_line:
  trim_newline(zLine);
  fossil_fatal("bad fast-import line: [%s]", zLine);
  return;
}