|
| 1 | +require 'yaml' |
| 2 | +require 'yaml/front-matter' |
| 3 | +require 'fileutils' |
| 4 | +require 'securerandom' |
| 5 | + |
| 6 | +USER_XCODE_SNIPPETS_DIRECTORY = "~/Library/Developer/Xcode/UserData/CodeSnippets/" |
| 7 | + |
| 8 | +command :install do |c| |
| 9 | + c.syntax = 'codesnippet install [SNIPPET]' |
| 10 | + c.summary = 'Create and Install an Xcode Snippet' |
| 11 | + c.description = 'Creates and installs an Xcode .codesnippet file from an source file annotated with YAML front matter.' |
| 12 | + |
| 13 | + c.example 'description', 'codesnippet install /path/to/code.source' |
| 14 | + |
| 15 | + c.action do |args, options| |
| 16 | + say_error "Input file required" and abort unless @input_filepath = args.first |
| 17 | + say_error "Input file does not exist" and abort unless File.exist?(@input_filepath) |
| 18 | + |
| 19 | + @content = File.read(@input_filepath) |
| 20 | + say_error "Input file is empty" and abort if @content.empty? |
| 21 | + |
| 22 | + extract_front_matter! |
| 23 | + |
| 24 | + @output_filepath = File.join(USER_XCODE_SNIPPETS_DIRECTORY, @snippet.identifier + ".codesnippet") |
| 25 | + begin |
| 26 | + FileUtils.mkdir_p(USER_XCODE_SNIPPETS_DIRECTORY) |
| 27 | + |
| 28 | + File.open(@output_filepath, 'w') do |f| |
| 29 | + f.write @snippet.to_plist |
| 30 | + end |
| 31 | + rescue => error |
| 32 | + say_error "Error: #{error.message}" and abort |
| 33 | + end |
| 34 | + |
| 35 | + say_ok "Installed Code Snippet" |
| 36 | + puts @output_filepath |
| 37 | + end |
| 38 | +end |
| 39 | + |
| 40 | +private |
| 41 | + |
| 42 | +def extract_front_matter! |
| 43 | + @snippet = XcodeSnippet::Snippet.new |
| 44 | + |
| 45 | + front_matter, contents = YAML::FrontMatter.extract(@content) |
| 46 | + |
| 47 | + if front_matter.empty? |
| 48 | + say_error "No YAML Front Matter Detected" and abort |
| 49 | + else |
| 50 | + @snippet.contents = contents.strip |
| 51 | + @snippet.completion_prefix = File.basename(@input_filepath, File.extname(@input_filepath)) |
| 52 | + @snippet.language = case File.extname(@input_filepath) |
| 53 | + when ".swift" then "Xcode.SourceCodeLanguage.Swift" |
| 54 | + when ".m" then "Xcode.SourceCodeLanguage.Objective-C" |
| 55 | + when ".mm" then "Xcode.SourceCodeLanguage.Objective-C++" |
| 56 | + else "" |
| 57 | + end |
| 58 | + @snippet.title = front_matter["title"] || "" |
| 59 | + @snippet.summary = front_matter["summary"] || "" |
| 60 | + @snippet.completion_scopes = [front_matter["completion-scope"]] || front_matter["completion-scopes"] || "All" |
| 61 | + @snippet.identifier = SecureRandom.uuid().upcase |
| 62 | + @snippet.is_user_snippet = true |
| 63 | + @snippet.version = 0 |
| 64 | + end |
| 65 | +end |
0 commit comments