Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: MarkdownFormatter#AbstractObjectFormatter #536

Merged
merged 1 commit into from
Jul 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ object KitUtils {
}
}

fun <T> Boolean?.or(whenTrue: T, whenFalse: T): T {
return when (this) {
true -> whenTrue
else -> whenFalse
}
}

fun Any?.toJson(): String? {
if (this == null) {
return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,10 @@ class KitUtilsTest {
assertTrue("cbA".equalIgnoreCase("CBa"))
}

@Test
fun testBoolOr() {
assertEquals("true", true.or("true", "false"))
assertEquals("false", false.or("true", "false"))
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ import com.itangcent.common.logger.traceError
import com.itangcent.common.model.Doc
import com.itangcent.idea.plugin.Worker
import com.itangcent.idea.plugin.api.export.core.ClassExporter
import com.itangcent.idea.plugin.settings.SettingBinder
import com.itangcent.idea.plugin.settings.helper.MarkdownSettingsHelper
import com.itangcent.idea.utils.Charsets
import com.itangcent.idea.swing.MessagesHelper
import com.itangcent.idea.utils.FileSaveHelper
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.logger.Logger
Expand All @@ -37,69 +36,73 @@ class MarkdownApiExporter {
@Inject
private val markdownFormatter: MarkdownFormatter? = null

@Inject
private lateinit var messagesHelper: MessagesHelper

@Inject
private lateinit var markdownSettingsHelper: MarkdownSettingsHelper

fun export() {

logger!!.info("Start find apis...")
val docs: MutableList<Doc> = Collections.synchronizedList(ArrayList<Doc>())
val docs: MutableList<Doc> = Collections.synchronizedList(ArrayList())

SelectedHelper.Builder()
.dirFilter { dir, callBack ->
actionContext!!.runInSwingUI {
try {
val project = actionContext.instance(Project::class)
val yes = Messages.showYesNoDialog(project,
"Export the api in directory [${ActionUtils.findCurrentPath(dir)}]?",
"Please Confirm",
Messages.getQuestionIcon())
if (yes == Messages.YES) {
callBack(true)
} else {
logger.debug("Cancel the operation export api from [${ActionUtils.findCurrentPath(dir)}]!")
callBack(false)
}
} catch (e: Exception) {
.dirFilter { dir, callBack ->
actionContext!!.runInSwingUI {
try {
val yes = messagesHelper.showYesNoDialog(
"Export the api in directory [${ActionUtils.findCurrentPath(dir)}]?",
"Please Confirm",
Messages.getQuestionIcon()
)
if (yes == Messages.YES) {
callBack(true)
} else {
logger.debug("Cancel the operation export api from [${ActionUtils.findCurrentPath(dir)}]!")
callBack(false)
}
} catch (e: Exception) {
logger.traceError("failed show dialog", e)
callBack(false)
}
}
.fileFilter { file -> FileType.acceptable(file.name) }
.classHandle {
actionContext!!.checkStatus()
classExporter!!.export(it) { doc -> docs.add(doc) }
}
.onCompleted {
try {
if (classExporter is Worker) {
classExporter.waitCompleted()
}
if (docs.isEmpty()) {
logger.info("No api be found to export!")
return@onCompleted
}
logger.info("Start parse apis")
val apiInfo = markdownFormatter!!.parseRequests(docs)
docs.clear()
actionContext!!.runAsync {
try {
fileSaveHelper!!.saveOrCopy(apiInfo, markdownSettingsHelper.outputCharset(), {
logger.info("Exported data are copied to clipboard,you can paste to a md file now")
}, {
logger.info("Apis save success: $it")
}) {
logger.info("Apis save failed")
}
} catch (e: Exception) {
logger.traceError("Apis save failed", e)
}
.fileFilter { file -> FileType.acceptable(file.name) }
.classHandle {
actionContext!!.checkStatus()
classExporter!!.export(it) { doc -> docs.add(doc) }
}
.onCompleted {
try {
if (classExporter is Worker) {
classExporter.waitCompleted()
}
if (docs.isEmpty()) {
logger.info("No api be found to export!")
return@onCompleted
}
logger.info("Start parse apis")
val apiInfo = markdownFormatter!!.parseRequests(docs)
docs.clear()
actionContext!!.runAsync {
try {
fileSaveHelper!!.saveOrCopy(apiInfo, markdownSettingsHelper.outputCharset(), {
logger.info("Exported data are copied to clipboard,you can paste to a md file now")
}, {
logger.info("Apis save success: $it")
}) {
logger.info("Apis save failed")
}
} catch (e: Exception) {
logger.traceError("Apis save failed", e)
}
} catch (e: Exception) {
logger.traceError("Apis save failed", e)

}
} catch (e: Exception) {
logger.traceError("Apis save failed", e)

}
.traversal()
}
.traversal()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import com.intellij.psi.PsiClass
import com.itangcent.common.constant.Attrs
import com.itangcent.common.kit.KVUtils
import com.itangcent.common.kit.KitUtils
import com.itangcent.common.kit.or
import com.itangcent.common.model.Doc
import com.itangcent.common.model.MethodDoc
import com.itangcent.common.model.Request
Expand Down Expand Up @@ -72,10 +73,10 @@ class MarkdownFormatter {
requests.forEach { request ->
val module = request.resource?.let { moduleHelper!!.findModule(it) } ?: "easy-api"
moduleGroupedMap.safeComputeIfAbsent(module) { ArrayList() }!!
.add(request)
.add(request)
}

moduleGroupedMap.forEach { module, requestsInModule ->
moduleGroupedMap.forEach { (module, requestsInModule) ->
moduleFolderApiMap[module] = parseRequestsToFolder(requestsInModule)
}

Expand All @@ -99,12 +100,12 @@ class MarkdownFormatter {

val modules: ArrayList<HashMap<String, Any?>> = ArrayList()
moduleFolderApiMap.entries
.map { moduleAndFolders ->
val items: ArrayList<HashMap<String, Any?>> = ArrayList()
moduleAndFolders.value.forEach { items.add(wrapInfo(it.key, it.value)) }
return@map wrapInfo(moduleAndFolders.key, items)
}
.forEach { modules.add(it) }
.map { moduleAndFolders ->
val items: ArrayList<HashMap<String, Any?>> = ArrayList()
moduleAndFolders.value.forEach { items.add(wrapInfo(it.key, it.value)) }
return@map wrapInfo(moduleAndFolders.key, items)
}
.forEach { modules.add(it) }

val rootModule = moduleHelper!!.findModuleByPath(ActionUtils.findCurrentPath()) ?: "easy-api"
return wrapInfo(rootModule, modules)
Expand All @@ -121,7 +122,7 @@ class MarkdownFormatter {
requests.forEach { request ->
val folder = formatFolderHelper!!.resolveFolder(request.resource ?: PostmanFormatter.NULL_RESOURCE)
folderGroupedMap.safeComputeIfAbsent(folder) { ArrayList() }!!
.add(request)
.add(request)
}

return folderGroupedMap
Expand All @@ -145,11 +146,11 @@ class MarkdownFormatter {
handle("\n\n")
}
(info[ITEMS] as List<*>)
.filterNotNull()
.forEach {
parseApi(it, deep + 1, handle)
handle("\n\n")
}
.filterNotNull()
.forEach {
parseApi(it, deep + 1, handle)
handle("\n\n")
}
}

private fun parseMethodDoc(methodDoc: MethodDoc, deep: Int, handle: (String) -> Unit) {
Expand Down Expand Up @@ -211,8 +212,8 @@ class MarkdownFormatter {
handle("| ------------ | ------------ | ------------ |\n")
request.paths!!.forEach {
handle(
"| ${it.name} | ${it.value ?: ""} |" +
" ${escape(it.desc)} |\n"
"| ${it.name} | ${it.value ?: ""} |" +
" ${escape(it.desc)} |\n"
)
}
}
Expand All @@ -224,10 +225,12 @@ class MarkdownFormatter {
handle("| ------------ | ------------ | ------------ | ------------ |\n")
request.headers!!.forEach {
handle(
"| ${it.name} | ${it.value ?: ""} | ${
KitUtils.fromBool(it.required
?: false, "YES", "NO")
} | ${escape(it.desc)} |\n"
"| ${it.name} | ${it.value ?: ""} | ${
KitUtils.fromBool(
it.required
?: false, "YES", "NO"
)
} | ${escape(it.desc)} |\n"
)
}
}
Expand All @@ -239,8 +242,8 @@ class MarkdownFormatter {
handle("| ------------ | ------------ | ------------ | ------------ |\n")
request.querys!!.forEach {
handle(
"| ${it.name} | ${it.value ?: ""} | ${KitUtils.fromBool(it.required ?: false, "YES", "NO")} |" +
" ${escape(it.desc)} |\n"
"| ${it.name} | ${it.value ?: ""} | ${KitUtils.fromBool(it.required ?: false, "YES", "NO")} |" +
" ${escape(it.desc)} |\n"
)
}
}
Expand All @@ -263,8 +266,8 @@ class MarkdownFormatter {
handle("| ------------ | ------------ | ------------ | ------------ | ------------ |\n")
request.formParams!!.forEach {
handle(
"| ${it.name} | ${it.value ?: ""} | ${KitUtils.fromBool(it.required ?: false, "YES", "NO")} |" +
" ${it.type} | ${escape(it.desc)} |\n"
"| ${it.name} | ${it.value ?: ""} | ${KitUtils.fromBool(it.required ?: false, "YES", "NO")} |" +
" ${it.type} | ${escape(it.desc)} |\n"
)
}
}
Expand All @@ -281,12 +284,9 @@ class MarkdownFormatter {
handle("| ------------ | ------------ | ------------ | ------------ | ------------ |\n")
response.headers!!.forEach {
handle(
"| ${it.name} | ${it.value ?: ""} | ${
KitUtils.fromBool(
it.required
?: false, "YES", "NO"
)
} | ${escape(it.desc)} |\n"
"| ${it.name} | ${it.value ?: ""} | ${
it.required.or("YES", "NO")
} | ${escape(it.desc)} |\n"
)
}

Expand Down Expand Up @@ -384,6 +384,11 @@ private interface ObjectFormatter {

private abstract class AbstractObjectFormatter(val handle: (String) -> Unit) : ObjectFormatter {

/**
* -1: always writeHeader, -> -1
* 0: writeHeader once, -> 1
* >0: not writeHeader
*/
private var inStream = -1

override fun writeObject(obj: Any?, name: String, desc: String) {
Expand Down Expand Up @@ -429,7 +434,7 @@ private abstract class AbstractObjectFormatter(val handle: (String) -> Unit) : O
inStream = 0
try {
action(this)
} catch (e: Throwable) {
} finally {
inStream = -1
}
}
Expand Down Expand Up @@ -493,8 +498,8 @@ private class SimpleObjectFormatter(handle: (String) -> Unit) : AbstractObjectFo
} catch (e: Throwable) {
}
obj.forEachValid { k, v ->
val propertyDesc: String? = KVUtils.getUltimateComment(comment, k)
writeBody(v, k.toString(), propertyDesc ?: "", deep + 1)
val propertyDesc = KVUtils.getUltimateComment(comment, k)
writeBody(v, k.toString(), propertyDesc, deep + 1)
}
} else {
addBodyProperty(deep, name, "object", desc)
Expand Down Expand Up @@ -560,11 +565,13 @@ private class UltimateObjectFormatter(handle: (String) -> Unit) : AbstractObject
obj.forEachValid { k, v ->
val key = k.toString()
val propertyDesc: String? = KVUtils.getUltimateComment(comments, k)
writeBody(v, key,
requireds?.get(key) as? Boolean,
defaults?.get(key) as? String,
propertyDesc ?: "",
deep + 1)
writeBody(
v, key,
requireds?.get(key) as? Boolean,
defaults?.get(key) as? String,
propertyDesc ?: "",
deep + 1
)
}
} else {
addBodyProperty(deep, name, "object", required, default, desc)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ enum class FileType(private val suffix: String) {

fun acceptable(fileName: String): Boolean {
if (fileName.endsWith("scala")) {
ActionContext.instance(TipsHelper::class).showTips(SUPPORT_SUPPORT_TIP)
ActionContext.getContext()?.instance(TipsHelper::class)?.showTips(SUPPORT_SUPPORT_TIP)
}
return values().any { fileName.endsWith(it.suffix()) }
}
Expand Down
Loading