package io.gitlab.jfronny.woodpecker.include; import com.amihaiemil.eoyaml.*; import io.gitlab.jfronny.commons.HttpUtils; import io.gitlab.jfronny.commons.log.Logger; import io.gitlab.jfronny.commons.serialize.Serializer; import io.gitlab.jfronny.commons.serialize.gson.api.v1.GsonHolders; import io.gitlab.jfronny.woodpecker.include.model.*; import io.gitlab.jfronny.woodpecker.include.util.YamlTypeAdapter; import net.freeutils.httpserver.HTTPServer; import java.io.*; import java.util.concurrent.atomic.AtomicBoolean; public class Main { public static final Logger LOG = Logger.forName("Woodpecker-Include"); public static void main(String[] args) throws IOException { if (args.length != 1) { LOG.error("Usage: woodpecker-include "); return; } HTTPServer server = new HTTPServer(Integer.parseInt(args[0])); HTTPServer.VirtualHost host = server.getVirtualHost(null); GsonHolders.registerSerializer(); GsonHolders.registerTypeAdapter(YamlMapping.class, new YamlTypeAdapter()); HttpUtils.setUserAgent("Woodpecker-Include/1.0"); host.addContext("/ciconfig", (req, resp) -> { Ref ref = new Ref(); try { try { return processRequest(req, resp, ref); } catch (UncheckedIOException e) { throw e.getCause(); } } catch (Throwable e) { if (ref.name == null) LOG.info("Could not process pipeline", e); else LOG.info("Could not process pipeline for " + ref.name, e); throw e; } }, "POST"); server.start(); LOG.info("Running Woodpecker-Include"); } private static int processRequest(HTTPServer.Request req, HTTPServer.Response resp, Ref ref) throws IOException { RequestModel request; try (var is = req.getBody()) { String body = new String(is.readAllBytes()); request = Serializer.getInstance().deserialize(body, RequestModel.class); } ref.name = request.repo.full_name; AtomicBoolean changed = new AtomicBoolean(false); ResponseModel response = new ResponseModel(request.configs.stream().mapMulti(new PipelineUnpacker(changed)).toList()); if (changed.get()) { resp.sendHeaders(200); try (OutputStreamWriter writer = new OutputStreamWriter(resp.getBody())) { Serializer.getInstance().serialize(response, writer); } LOG.info("Processed includes for pipeline for " + ref.name); } else { resp.sendHeaders(204); } return 0; } private static class Ref { public String name; } }