<commit_before>(ns ci3.server
  (:require
   [clojure.string :as str]
   [org.httpkit.server :as http-kit]
   [org.httpkit.client :as http-client]
   [clojure.tools.logging :as log]
   [clojure.java.shell :as sh]
   [cheshire.core :as json]
   [ci3.k8s :as k8s]
   [pandect.algo.sha1 :refer [sha1-hmac]]
   [route-map.core :as route-map]
   [ring.util.codec]))

(defonce server (atom nil))

(defn exec [& args]
  (log/info "Execute: " args)
  (let [res (apply sh/sh args)]
    (log/info "Result: " res)
    res))

(defn process-keys [res]
  (reduce (fn [acc [k v]]
            (let [pth (mapv keyword (str/split k #"\."))]
              (assoc-in acc pth v)))
          {} (get res "data")))

(defn repo-key [h]
  (fn [req]
    (let [repo-key (str/replace (:uri req) #"^/" "")]
      (if (str/blank? repo-key)
        {:body (str "Hi, i'm zeroci please use /repo-key path to trigger")}
        (h (assoc req :repo-key repo-key :log []))))))

(defn get-repositories [h]
  (fn [req]
    (if-let [rs (let [res (exec "kubectl" "get" "configmaps" "repositories" "-o" "json")]
                  (log/info "Repositories" res)
                  (process-keys (json/parse-string (:out res))))]
      (h (assoc req :repositories rs))
      {:body (str "Could not get repositories configmap") :status 500})))

(defn get-config [h]
  (fn [{rk :repo-key rs :repositories :as req}]
    (if-let [cfg (get rs (keyword rk))]
      (h (assoc req :config cfg))
      {:body (str "Could not get config for " rk) :status 500})))

(defn verify
  [{headers :headers body :body :as req}]
  (let [signature (get headers "x-hub-signature")
        payload (slurp body)
        hash (str "sha1=" (sha1-hmac payload "secret")) ]
    (if (= signature hash)
      (json/parse-string payload keyword)
      {:status 401 })))


(def cfg {:apiVersion "ci3.io/v1" :ns "default"})


(defn cleanup [s]
  (-> s
      (str/replace  #"\/" "-")
      (str/replace  #"\_" "-")
      (str/replace  #"\:" "-")))

(defn create-build [payload]
  (let [repository (:repository payload)
        commit (last (:commits payload))
        hashcommit (:id commit)
        build-name (cleanup (str (:full_name repository) "-" hashcommit)) ]
    {:body (k8s/create cfg :builds
                       {:kind "Build"
                        :apiVersion "ci3.io/v1"
                        :metadata {:name  hashcommit}
                        :payload {:ref (:ref payload)
                                  :diff (:compare payload)
                                  :repository (select-keys repository
                                                           [:name :organization :full_name
                                                            :url :html_url :git_url :ssh_url
                                                            ]
                                                           )
                                  :commit (select-keys commit
                                                       [:id :message :timestamp
                                                        :url :author ])
                                 } })}))

(defn webhook [req]<commit_msg>build name<commit_after>(ns ci3.server
  (:require
   [clojure.string :as str]
   [org.httpkit.server :as http-kit]
   [org.httpkit.client :as http-client]
   [clojure.tools.logging :as log]
   [clojure.java.shell :as sh]
   [cheshire.core :as json]
   [ci3.k8s :as k8s]
   [pandect.algo.sha1 :refer [sha1-hmac]]
   [route-map.core :as route-map]
   [ring.util.codec]))

(defonce server (atom nil))

(defn exec [& args]
  (log/info "Execute: " args)
  (let [res (apply sh/sh args)]
    (log/info "Result: " res)
    res))

(defn process-keys [res]
  (reduce (fn [acc [k v]]
            (let [pth (mapv keyword (str/split k #"\."))]
              (assoc-in acc pth v)))
          {} (get res "data")))

(defn repo-key [h]
  (fn [req]
    (let [repo-key (str/replace (:uri req) #"^/" "")]
      (if (str/blank? repo-key)
        {:body (str "Hi, i'm zeroci please use /repo-key path to trigger")}
        (h (assoc req :repo-key repo-key :log []))))))

(defn get-repositories [h]
  (fn [req]
    (if-let [rs (let [res (exec "kubectl" "get" "configmaps" "repositories" "-o" "json")]
                  (log/info "Repositories" res)
                  (process-keys (json/parse-string (:out res))))]
      (h (assoc req :repositories rs))
      {:body (str "Could not get repositories configmap") :status 500})))

(defn get-config [h]
  (fn [{rk :repo-key rs :repositories :as req}]
    (if-let [cfg (get rs (keyword rk))]
      (h (assoc req :config cfg))
      {:body (str "Could not get config for " rk) :status 500})))

(defn verify
  [{headers :headers body :body :as req}]
  (let [signature (get headers "x-hub-signature")
        payload (slurp body)
        hash (str "sha1=" (sha1-hmac payload "secret")) ]
    (if (= signature hash)
      (json/parse-string payload keyword)
      {:status 401 })))


(def cfg {:apiVersion "ci3.io/v1" :ns "default"})


(defn cleanup [s]
  (-> s
      (str/replace  #"\/" "-")
      (str/replace  #"\_" "-")
      (str/replace  #"\:" "-")))

(defn create-build [payload]
  (let [repository (:repository payload)
        commit (last (:commits payload))
        hashcommit (:id commit)
        build-name (cleanup (str (:full_name repository) "-" hashcommit)) ]
    {:body (k8s/create cfg :builds
                       {:kind "Build"
                        :apiVersion "ci3.io/v1"
                        :metadata {:name  build-name}
                        :payload {:ref (:ref payload)
                                  :diff (:compare payload)
                                  :repository (select-keys repository
                                                           [:name :organization :full_name
                                                            :url :html_url :git_url :ssh_url
                                                            ]
                                                           )
                                  :commit (select-keys commit
                                                       [:id :message :timestamp
                                                        :url :author ])
                                 } })}))

(defn webhook [req]
{'fraction_non_alphanumeric': 0.14763497372193024, 'fraction_numerical': 0.007007485268354834, 'mean_word_length': 1.5373737373737373, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3697649', 'n_tokens_mistral': 1998, 'n_tokens_neox': 1911, 'n_words': 542}