seconds: tolerate trailing whitespace in dates

This allows handling dates with leading and trailing whitespace,
including newlines.
This commit is contained in:
Ori Bernstein 2020-09-01 19:03:17 -07:00
parent e9cd41467e
commit e0278f6917

View file

@ -1,5 +1,6 @@
#include <u.h> #include <u.h>
#include <libc.h> #include <libc.h>
#include <ctype.h>
char *knownfmt[] = { char *knownfmt[] = {
/* asctime */ /* asctime */
@ -57,6 +58,16 @@ char *zonefmt[] = {
nil, nil,
}; };
static int
nojunk(char *p)
{
while(isspace(*p))
p++;
if(*p == '\0')
return 1;
werrstr("trailing junk");
return 0;
}
static void static void
usage(void) usage(void)
@ -89,24 +100,21 @@ main(int argc, char **argv)
sysfatal("bad local time: %r"); sysfatal("bad local time: %r");
for(i = 0; i < argc; i++){ for(i = 0; i < argc; i++){
if(fmt != nil){ if(fmt != nil){
if(tmparse(&tm, fmt, argv[i], tz, &ep) != nil && *ep == 0) if(tmparse(&tm, fmt, argv[i], tz, &ep) && nojunk(ep))
goto Found; goto Found;
}else{ }else{
for(f = knownfmt; *f != nil; f++) for(f = knownfmt; *f != nil; f++)
if(tmparse(&tm, *f, argv[i], tz, &ep) != nil && *ep == 0) if(tmparse(&tm, *f, argv[i], tz, &ep) != nil && nojunk(ep))
goto Found; goto Found;
for(df = datefmt; *df; df++) for(df = datefmt; *df; df++)
for(tf = timefmt; *tf; tf++) for(tf = timefmt; *tf; tf++)
for(zf = zonefmt; *zf; zf++){ for(zf = zonefmt; *zf; zf++){
snprint(buf, sizeof(buf), "%s%s%s", *df, *tf, *zf); snprint(buf, sizeof(buf), "%s%s%s", *df, *tf, *zf);
if(tmparse(&tm, buf, argv[i], tz, &ep) != nil && *ep == 0) if(tmparse(&tm, buf, argv[i], tz, &ep) != nil && nojunk(ep))
goto Found; goto Found;
} }
} }
if(*ep == 0) sysfatal("tmparse: %r");
sysfatal("tmparse: %r");
else
sysfatal("tmparse: trailing junk");
Found: Found:
print("%lld\n", tmnorm(&tm)); print("%lld\n", tmnorm(&tm));
} }