func()

in tools/commentMonitor/main.go [109:217]


func (c *commentMonitorConfig) webhookExtract(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	// Load config on every request.
	err := c.loadConfig()
	if err != nil {
		log.Println(err)
		http.Error(w, "comment-monitor configuration incorrect", http.StatusInternalServerError)
		return
	}

	// Validate payload.
	payload, err := github.ValidatePayload(r, c.whSecret)
	if err != nil {
		log.Println(err)
		http.Error(w, "unable to read webhook body", http.StatusBadRequest)
		return
	}

	// Setup commentMonitor client.
	cmClient := commentMonitorClient{
		allArgs:  make(map[string]string),
		events:   c.configFile.WebhookEvents,
		prefixes: c.configFile.Prefixes,
	}

	// Parse webhook event.
	event, err := github.ParseWebHook(github.WebHookType(r), payload)
	if err != nil {
		log.Println(err)
		http.Error(w, "unable to parse webhook", http.StatusBadRequest)
		return
	}

	switch e := event.(type) {
	case *github.IssueCommentEvent:

		if *e.Action != "created" {
			http.Error(w, "issue_comment type must be 'created'", http.StatusOK)
			return
		}

		// Setup github client.
		ctx := context.Background()
		cmClient.ghClient, err = newGithubClient(ctx, e)
		if err != nil {
			log.Println(err)
			http.Error(w, "could not create GitHub client", http.StatusBadRequest)
			return
		}

		// Strip whitespace.
		command := extractCommand(cmClient.ghClient.commentBody)

		// Command check.
		if !cmClient.checkCommandPrefix(command) {
			http.Error(w, "comment validation failed", http.StatusOK)
			return
		}

		// Validate regex.
		if !cmClient.validateRegex(command) {
			log.Println("invalid command syntax: ", command)
			err = cmClient.generateAndPostErrorComment()
			if err != nil {
				log.Println(err)
				http.Error(w, "could not post comment to GitHub", http.StatusBadRequest)
				return
			}
			http.Error(w, "command syntax invalid", http.StatusBadRequest)
			return
		}

		// Verify user.
		err = cmClient.verifyUser()
		if err != nil {
			log.Println(err)
			http.Error(w, "user not allowed to run command", http.StatusForbidden)
			return
		}

		// Extract args.
		err = cmClient.extractArgs(command)
		if err != nil {
			log.Println(err)
			http.Error(w, "could not extract arguments", http.StatusBadRequest)
			return
		}

		// Post generated comment to GitHub pr.
		err = cmClient.generateAndPostSuccessComment()
		if err != nil {
			log.Println(err)
			http.Error(w, "could not post comment to GitHub", http.StatusBadRequest)
			return
		}

		// Set label to GitHub pr.
		err = cmClient.postLabel()
		if err != nil {
			log.Println(err)
			http.Error(w, "could not set label to GitHub", http.StatusBadRequest)
			return
		}

	default:
		log.Println("only issue_comment event is supported")
	}
}