code.gitea.io/gitea@v1.21.7/services/org/org.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package org
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  
    10  	"code.gitea.io/gitea/models"
    11  	"code.gitea.io/gitea/models/db"
    12  	org_model "code.gitea.io/gitea/models/organization"
    13  	packages_model "code.gitea.io/gitea/models/packages"
    14  	repo_model "code.gitea.io/gitea/models/repo"
    15  	user_model "code.gitea.io/gitea/models/user"
    16  	"code.gitea.io/gitea/modules/storage"
    17  	"code.gitea.io/gitea/modules/util"
    18  	repo_service "code.gitea.io/gitea/services/repository"
    19  )
    20  
    21  // DeleteOrganization completely and permanently deletes everything of organization.
    22  func DeleteOrganization(ctx context.Context, org *org_model.Organization, purge bool) error {
    23  	ctx, commiter, err := db.TxContext(ctx)
    24  	if err != nil {
    25  		return err
    26  	}
    27  	defer commiter.Close()
    28  
    29  	if purge {
    30  		err := repo_service.DeleteOwnerRepositoriesDirectly(ctx, org.AsUser())
    31  		if err != nil {
    32  			return err
    33  		}
    34  	}
    35  
    36  	// Check ownership of repository.
    37  	count, err := repo_model.CountRepositories(ctx, repo_model.CountRepositoryOptions{OwnerID: org.ID})
    38  	if err != nil {
    39  		return fmt.Errorf("GetRepositoryCount: %w", err)
    40  	} else if count > 0 {
    41  		return models.ErrUserOwnRepos{UID: org.ID}
    42  	}
    43  
    44  	// Check ownership of packages.
    45  	if ownsPackages, err := packages_model.HasOwnerPackages(ctx, org.ID); err != nil {
    46  		return fmt.Errorf("HasOwnerPackages: %w", err)
    47  	} else if ownsPackages {
    48  		return models.ErrUserOwnPackages{UID: org.ID}
    49  	}
    50  
    51  	if err := org_model.DeleteOrganization(ctx, org); err != nil {
    52  		return fmt.Errorf("DeleteOrganization: %w", err)
    53  	}
    54  
    55  	if err := commiter.Commit(); err != nil {
    56  		return err
    57  	}
    58  
    59  	// FIXME: system notice
    60  	// Note: There are something just cannot be roll back,
    61  	//	so just keep error logs of those operations.
    62  	path := user_model.UserPath(org.Name)
    63  
    64  	if err := util.RemoveAll(path); err != nil {
    65  		return fmt.Errorf("failed to RemoveAll %s: %w", path, err)
    66  	}
    67  
    68  	if len(org.Avatar) > 0 {
    69  		avatarPath := org.CustomAvatarRelativePath()
    70  		if err := storage.Avatars.Delete(avatarPath); err != nil {
    71  			return fmt.Errorf("failed to remove %s: %w", avatarPath, err)
    72  		}
    73  	}
    74  
    75  	return nil
    76  }