Skip to content

Commit

Permalink
Package structure
Browse files Browse the repository at this point in the history
  • Loading branch information
estedeahora committed Mar 21, 2024
1 parent e8dd03f commit 4da18db
Show file tree
Hide file tree
Showing 114 changed files with 7,110 additions and 623 deletions.
2 changes: 2 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
^guri\.Rproj$
^\.Rproj\.user$
18 changes: 18 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Package: guri
Title: ~!gurí_: Unified Format Manager for Research Journals
Version: 1.0.0
Authors@R:
person("Pablo Santiago", "Serrati", , "pabloserrati@gmail.com", role = c("aut", "cre"),
comment = c(ORCID = "0000-0001-5300-2243"))
Description: ~gurí_ (Gestor Unificado de formatos para Revistas de Investigación / Unified Format Manager for Research Journals) facilitates the generation of final documents for scientific journals from documents obtained in the 'proofreading' stage. The proposal seeks to solve the difficulties of some academic journals in generating final documents in different formats in a consistent way and without generating duplicated processes. It also takes into account that many scientific journals use docx documents as the basis of their workflows.
License: CC BY-NC-SA 4.0 + file LICENSE
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.3.1
Imports:
cli,
pandoc,
readxl,
rmarkdown,
stringr,
tinytex
437 changes: 437 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Generated by roxygen2: do not edit by hand

export(GURI_make_journal)
importFrom(cli,cli_alert_info)
importFrom(cli,cli_alert_success)
importFrom(cli,cli_process_done)
importFrom(cli,cli_process_start)
68 changes: 68 additions & 0 deletions R/GURI.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

# GURI() ----------------------------------------------------

GURI <- function(art_path, art_name, verbose = F,
zip_file = F, clean_files = T){

pandoc_req <- "3.1.10"
if(!pandoc_version() >= pandoc_req){
stop("Necesita actualizar su versión de Pandoc (se requiere ",
pandoc_req, " o posterior). Descargue la última versión",
"en el sitio de Pandoc: https://github.com/jgm/pandoc/releases/latest")
}

# Preprar archivos
cat("Artículo:", "\033[34m", art_name, "\033[39m", "\n")
cat("\033[33m", "* Preparación de archivos.", "\033[39m")
GURI_prepare(art_path, art_name)
cat("DONE\n")

# Convert files
# docx -> md
cat("\033[33m", "* Crear archivo markdown (", art_name, ".md ).", "\033[39m")
GURI_to_md(art_path, art_name, verbose = verbose)
cat("DONE\n")
# docx -> biblio
cat("\033[33m", "* Crear archivo de bibliografía (", art_name, "_biblio).", "\033[39m")
GURI_biblio(art_path, art_name)
cat("DONE\n")
# md -> AST
cat("\033[33m", "* Crear AST (", art_name, "_AST.json ).", "\033[39m")
GURI_to_AST(art_path, art_name)
cat("DONE\n")
# md -> jats
cat("\033[33m", "* Crear archivo jats-xml (", art_name, ".xml ).", "\033[39m")
GURI_to_jats(art_path, art_name)
cat("DONE\n")
# md -> html
cat("\033[33m", "* Crear archivo html (", art_name, ".html ).", "\033[39m")
GURI_to_html(art_path, art_name)
cat("DONE\n")
# md -> tex + pdf
cat("\033[33m", "* Crear archivo latex (", art_name, ".tex ).",
"y pdf (", art_name, "pdf ).", "\033[39m")
GURI_to_pdf(art_path, art_name, verbose = verbose)
cat("DONE\n")

# File reorganization
wd_orig <- getwd()
setwd(art_path)

# Zip file
if(zip_file){
cat("\033[33m", "* Crear zip con archivos usados como entrada", "\033[39m")
GURI_zip_input(art_name)
cat("DONE\n")
}
# Clean files
if(clean_files){
cat("\033[33m", "* Mover archivos temporales a './_temp/'", "\033[39m")
GURI_clean_temp(art_name)
cat("DONE\n")
cat("\033[33m", "* Mover archivos finales a './_output/'", "\033[39m")
GURI_output(art_name)
cat("DONE\n")
}
setwd(wd_orig)
}

20 changes: 20 additions & 0 deletions R/GURI_appendix.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# GURI_appendix() ------------------------------------------
# Transformación de archivos de anexos docx -> md
# Devuelve el listado de archivos para anexos

GURI_appendix <- function(wdir, art){
appendix_files <- list.files(wdir, pattern = paste0(art, "_app[0-9]*\\.docx"))

walk(appendix_files,
\(file){
pandoc_convert(wd = wdir,
input = file,
from = "docx+citations",
output = str_replace(file, "docx", "md") ,
citeproc = T,
to = "markdown")}
)

return(str_replace(appendix_files, "docx", "md"))
}

25 changes: 25 additions & 0 deletions R/GURI_example.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#' Crear revista de ejemplo
#'
#' @export

