Import LeetCode problems from a pasted link on the site
The problem list's admin row gains a link box beside "Today's LeetCode":
POST /leetcode/import takes {url} and does what `usaco new
<leetcode-link>` does, through the same lib/leetcode.py run and "Start
<slug>" commit as the daily question, then opens the solve page. A
problem already in the repo is only opened.
leetcode.Slug reads the link as slug_of in lib/leetcode.py does: full
links with /description/ and query strings, www., no scheme, or a bare
slug. Anything else is a 400.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// Package leetcode starts LeetCode problems from the site the way `usaco
|
||||
// daily` does from the CLI. The import itself is the CLI's: lib/leetcode.py
|
||||
// daily` and `usaco new <leetcode-link>` do from the CLI. The import itself is the CLI's: lib/leetcode.py
|
||||
// in the clone writes problem.md, main.cpp, the generated driver.h and the
|
||||
// examples as tests. Rewriting its driver generator in Go would leave two
|
||||
// copies to drift apart, so the site image carries python3 to run it.
|
||||
@@ -13,8 +13,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -73,6 +75,31 @@ func (i *Importer) Daily(ctx context.Context) (string, error) {
|
||||
return out.Data.Daily.Question.Slug, nil
|
||||
}
|
||||
|
||||
var slugRe = regexp.MustCompile(`^[a-z0-9-]+$`)
|
||||
|
||||
// Slug is the problem a LeetCode link names, as slug_of in lib/leetcode.py
|
||||
// reads it: https://leetcode.com/problems/<slug>/ with anything after (the
|
||||
// /description/ and ?envType=... a copied link carries), with or without the
|
||||
// scheme, or a bare slug.
|
||||
func Slug(link string) (string, error) {
|
||||
link = strings.TrimSpace(link)
|
||||
if slugRe.MatchString(link) {
|
||||
return link, nil
|
||||
}
|
||||
if !strings.Contains(link, "://") {
|
||||
link = "https://" + link
|
||||
}
|
||||
u, err := url.Parse(link)
|
||||
if err != nil || strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") != "leetcode.com" {
|
||||
return "", errors.New("not a LeetCode problem link")
|
||||
}
|
||||
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
if len(parts) < 2 || parts[0] != "problems" || !slugRe.MatchString(parts[1]) {
|
||||
return "", errors.New("not a LeetCode problem link")
|
||||
}
|
||||
return parts[1], nil
|
||||
}
|
||||
|
||||
// Import runs `lib/leetcode.py root slug` in the clone at root, which
|
||||
// creates solving/<slug>. The script reports a failure as "Error: ..." on
|
||||
// stderr, which is what the admin is shown.
|
||||
|
||||
Reference in New Issue
Block a user