entry_add.awk (2820B)
1 #!/bin/awk 2 3 function get_date( s, f ){ 4 gsub( x_whtspc, "", s ) 5 date_good = "date -d \""s"\" +\""f"\" 2>/dev/null" | getline r 6 close( r ) 7 #if ( !date_good ) { exit 1 } 8 return r 9 } 10 11 function mktime_format( s ){ 12 return get_date( s, "%Y %m %d %H %M 00" ) 13 } 14 15 function mkapt_time( s ){ 16 r = mktime( s ) 17 return strftime( "%m/%d/%Y @ %H:%M", r ) 18 } 19 20 BEGIN{ 21 x_whtspc = "^[[:space:]]*|[[:space:]]*$" 22 x_recur_full = "#[0-9]+[a-zA-Z].*$" 23 x_recur = "^[0-9]+[a-zA-Z]" 24 } 25 { 26 # split dates from description into array 'a' 27 split( $0, a, "::" ) 28 29 # Trim whitespace 30 gsub( x_whtspc, "", a[2] ) 31 gsub( x_whtspc, "", a[1] ) 32 33 # Must have a description. 34 if ( ! a[2] ) { exit 1 } 35 36 # Todo entry: a[1] = optional rank, a[2] = description 37 if ( typeflag == "t" ){ 38 39 # Rank number, default 0 40 if ( a[1] ){ b = a[1] } else { b = 0 } 41 42 entry = sprintf( "[%s] %s", b, a[2] ) 43 44 # Skip all else for todo entry 45 next 46 } 47 48 # Extract recurrent value from a[1] if present 49 if ( match( a[1], x_recur_full ) > 0 ){ 50 51 # Leave the pound sign behind, add one to RSTART 52 recur_full = substr( a[1], RSTART + 1 ) 53 match( recur_full, x_recur ) 54 recur = toupper( substr( recur_full, 1, RLENGTH ) ) 55 recur_date = substr( recur_full, RLENGTH + 1 ) 56 if (recur_date){ 57 recur_date = sprintf( " -> %s", get_date( recur_date, "%m/%d/%Y" ) ) 58 if ( ! date_good ) { exit 1 } 59 }else{ 60 recur_date = "" 61 } 62 recur = sprintf( " {%s%s} ", recur, recur_date ) 63 64 # Remove from a[1] for rest of date processing 65 sub( x_recur_full, "", a[1] ) 66 } 67 68 # Split start and possible end date into array 'b' 69 bl = split( a[1], b, "-" ) 70 71 # Use external date command to format for mktime 72 if ( ! ( c_a = mktime_format( b[1] ))) { exit 1; } 73 c_a = mktime( c_a ) 74 75 if ( a[1] ~ /[0-9]+:[0-9]+/ || a[1] ~ /min|minute|hour/ ) { 76 time_a = strftime( "%m/%d/%Y @ %H:%M", c_a ) 77 if ( bl > 1 ) { 78 # First check if date 2 is give as only a time 79 if ( b[2] ~ /^[[:space:]]*[0-9]+:[0-9]+[[:space:]]*$/ ){ 80 gsub( x_whtspc , "", b[2] ) 81 gsub( /:/, " ", b[2] ) 82 c_b = sprintf( "%s %s 00", strftime("%Y %m %d", c_a), b[2] ) 83 }else{ 84 # Now try to parse date 2 as it were an addition to first date 85 # eg: "1 hour" from date 1 86 c_b = mktime_format(sprintf( "%s %s", b[1], b[2] )) 87 if ( ! date_good ) { 88 # Now try to make full date/time from date 2 89 c_b = mktime_format( b[2] ) 90 if ( ! date_good ) { 91 # If all tries fail then exit 92 exit 1; 93 } 94 } 95 } 96 time_b = mkapt_time(c_b) 97 }else{ 98 time_b = time_a 99 } 100 entry_type = recur ? "apt_recur" : "apt" 101 entry = sprintf("%s -> %s%s|%s", time_a, time_b, recur, a[2]) 102 103 }else{ 104 entry_type = recur ? "evt_recur" : "evt" 105 106 c_a = strftime("%m/%d/%Y", c_a) 107 108 ( ! recur ) && recur = " " 109 entry = sprintf("%s [1]%s%s", c_a, recur, a[2]) 110 } 111 } 112 END{ 113 if ( entry ) { print entry } 114 }