GURI_example <- function(){

journal <- "example"
GURI_make_journal(journal = journal)

example_folder <- pkg_file(journal)
file.copy(from = file.path(example_folder, "num1"),
to = file.path(".", journal), recursive = T,
overwrite = T)
cli_alert_success(paste0("Copy example journal issue ({.path ./example/num1/})."))

file.copy(from = file.path(example_folder, "_journal.yaml"),
to = file.path(".", journal, "_journal.yaml"), overwrite = T)

cli_alert_success("Copy {.path ./_journal.yaml} file.")

cli_alert_info("Ejecute GRUI_output_issue('num1', journal = 'example') para generar los archivos finales de esta revista de ejemplo")
invisible(T)

}

75 changes: 75 additions & 0 deletions R/GURI_install.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#' Updates/installs the external dependencies necessary for working `~!guri_`.
#'
#' @description
#' Upgrade or install (as necessary) pandoc, as well as the latex distribution
#' (tinytex) and latex packages.
#'
#' @param pandoc Logical. Should pandoc be installed/updated? (default 'TRUE')
#' @param tinytex Logical. Should tinytex be installed/updated? (default 'TRUE')
#' @param force Logical. Should pandoc and tinytex be forced to reinstall? (default 'FALSE')
#'
#' @return Invisible. A list with a logical vector indicating whether tinytex
#' and pandoc are available and two items with the installed versions of Tinitex and Pandoc.
#'
#' @export
#

GURI_install <- function(pandoc = T, tinytex = T, force = F){

if(pandoc){
pandoc::pandoc_install(force = force)
}

# Instalación de distribución tinytex y paquetes sugeridos
if(tinytex){
if(!tinytex::is_tinytex() | force){

cli_process_start("Installing latex distribution (tinytex)")
tinytex::install_tinytex()
cli_process_done()

}else{
cli_process_start("Updating the tinytex latex distribution")
tinytex::tlmgr_update()
cli_process_done()
}

latex_pkg <- c("amsmath", "amsfonts", "lm", "unicode-math", "iftex", "listings",
"fancyvrb", "booktabs", "hyperref", "xcolor", "soul", "geometry",
"setspace", "babel", "fontspec", "selnolig", "mathspec", "biblatex",
"bibtex", "upquote", "microtype", "csquotes", "natbib",
"bookmark", "xurl", "parskip", "svg", "geometry", "multirow",
"etoolbox", "luacolor", "lua-ul",
"adjustbox", "fontawesome5", "caption", "ccicons",
"relsize", "koma-script", "truncate", "lastpage")

cli_process_start("Checking necessary latex packages")
latex_pkg_installed <- lapply(latex_pkg, tinytex::check_installed) |>
as.logical()
cli_process_done()

if(sum(!latex_pkg_installed) > 0){
cli_process_start("Installing necessary latex packages")
tinytex::tlmgr_install(paste0(latex_pkg[!latex_pkg_installed], ".sty"))
cli_process_done()
}
}
invisible(list(c(tinytex = tinytex::is_tinytex(),
pandoc = pandoc::pandoc_available()),
tinytex_version = tinytex::tlmgr_version(),
pandoc_version = pandoc::pandoc_version() ))
}


# dep <- c("tidyverse", "rmarkdown", "readxl", "tinytex", "crayon")
# pkg <- .packages(all.available = TRUE)
#
# dep_needed <- dep [!dep %in% pkg]
#
# if(length(dep_needed) > 0){
# cat("\n", "Instalando paquetes R faltantes:",
# paste0(dep_needed, collapse = ", ") )
# install.packages(dep_needed)
# }else{
# cat("\n", "Paquetes R necesarios presentes")
# }
90 changes: 90 additions & 0 deletions R/GURI_make_journal.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#' Create the basic file structure for a new journal
#'
#' @description
#' Create the basic file structure for a new journal. The journal directory
#' includes a folder with the files used to configure the journal output
#' (`_config`) and a folder with the basic files you will use for the
#' production process (`default-files`). In addition, the `_journal.yaml`
#' file will be generated, which you will have to edit manually with the
#' journal data.
#'
#' @param journal A string with the short name of the journal. This 'short name' can contain only letters, numbers or a low dash (_). It should preferably be a single word.
#' @param issue_prefix A string. This prefix is used to identify the folders where each issue of your journal will be stored. For example, if you use 'num' (default) the folders where you should store the issues of your journal will be 'num1', 'num2', and so on.
#'
#' @return The journal directory with configuration and template files.
#' @export

