Skip to content

Instantly share code, notes, and snippets.

@prati0100
Created March 21, 2020 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prati0100/d7c8a7b2c3f94d070a98e0c69fd84ecf to your computer and use it in GitHub Desktop.
Save prati0100/d7c8a7b2c3f94d070a98e0c69fd84ecf to your computer and use it in GitHub Desktop.
#!/usr/bin/env tclsh
if {$argc > 2} {
puts "More arguments than expected"
exit 1
}
set dirname [lindex $argv 0]
# Create the target directory if it doesn't already exist.
if {[catch {file mkdir $dirname}]} {
exit 1
}
set message [read stdin]
# Get the subject line. We need it to decide the file name.
set subject [lindex [regexp -line -inline {^Subject: .*} $message] 0]
if {$subject eq {}} {
puts "Error! No subject line found"
exit 1
}
# Strip the "Subject: " at the start
set subject [regsub {^Subject: } $subject {}]
# Remove all blocks wrapped in square brackets. Then remove all initial
# whitespace.
set stripped_subject [regsub -all {\[.*\]} $subject {}]
set stripped_subject [string trim $stripped_subject]
set file_ext ".mbox"
set is_patch [regexp {\[.*PATCH.*\]} $subject]
if {$is_patch} {
set patch_num {}
regexp {\[.*PATCH.*([0-9]+)/[0-9]+.*\]} $subject foo patch_num
# If no patch number was found, set it to 1.
if {$patch_num eq {}} {
set patch_num 1
}
# Make it a 4-digit number, just like the output from git-format-patch.
set patch_num [format "%04d" $patch_num]
set patch_version {}
regexp {\[.*PATCH.*\]} $subject foo
regexp {v[0-9]+} $foo patch_version
if {$patch_version eq {}} {
set patch_version "v1"
}
# If the second argument is supplied, over-ride the patch version.
if {[lindex $argv 1] ne {}} {
set patch_version [lindex $argv 1]
}
set file_ext ".patch"
set filename "$patch_version-$patch_num-"
}
# Convert all non-alpha characters to '-', and remove consecutive dashes.
set filename [regsub -all {[^[:alnum:]]} "$filename$stripped_subject" "-"]
set filename [regsub -all -- {--+} $filename "-"]
# Strip the filename to 60 characters.
set filename [string range $filename 0 59]
# Add the directory and extension.
set filename "$dirname/$filename$file_ext"
# Make sure the file does not already exist.
if {[file exists $filename]} {
puts "Error! $filename already exists"
exit 1
}
# Create the file and output the data.
if {[catch {set fd [open $filename "w"]]} {
puts "Error opening the file $filename"
exit 1
}
puts -nonewline $fd $message
if {[catch {close $fd}]} {
puts "Error writing the file $filename"
exit 1
}
# All done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment