Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class HaskellServantCodegen extends DefaultCodegen implements CodegenConfig {
private final Logger LOGGER = LoggerFactory.getLogger(HaskellServantCodegen.class);
// source folder where to write the files
protected String sourceFolder = "src";
protected String apiVersion = "0.0.1";
private static final Pattern LEADING_UNDERSCORE = Pattern.compile("^_+");
public static final String PROP_SERVE_STATIC = "serveStatic";
public static final String PROP_SERVE_STATIC_DESC = "serve will serve files from the directory 'static'.";
public static final Boolean PROP_SERVE_STATIC_DEFAULT = Boolean.TRUE;
public static final String USE_CUSTOM_MONAD = "useCustomMonad";
public static final String USE_CUSTOM_MONAD_DESC = "use a custom monad instead of the default Handler";
public static final Boolean USE_CUSTOM_MONAD_DEFAULT = Boolean.FALSE;
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
*/
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "haskell";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Haskell server and client library.";
}
public HaskellServantCodegen() {
super();
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML))
.securityFeatures(EnumSet.of(
SecurityFeature.BasicAuth,
SecurityFeature.BearerToken,
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism
)
.includeParameterFeatures(
ParameterFeature.Cookie
)
);
// override the mapping to keep the original mapping in Haskell
specialCharReplacements.put("-", "Dash");
specialCharReplacements.put(">", "GreaterThan");
specialCharReplacements.put("<", "LessThan");
// set the output folder here
outputFolder = "generated-code/haskell-servant";
/*
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "haskell-servant";
/*
* Api Package. Optional, if needed, this can be used in templates
*/
apiPackage = "API";
/*
* Model Package. Optional, if needed, this can be used in templates
*/
modelPackage = "Types";
// Haskell keywords and reserved function names, taken mostly from https://wiki.haskell.org/Keywords
setReservedWordsLowerCase(
Arrays.asList(
// Keywords
"as", "case", "of",
"class", "data", "family",
"default", "deriving",
"do", "forall", "foreign", "hiding",
"if", "then", "else",
"import", "infix", "infixl", "infixr",
"instance", "let", "in",
"mdo", "module", "newtype",
"proc", "qualified", "rec",
"type", "where"
)
);
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
/*
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("stack.mustache", "", "stack.yaml"));
supportingFiles.add(new SupportingFile("Setup.mustache", "", "Setup.hs"));
/*
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = new HashSet<>(
Arrays.asList(
"Bool",
"String",
"Int",
"Integer",
"Float",
"Char",
"Double",
"List",
"FilePath"
)
);
typeMapping.clear();
typeMapping.put("array", "List");
typeMapping.put("set", "Set");
typeMapping.put("boolean", "Bool");
typeMapping.put("string", "Text");
typeMapping.put("integer", "Int");
typeMapping.put("long", "Integer");
typeMapping.put("short", "Int");
typeMapping.put("char", "Char");
typeMapping.put("float", "Float");
typeMapping.put("double", "Double");
typeMapping.put("DateTime", "UTCTime");
typeMapping.put("Date", "Day");
typeMapping.put("file", "FilePath");
typeMapping.put("binary", "FilePath");
typeMapping.put("number", "Double");
typeMapping.put("BigDecimal", "Double");
typeMapping.put("any", "Value");
typeMapping.put("AnyType", "Value");
typeMapping.put("UUID", "UUID");
typeMapping.put("URI", "Text");
typeMapping.put("ByteArray", "Text");
typeMapping.put("object", "Value");
importMapping.clear();
importMapping.put("Map", "qualified Data.Map as Map");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(new CliOption(PROP_SERVE_STATIC, PROP_SERVE_STATIC_DESC).defaultValue(PROP_SERVE_STATIC_DEFAULT.toString()));
cliOptions.add(new CliOption(USE_CUSTOM_MONAD, USE_CUSTOM_MONAD_DESC).defaultValue(USE_CUSTOM_MONAD_DEFAULT.toString()));
}
public void setBooleanProperty(String property, Boolean defaultValue) {
if (additionalProperties.containsKey(property)) {
additionalProperties.put(property, convertPropertyToBoolean(property));
} else {
additionalProperties.put(property, defaultValue);
}
}
@Override
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("HASKELL_POST_PROCESS_FILE"))) {
LOGGER.info("Hint: Environment variable HASKELL_POST_PROCESS_FILE not defined so the Haskell code may not be properly formatted. To define it, try 'export HASKELL_POST_PROCESS_FILE=\"$HOME/.local/bin/hfmt -w\"' (Linux/Mac)");
}
setBooleanProperty(PROP_SERVE_STATIC, PROP_SERVE_STATIC_DEFAULT);
setBooleanProperty(USE_CUSTOM_MONAD, USE_CUSTOM_MONAD_DEFAULT);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
public String firstLetterToUpper(String word) {
if (word.length() == 0) {
return word;
} else if (word.length() == 1) {
return word.substring(0, 1).toUpperCase(Locale.ROOT);
} else {
return word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1);
}
}
public String firstLetterToLower(String word) {
if (word.length() == 0) {
return word;
} else if (word.length() == 1) {
return word.substring(0, 1).toLowerCase(Locale.ROOT);
} else {
return word.substring(0, 1).toLowerCase(Locale.ROOT) + word.substring(1);
}
}
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
// From the title, compute a reasonable name for the package and the API
String title = openAPI.getInfo().getTitle();
// Drop any API suffix
if (title == null) {
title = "OpenAPI";
} else {
title = title.trim();
if (title.toUpperCase(Locale.ROOT).endsWith("API")) {
title = title.substring(0, title.length() - 3);
}
}
String[] words = title.split(" ");
// The package name is made by appending the lowercased words of the title interspersed with dashes
List wordsLower = new ArrayList<>();
for (String word : words) {
wordsLower.add(word.toLowerCase(Locale.ROOT));
}
String cabalName = joinStrings("-", wordsLower);
// The API name is made by appending the capitalized words of the title
List wordsCaps = new ArrayList<>();
for (String word : words) {
wordsCaps.add(firstLetterToUpper(word));
}
String apiName = joinStrings("", wordsCaps);
// Set the filenames to write for the API
supportingFiles.add(new SupportingFile("haskell-servant-codegen.mustache", "", cabalName + ".cabal"));
supportingFiles.add(new SupportingFile("API.mustache", "lib/" + apiName, "API.hs"));
supportingFiles.add(new SupportingFile("Types.mustache", "lib/" + apiName, "Types.hs"));
additionalProperties.put("title", apiName);
additionalProperties.put("titleLower", firstLetterToLower(apiName));
additionalProperties.put("package", cabalName);
// Due to the way servant resolves types, we need a high context stack limit
additionalProperties.put("contextStackLimit", openAPI.getPaths().size() * 2 + 300);
List