GURI_make_journal <- function(journal, issue_prefix = "num"){

if(length(journal) != 1) {
stop("Provide a unique name for the journal.")
}

if(!stringr::str_detect(journal, "^[A-z]([A-z]|[0-9])+$")) {
stop("The journal.")
}

if(length(issue_prefix) != 1) {
stop("Provide a unique value for the 'issue_prefix'")
}

journal_folder <- file.path(".", journal)
if(dir.exists(journal_folder)){
stop("The journal name already exists. To create a new journal, choose a new journal name.")
}

dir.create(journal_folder)
cli_alert_success(paste0("Create journal folder ({.path ", journal_folder, "})."))

config_folder <- pkg_file("config-files/")
file.copy(from = paste0(config_folder, c("/_config", "/_default-files")),
to = journal_folder, recursive = T)
cli_alert_success(paste0("Copy configuration files in {.path ",
journal_folder, "/_config/}."))
cli_alert_success(paste0("Copy default files in {.path ",
journal_folder, "/_default-files/}."))



if(journal != "example"){
file.copy(from = paste0(config_folder, "/_journal.yaml"),
to = paste0(journal_folder, "/_journal.yaml"))

cli_alert_success("Copy {.path ./_journal.yaml} file.")
cli_alert_info("Edit manually {.path ./_journal.yaml} file.")

file.edit(paste0(journal_folder, "/_journal.yaml"))
}
invisible(T)
}

# TODO
# dir.create(paste0(journal_folder, "/_docs") )
# cli::cli_alert_success(paste0("Create journal documents folder (",
# journal_folder, "/_docs)."))
#
# script_path <- paste0(journal_folder, "/GURI_", journal, ".R")
# cat("* Create journal script (", paste0(script_path), ")\n", sep = "")
#
# file.copy(from = "scripts/GURI_01_make-files.R",
# to = script_path)
# iocon <- file(script_path,"r+")
# script <- readLines(iocon)
#
# # Modificar variable journal
# script <- map_chr(script,
# \(x) {str_replace(x, '^journal <- "example"',
# paste0('journal <- "', journal, '"'))})
# # Modificar variable prefix
# script <- map_chr(script,
# \(x) {str_replace(x, '^prefix <- "num"',
# paste0('prefix <- "', issue_prefix, '"'))})
# # Modificar primer issue
# script <- map_chr(script,
# \(x) {str_replace(x, '^issue <- 1',
# paste0('issue <- ', issue_first))})
#
# writeLines(script, con=iocon)
# close(iocon)
#
# file.edit(script_path)
19 changes: 19 additions & 0 deletions R/GURI_prepare.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#' GURI_prepare
#'

GURI_prepare <- function(art_path, art_pre){

# # Crear "art[~]_biblio.json" vacío si no tiene bibliografía
# biblio <- paste0(art_path, art_pre, "_biblio.json")
# if(!file.exists(biblio)){
# write_file(x = "[]", file = biblio)
# }

# Generar "art[~]_credit.csv "
credit_xlsx <- paste0(art_path, art_pre, "_credit.xlsx")
credit_csv <- paste0(art_path, art_pre, "_credit.csv")

if(file.exists(credit_xlsx)){
read_xlsx(credit_xlsx) |> write.csv(credit_csv, row.names = F, na = "")
}
}
53 changes: 53 additions & 0 deletions R/base_files.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Armado de archivos base ------------------------------

# GURI_listfiles() ----------------------------------------

GURI_listfiles <- function(path_issue){

if(!dir.exists(path_issue)){
stop("No existe el directorio ", "\033[34m", path_issue, "\033[39m", "\n",
"Cree el directorio con los artículos a maquetar.",
"Recuerde colocar una carpeta para artículo.")
}

art <- data.frame(art_path = list.dirs(path_issue, recursive = F)) |>
filter(str_detect(art_path, paste0(path_issue, "art[0-9]{3}.*"), negate = F)
) |>
mutate(#g = str_detect(art_path, paste0(path_issue, "art[0-9]{3}_*.*?/")),
art_id = str_remove(art_path, path_issue),
art_id = str_remove(art_id, "_.*$"),
art_path = paste0(art_path, "/"))

files <- map(art$art_path, ~list.files(.x, all.files = T, recursive = T)) |>
map2_df(.y = art$art_id, ~GURI_filetype(.x, .y)) |>
mutate(across(starts_with("is_"), as.logical) )

art <- cbind(art, files)

return(art)
}

# GURI_filetype() -----------------------------------------

GURI_filetype <- function(art_files, art_id){

search1 <- c(".docx", ".yaml", "_credit.xlsx", # "_biblio.json",
"_app[0-9]{2}.docx", "_notes.md")

res1 <- map_lgl(search1, ~any(str_detect(art_files, paste0(art_id, .x) ))) |>
set_names(c("is_docx", "is_yaml", "is_credit", # "is_biblio",
"is_appendix", "is_notes"))

# bib <- art_files[str_detect(art_files, paste0(art_id, "_biblio.json"))]
# print(read.delim(paste0(path_issue, bib)))

search2 <- c("float/TAB_[0-9]{2}.xlsx+", "float/FIG_[0-9]{2}.+")

res2 <- map_int(search2, ~sum(str_detect(art_files, .x ))) |>
set_names(c("float_tab", "float_fig"))

return(c(res1, res2))
}



10 changes: 10 additions & 0 deletions R/guri-package.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#' @keywords internal
"_PACKAGE"

## usethis namespace: start
#' @importFrom cli cli_alert_info
#' @importFrom cli cli_alert_success
#' @importFrom cli cli_process_done
#' @importFrom cli cli_process_start
## usethis namespace: end
NULL
Loading

0 comments on commit 4da18db

Please sign in to comment.