I would like to extract comments (matching to patterns) from my R source script keeping the functions in which they occurs.
The goal is to write documentation comments inside function body code using classic markdown checkboxes - [ ]
or - [x]
and extract those comments for further processing as list of character vectors - which I can easily write to new .md
file.
Reproducible example and expected output below.
# preview the 'data'
script_body = c('# some init comment - not matching pattern','g = function(){','# - [x] comment_g1','# - [ ] comment_g2','1','}','f = function(){','# - [ ] comment_f1','# another non match to pattern','g()+1','}')
cat(script_body, sep = "\n")
# # some init comment - not matching pattern
# g = function(){
# # - [x] comment_g1
# # - [ ] comment_g2
# 1
# }
# f = function(){
# # - [ ] comment_f1
# # another non match to pattern
# g()+1
# }
# populate R souce file
writeLines(script_body, "test.R")
# test it
source("test.R")
f()
# [1] 2
# expected output
r = magic_function_get_comments("test.R", starts.with = c(" - [x] "," - [ ] "))
# r = list("g" = c(" - [x] comment_g1"," - [ ] comment_g2"), "f" = " - [ ] comment_f1")
str(r)
# List of 2
# $ g: chr [1:2] " - [x] comment_g1" " - [ ] comment_g2"
# $ f: chr " - [ ] comment_f1"