forgejo

package
v0.0.0-...-ae5926d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	StudentsTeamName = "students"
	TutorsTeamName   = "tutors"
)
View Source
const (
	AccessNone  = "none"
	AccessRead  = "read"
	AccessWrite = "write"
)

AccessNone, AccessRead, AccessWrite are the valid access levels.

View Source
const CourseRepoSpecsSettingKey = "course_repos"

CourseRepoSpecsSettingKey is the Setting key that holds the JSON array of CourseRepoSpec values. When absent or invalid the built-in defaults are used.

View Source
const ForumRepoName = "forum"

ForumRepoName is the configurable course repo used as the question forum (issues enabled, code unit disabled). Exercise labels are created only in repos with this name.

View Source
const GraderBotUsername = "testing-bot"

GraderBotUsername is the Forgejo account that writes final report commits to student repos via the Contents API. It is a non-admin local account; orchestration grants it write access on each student repo so the build/grading service can write reports with least privilege. See docs/build.md "testing-bot account".

View Source
const SourceUnknown = "unknown"

SourceUnknown is the placeholder used when a request's call site cannot be identified.

View Source
const TemplateRepoName = "template"

TemplateRepoName is the hardcoded name of the template repository that is always created in every course org and used as the template source for per-student repos.

Variables

View Source
var ErrForgejoUserMissing = errors.New("forgejo user does not exist")

ErrForgejoUserMissing reports that a user has no usable Forgejo account: either their preferred_username is unset or no account with that username exists on the Forgejo instance. Callers treat this as a retryable skip; provisioning retries once the user logs in to Forgejo.

View Source
var ErrUserNotLinked = errors.New("user has no OIDC subject linked yet")

ErrUserNotLinked reports that the user row has no OIDC subject yet. Pre-provisioned users (created via the admin API without a subject) get their subject on their first OIDC login, which is also when Dex auto-registers their Forgejo account. An empty subject therefore guarantees that no Forgejo account can exist, so provisioning short-circuits without any HTTP calls and retries after first login.

Functions

func AllCourseRepoNames

func AllCourseRepoNames(database *gorm.DB) []string

AllCourseRepoNames returns "template" plus every configurable repo name. Used by the cleanup cron to identify repos that must never be deleted.

func DefaultCourseRepoSpecsJSON

func DefaultCourseRepoSpecsJSON() string

DefaultCourseRepoSpecsJSON returns the built-in course repo specs serialised as JSON, suitable for pre-filling the settings editor.

func ForgejoUsername

func ForgejoUsername(user *db.User) string

ForgejoUsername returns the username used by the user on the Forgejo instance, sourced from the OIDC `preferred_username` claim at sign-in time. Returns "" when the user has no preferred_username, in which case they need to log in to the OIDC provider / Forgejo once with that claim populated.

func RegisterCourseAccessHooks

func RegisterCourseAccessHooks(database *gorm.DB)

RegisterCourseAccessHooks wires GORM callbacks that mirror course access grants into the Forgejo tutors team. A grant gives a staff user the same manage rights as the course owner, so the user needs write access to the course repos and a recognised role in the pre-receive hook. Both come from tutors team membership. When a grant is revoked the user is removed from the team unless a tutor slot still keeps them there.

func RegisterCourseHooks

func RegisterCourseHooks(database *gorm.DB)

func RegisterStudentHooks

func RegisterStudentHooks(database *gorm.DB)

RegisterStudentHooks wires GORM callbacks that sync Forgejo when students are added or removed. On create: creates the per-student repo (generated from template), grants write on it, grants access to shared course repos per the access config, and fills in exercise folders missing from an existing repo (rejoin after leave). On delete: revokes all collaborator access (the per-student repo is kept).

Forgejo calls run in a detached goroutine so the DB transaction is never blocked. The cron job is the safety net for failures.

func RegisterTutorHooks

func RegisterTutorHooks(database *gorm.DB)

RegisterTutorHooks wires GORM callbacks that keep Forgejo in sync with the tutors table. When a Tutor row is inserted the hook grants the tutor access to each course repo according to the course_repos access configuration. When deleted, all access is revoked unless a course access grant still keeps the user in the tutors team.

func RepairAllUsers

func RepairAllUsers(ctx context.Context, database *gorm.DB) error

RepairAllUsers runs RepairUserRepos for every user holding an enrollment (students and tutors) or a course access grant. Users without a Forgejo account are skipped with a log line; other errors are logged and do not abort the remaining users. Used by the forgejo-user-repair admin task.

func RepairUserRepos

func RepairUserRepos(ctx context.Context, database *gorm.DB, userID string) (bool, error)

RepairUserRepos repairs every Forgejo resource for all of a user's enrollments (students and tutors rows) and course access grants. It is the routine behind the per-user repair endpoint. The user and their enrollments are loaded fresh from the given database handle, so the caller can pass the base *gorm.DB from a detached goroutine.

The first return value reports whether any repair work ran: it is false when the user holds no enrollment and no course access grant, which lets callers keep the cooldown stamp unset in that case. A user with no OIDC subject yet (pre-provisioned, awaiting first login) or a missing Forgejo account aborts the repair with ErrUserNotLinked or ErrForgejoUserMissing: nothing can be provisioned until the user logs in, and callers use this to decide whether a later retry makes sense.

func ScheduleExerciseFolderSync

func ScheduleExerciseFolderSync(database *gorm.DB, exerciseID uint)

ScheduleExerciseFolderSync fires the Forgejo exercise folder and label creation in a detached goroutine so the request path is not blocked. It uses the base *gorm.DB (not any request-scoped transaction) and reloads the exercise and course fresh, mirroring the forgejo hook pattern.

func SyncAllExerciseFolders

func SyncAllExerciseFolders(ctx context.Context, database *gorm.DB) error

SyncAllExerciseFolders ensures every exercise of every course has its folder in the template repo and all student repos. It is the backfill and repair sweep behind the forgejo-exercise-folder-sync admin task: it covers exercises created before folder sync existed and retries repos that failed earlier.

func SyncAllExerciseLabels

func SyncAllExerciseLabels(ctx context.Context, database *gorm.DB) error

SyncAllExerciseLabels ensures every exercise of every course has its label in the course's forum repo. It is the backfill and repair sweep behind the forgejo-exercise-label-sync admin task: it covers exercises created before label sync existed and retries labels that failed earlier.

func SyncUserAdminStatus

func SyncUserAdminStatus(user *db.User)

SyncUserAdminStatus updates the Forgejo user's admin flag to match the local db.User. It is a no-op when DefaultClient is nil (Forgejo not configured) or when the user has no Forgejo username. Marked deliberately as a package-level function so both API handlers and UI fragment handlers can call it without importing a *Client.

func SyncUserDisplayName

func SyncUserDisplayName(user *db.User)

SyncUserDisplayName updates the Forgejo user's full name to match the local display name. It is a no-op when DefaultClient is nil (Forgejo not configured), when the user has no Forgejo username, or when the display name is empty. Marked deliberately as a package-level function so API handlers and UI fragment handlers can call it without importing a *Client.

func ValidAccess

func ValidAccess(s string) bool

ValidAccess reports whether s is a valid access level.

func WithSource

func WithSource(ctx context.Context, source string) context.Context

WithSource returns a derived context that carries the given source label. The label is read back inside the logging transport and persisted on the resulting ForgejoRequest row. An empty source is stored as SourceUnknown.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps the Forgejo SDK with a logging transport so that every outgoing HTTP request is persisted to the forgejo_requests table.

var DefaultClient *Client

func NewClient

func NewClient(baseURL, token string, skipTLS bool, database *gorm.DB, tz *time.Location) (*Client, error)

NewClient creates a Forgejo API client whose outgoing requests are logged to the forgejo_requests table. The logging transport is installed on the shared *http.Client passed to the SDK, so every call (SDK and raw alike) is captured without per-call-site instrumentation.

func (*Client) AddCollaborator

func (c *Client) AddCollaborator(org, repo, username, access string) error

AddCollaborator grants the given user access to a repo with the specified permission level ("read" or "write"). Existing membership (HTTP 422) is treated as a no-op so the call is idempotent.

func (*Client) AddTeamMember

func (c *Client) AddTeamMember(teamID int64, username string) error

AddTeamMember adds a user to a team.

func (*Client) AddTeamRepo

func (c *Client) AddTeamRepo(teamID int64, org, repo string) error

AddTeamRepo associates a repository with a team.

func (*Client) CreateUserRepo

func (c *Client) CreateUserRepo(org, name string) error

CreateUserRepo generates a per-student repository inside the given org, named after the student, from the course's "template" repo using Forgejo's "generate from template" API. Unlike a fork there is no one-per-owner limit; unlike a migration there is no network clone (files are copied on the same filesystem). The new repo is private and starts with the same git content as the template. A pre-existing repo (HTTP 409) is treated as success so the call is idempotent and the weekly sync can re-run safely.

func (*Client) DeleteOrg

func (c *Client) DeleteOrg(name string) error

DeleteOrg removes the named organization from Forgejo.

func (*Client) DeleteRepo

func (c *Client) DeleteRepo(owner, repo string) error

DeleteRepo removes a repository from Forgejo.

func (*Client) EnsureCourseRepos

func (c *Client) EnsureCourseRepos(org string, course db.Course) error

EnsureCourseRepos creates the template repo plus every enabled configurable repo in the given course's org. Existing repos are left untouched, except the template repo which is marked as a Forgejo template (is_template=true) if it is not already. A pre-existing repo (HTTP 409) is treated as success.

func (*Client) EnsureCourseTeams

func (c *Client) EnsureCourseTeams(org string, course db.Course) error

EnsureCourseTeams creates the "students" and "tutors" teams in the course's Forgejo org and assigns each team to the appropriate repos based on the resolved access configuration. Repos that no longer grant access to a role are removed from the team.

func (*Client) EnsureExerciseFolder

func (c *Client) EnsureExerciseFolder(ctx context.Context, database *gorm.DB, course *db.Course, exercise *db.Exercise) error

EnsureExerciseFolder creates the folder for an exercise in the course's template repo and in every enrolled student's repo, marked by a placeholder README (heading plus empty tutor/build regions, see docs/build.md) and a notes template at <exercise.Name>/README.md and <exercise.Name>/NOTES.md.

Missing files are created with a bot commit; existing files are left untouched (students may have pushed work, and the grading service writes report READMEs). Per-student failures are logged and do not abort the remaining repos. Safe to call repeatedly and after a rename: the new folder is created if missing, the old folder is intentionally kept.

func (*Client) EnsureExerciseLabel

func (c *Client) EnsureExerciseLabel(ctx context.Context, database *gorm.DB, course *db.Course, exercise *db.Exercise) error

EnsureExerciseLabel creates a label named after the exercise in the course's forum repo, so issues submitted through the per-exercise issue template are tagged automatically. The label name matches the exercise name exactly. Missing labels are created; existing labels are left untouched. Safe to call repeatedly and after a rename: the label for the new name is created if missing, the old label is intentionally kept.

It is a no-op when the course has no enabled repo named "forum" (resolved from the course_repos setting and per-course overrides).

func (*Client) EnsureOrg

func (c *Client) EnsureOrg(name, fullName string) error

EnsureOrg ensures an organization with the given name and full name exists on the Forgejo instance. If the org exists with a different full name, the full name is updated. Orgs use limited visibility (visible to any signed-in user) so that non-private course repos such as the forum repo are readable by every logged-in user; Forgejo derives repo visibility from the owning org, and a private org would hide all repos from non-members.

func (*Client) EnsureTeam

func (c *Client) EnsureTeam(org, name, permission string) (int64, error)

EnsureTeam creates a team in the given org if it does not exist, or updates its permission if it does. Returns the team ID.

func (*Client) EnsureUserRepos

func (c *Client) EnsureUserRepos(ctx context.Context, database *gorm.DB, course *db.Course, user *db.User, role string) (string, error)

EnsureUserRepos is the canonical per-enrollment provisioning routine. It repairs every Forgejo resource tied to one user in one course:

  • the per-student repo, including recovery of a created-but-empty repo via recoverEmptyRepo (students only)
  • the exercise folders missing from the repo, never overwriting existing files (students only)
  • the student's write access on their own repo and the grader bot's write access for report commits (students only)
  • the tutors team's access on the student repo, so every tutor in the course can read and push to it (students only)
  • team membership in the students or tutors team

role is "student" or "tutor". Steps run best-effort: after a step fails the remaining steps still run and the first error is returned. Returns ErrUserNotLinked (wrapped) when the user row has no OIDC subject yet, and ErrForgejoUserMissing (wrapped) when the user has no Forgejo account; in both cases no Forgejo calls were made.

The returned action string is the repo reconcile outcome ("created", "recovered", or "noop") for callers that keep counters; it is "noop" for tutors, who have no per-user repo.

func (*Client) ForceDeleteOrg

func (c *Client) ForceDeleteOrg(org string) ForceDeleteResult

ForceDeleteOrg removes every repository in the org and then the org itself. It exists so admins can clean up orgs that Forgejo would otherwise refuse to delete because they still own repositories, which is inherently destructive to student work. Every step is logged; the caller is responsible for verifying that the org has no matching course.

When any repo deletion fails, the org deletion is skipped: Forgejo would reject it anyway and a clear "skipped" reason is more useful than the raw org-delete error.

func (*Client) GetFile

func (c *Client) GetFile(owner, repo, ref, path string) ([]byte, error)

A 404 (file missing) returns (nil, nil) so callers can treat "not present" as a benign outcome without inspecting errors.

func (*Client) GetRepoBranch

func (c *Client) GetRepoBranch(org, repo, branch string) (*fj.Branch, error)

GetRepoBranch returns metadata for a single branch in a repo, including the commit SHA of its tip. A 404 is reported as (nil, nil) so callers can treat "branch does not exist" as a normal outcome.

func (*Client) ListOrgNames

func (c *Client) ListOrgNames() ([]string, error)

ListOrgNames returns the UserName of every organization visible to the bot token.

func (*Client) ListOrgRepos

func (c *Client) ListOrgRepos(org string) ([]*fj.Repository, error)

ListOrgRepos returns every repository that lives in the given organisation. The result is the full set of repos for the org (across all pages).

func (*Client) ListOrgTeamIDs

func (c *Client) ListOrgTeamIDs(org string) (map[string]int64, error)

ListOrgTeamIDs returns the IDs of all teams in an org.

func (*Client) ListTeamMembers

func (c *Client) ListTeamMembers(teamID int64) ([]string, error)

ListTeamMembers returns the usernames of all members of a team.

func (*Client) OrgExists

func (c *Client) OrgExists(name string) (bool, error)

OrgExists reports whether an organization with the given name exists on Forgejo.

func (*Client) ReconcileStudentExerciseFolders

func (c *Client) ReconcileStudentExerciseFolders(ctx context.Context, database *gorm.DB, course *db.Course, username string) error

ReconcileStudentExerciseFolders ensures every exercise of the given course has its folder in the named student repo. It is the per-student counterpart of EnsureExerciseFolder and covers repos that missed the original fan-out, most notably when a student rejoins a course: leave keeps the repo, so rejoin only re-grants access and the folders created during the leave period would stay missing otherwise.

Only the student repo is touched, never the template repo: the template was already seeded when the exercise was created, and the weekly folder sync repairs template drift. Missing README and NOTES files are created with a bot commit; existing files are left untouched.

func (*Client) RemoveCollaborator

func (c *Client) RemoveCollaborator(org, repo, username string) error

RemoveCollaborator revokes a user's access to a repo. Missing membership (HTTP 404) is treated as a no-op.

func (*Client) RemoveTeamMember

func (c *Client) RemoveTeamMember(teamID int64, username string) error

RemoveTeamMember removes a user from a team. A 404 is treated as success (user was already not a member).

func (*Client) RemoveTeamRepo

func (c *Client) RemoveTeamRepo(teamID int64, org, repo string) error

RemoveTeamRepo removes a repository from a team. A 404 is treated as success.

func (*Client) RenameOrg

func (c *Client) RenameOrg(oldName, newName string) error

RenameOrg renames an organization on Forgejo. The SDK does not expose a rename method, so this is the one call that does not use the SDK; the request flows through c.http directly and the logging transport still captures it.

func (*Client) RepoExists

func (c *Client) RepoExists(org, name string) (bool, error)

RepoExists reports whether a repository with the given name exists in the given org on Forgejo. A 404 is reported as (false, nil).

func (*Client) RepoHasCommits

func (c *Client) RepoHasCommits(owner, repo string) (bool, error)

RepoHasCommits reports whether the repo has at least one commit. A repo whose generate push never landed has zero commits. A 404 from the commits endpoint (Forgejo reports empty repos as not found there) counts as zero commits, not an error. Errors are returned, not swallowed, so callers can distinguish "no commits" from "could not check".

func (*Client) SetUserAdmin

func (c *Client) SetUserAdmin(username string, isAdmin bool) error

SetUserAdmin promotes or demotes a Forgejo user to/from site admin. A 404 (user does not exist on Forgejo) is treated as a no-op.

func (*Client) SetUserFullName

func (c *Client) SetUserFullName(username, fullName string) error

SetUserFullName updates a Forgejo user's full name. A 404 (user does not exist on Forgejo) is treated as a no-op.

func (*Client) SyncTemplateToStudents

func (c *Client) SyncTemplateToStudents(ctx context.Context, database *gorm.DB, course *db.Course, oldSHA, newSHA, branch string, files []string) error

SyncTemplateToStudents propagates template repo changes to all student repos. For each changed file, if the student's version matches the old template version exactly, the file is updated to the new template version via a bot commit. Files the student has modified are left untouched.

oldSHA and newSHA are the commit SHAs before and after the push. The diff covers all commits in the push, so multiple commits in a single push are handled correctly: the "old" version is the file content at oldSHA, and the "new" version is the file content at newSHA.

func (*Client) UserExists

func (c *Client) UserExists(username string) (bool, error)

UserExists reports whether a user with the given username exists in Forgejo. A 404 is reported as (false, nil).

type CourseRepoSpec

type CourseRepoSpec struct {
	Name          string `json:"name"`
	Private       bool   `json:"private"`
	Enabled       bool   `json:"enabled"`
	HasCode       bool   `json:"has_code"`
	HasIssues     bool   `json:"has_issues"`
	StudentAccess string `json:"student_access"` // "none", "read", "write"
	TutorAccess   string `json:"tutor_access"`   // "none", "read", "write"
}

CourseRepoSpec describes one configurable repository that a course's Forgejo org may contain. The "template" repo is not configurable; it is always created and always private. StudentAccess and TutorAccess define the default Forgejo collaborator permission for students and tutors on this repo: "none", "read", or "write".

func CourseRepoSpecsFromDB

func CourseRepoSpecsFromDB(database *gorm.DB) []CourseRepoSpec

CourseRepoSpecsFromDB reads course repo specs from the course_repos Setting, falling back to defaults when absent or invalid.

func ParseCourseRepoSpecs

func ParseCourseRepoSpecs(data string) ([]CourseRepoSpec, error)

ParseCourseRepoSpecs parses a JSON array of CourseRepoSpec values and validates that every repo has a non-empty name and that no repo is named "template" (which is reserved and always created).

type ForceDeleteResult

type ForceDeleteResult struct {
	Org string
	// DeletedRepos lists the repos that were removed, in deletion order.
	DeletedRepos []string
	// FailedRepos lists the repos that could not be removed. The org is
	// not deleted when this is non-empty, because Forgejo refuses to
	// delete orgs that still own repositories.
	FailedRepos []RepoDeleteFailure
	// OrgDeleteErr is the error from deleting the org itself, nil on
	// success. It is set to a "skipped" error when repo deletions failed.
	OrgDeleteErr error
}

ForceDeleteResult reports the outcome of ForceDeleteOrg.

func (ForceDeleteResult) Success

func (r ForceDeleteResult) Success() bool

Success reports whether the org and all of its repos were deleted.

type NoopRecorder

type NoopRecorder struct{}

NoopRecorder discards every record. Exported so callers (and tests) can swap it in.

func (NoopRecorder) Record

func (NoopRecorder) Record(db.ForgejoRequest)

Record discards the entry.

type OrphanOrgStatus

type OrphanOrgStatus int

OrphanOrgStatus classifies a Forgejo org relative to the courses in the orchestration database.

const (
	// OrphanStatusActiveCourse: an active (non-deleted) course has this UID.
	OrphanStatusActiveCourse OrphanOrgStatus = iota
	// OrphanStatusArchivedCourse: only a soft-deleted course has this UID.
	// Such orgs hold student work and must not be deleted from the admin UI.
	OrphanStatusArchivedCourse
	// OrphanStatusOrphan: no course, active or archived, has this UID.
	OrphanStatusOrphan
)

func ClassifyOrphanOrg

func ClassifyOrphanOrg(orgName string, courses []db.Course) OrphanOrgStatus

ClassifyOrphanOrg reports how orgName relates to the given courses. The course slice must include soft-deleted courses (load with Unscoped) so archived-course orgs can be told apart from true orphans.

func (OrphanOrgStatus) Deletable

func (s OrphanOrgStatus) Deletable() bool

Deletable reports whether the org may be force-deleted from the admin UI. Only orgs with no matching course at all are deletable.

func (OrphanOrgStatus) Label

func (s OrphanOrgStatus) Label() string

Label returns a short human-readable description of the status.

type Recorder

type Recorder interface {
	Record(entry db.ForgejoRequest)
}

Recorder persists ForgejoRequest rows. The default implementation writes to a *gorm.DB; a no-op recorder is used in tests.

func NewGormRecorder

func NewGormRecorder(database *gorm.DB) Recorder

NewGormRecorder returns a Recorder backed by the given DB.

type RepoDeleteFailure

type RepoDeleteFailure struct {
	Repo string
	Err  string
}

RepoDeleteFailure records one repository that could not be deleted.

type ResolvedRepoSpec

type ResolvedRepoSpec struct {
	Name          string
	Private       bool
	Enabled       bool
	HasCode       bool
	HasIssues     bool
	StudentAccess string
	TutorAccess   string
}

ResolvedRepoSpec is a CourseRepoSpec with per-course overrides applied.

func RepoAccessForCourse

func RepoAccessForCourse(course db.Course, database *gorm.DB) []ResolvedRepoSpec

RepoAccessForCourse returns the resolved access levels for all course repos, merging global defaults with per-course overrides. Exported so the cron and other callers can use it without a *Client.

func (ResolvedRepoSpec) AccessFor

func (s ResolvedRepoSpec) AccessFor(role string) string

AccessFor returns the access level for the given role ("student" or "tutor").

Directories

Path Synopsis
Package cron registers background jobs that maintain the forgejo_requests table.
Package cron registers background jobs that maintain the forgejo_requests table.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL