Skip to content

Instantly share code, notes, and snippets.

@ralfebert
Last active December 11, 2020 13:13
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 ralfebert/cdc30dbc9d2c2356d8f9b6b7c1492888 to your computer and use it in GitHub Desktop.
Save ralfebert/cdc30dbc9d2c2356d8f9b6b7c1492888 to your computer and use it in GitHub Desktop.
Create and open a file from the shell using simple templates
#!/usr/bin/env ruby
# Create and open a file from the shell using simple templates
# https://gist.github.com/ralfebert/cdc30dbc9d2c2356d8f9b6b7c1492888/edit
require 'date'
require 'shellwords'
require 'ostruct'
require 'optionparser'
# --- Templates
templates = []
templates << OpenStruct.new(ext: ".md", name: "Markdown", text: "# Hello world")
templates << OpenStruct.new(ext: ".html", name: "HTML", text: %{<html>
<head>
<title>Example</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/spcss@0.5.0">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
})
templates << OpenStruct.new(ext: ".rb", executable: true, name: "Ruby", text: %{#!/usr/bin/env ruby
puts 'Hello world'
})
templates << OpenStruct.new(ext: ".py", executable: true, name: "Python", text: %{#!/usr/bin/env python
print('Hello world')
})
templates << OpenStruct.new(ext: ".csv", executable: true, name: "Comma-separated values", text: %{Column 1,Column 2
Hello,World
})
# --- Command line arguments
options = OpenStruct.new
parser = OptionParser.new do |opts|
opts.banner = %{Usage: create [options] [filename]
By default the file is created in ~/Desktop, you can also create a file in the current folder, f.e.
create ./index.html
Supported file formats:
#{templates.map { |template| "- #{template.name} (#{template.ext})" }.join("\n")}
Options:
}
opts.on("-d", "--date", "Prefix with a timestamp") do |v|
options[:date_prefix] = true
end
end
parser.parse!
# --- File creation
name = ARGV.join(" ")
ext = File.extname(name).downcase
template = templates.filter{ |template| template.ext == ext }.first
unless template
puts parser.help
exit(1)
end
if name.start_with?('./')
path = File.dirname(name)
name = File.basename(name)
else
path = File.join(File.expand_path('~'), 'Desktop')
end
if options.date_prefix
name = DateTime.now.strftime("%Y-%m-%d %H.%M.%S") + " " + name
end
path = File.join(path, name)
if File.exist?(path)
STDERR.puts("'#{path}' already exists.")
exit(1)
end
File.write(path, template.text)
if template.executable
FileUtils.chmod("+x", path)
end
`open #{path.shellescape}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment