← back to egeozcan__mahresources

Function bodies 753 total

All specs Real LLM only Function bodies
application_context.MahresourcesContext.GetQueries method · go · L35-L43 (9 LOC)
application_context/query_context.go
func (ctx *MahresourcesContext) GetQueries(offset, maxResults int, searchQuery *query_models.QueryQuery) ([]models.Query, error) {
	var res []models.Query

	if err := ctx.db.Scopes(database_scopes.QueryQuery(searchQuery)).Limit(maxResults).Offset(offset).Model(&res).Find(&res).Error; err != nil {
		return nil, err
	}

	return res, nil
}
application_context.MahresourcesContext.GetQueriesCount method · go · L45-L50 (6 LOC)
application_context/query_context.go
func (ctx *MahresourcesContext) GetQueriesCount(queryQ *query_models.QueryQuery) (int64, error) {
	var query models.Query
	var count int64

	return count, ctx.db.Scopes(database_scopes.QueryQuery(queryQ)).Model(&query).Count(&count).Error
}
application_context.MahresourcesContext.GetQuery method · go · L52-L59 (8 LOC)
application_context/query_context.go
func (ctx *MahresourcesContext) GetQuery(id uint) (*models.Query, error) {
	var query models.Query

	err := ctx.db.
		First(&query, id).Error

	return &query, err
}
application_context.MahresourcesContext.CreateQuery method · go · L61-L80 (20 LOC)
application_context/query_context.go
func (ctx *MahresourcesContext) CreateQuery(queryQuery *query_models.QueryCreator) (*models.Query, error) {
	if strings.TrimSpace(queryQuery.Name) == "" {
		return nil, errors.New("query name must be non-empty")
	}

	query := models.Query{
		Name:     queryQuery.Name,
		Text:     queryQuery.Text,
		Template: queryQuery.Template,
	}

	if err := ctx.db.Create(&query).Error; err != nil {
		return nil, err
	}

	ctx.Logger().Info(models.LogActionCreate, "query", &query.ID, query.Name, "Created query", nil)

	ctx.InvalidateSearchCacheByType(EntityTypeQuery)
	return &query, nil
}
application_context.MahresourcesContext.UpdateQuery method · go · L82-L102 (21 LOC)
application_context/query_context.go
func (ctx *MahresourcesContext) UpdateQuery(queryQuery *query_models.QueryEditor) (*models.Query, error) {
	var query models.Query
	if err := ctx.db.First(&query, queryQuery.ID).Error; err != nil {
		return nil, err
	}

	if strings.TrimSpace(queryQuery.Name) != "" {
		query.Name = queryQuery.Name
	}
	query.Text = queryQuery.Text
	query.Template = queryQuery.Template

	if err := ctx.db.Save(&query).Error; err != nil {
		return nil, err
	}

	ctx.Logger().Info(models.LogActionUpdate, "query", &query.ID, query.Name, "Updated query", nil)

	ctx.InvalidateSearchCacheByType(EntityTypeQuery)
	return &query, nil
}
application_context.MahresourcesContext.GetDatabaseSchema method · go · L104-L179 (76 LOC)
application_context/query_context.go
func (ctx *MahresourcesContext) GetDatabaseSchema() (map[string][]string, error) {
	schema := make(map[string][]string)

	sqlDB, err := ctx.db.DB()
	if err != nil {
		return nil, fmt.Errorf("getting underlying DB connection: %w", err)
	}

	if ctx.Config.DbType == constants.DbTypePosgres {
		rows, err := sqlDB.Query(
			`SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'public' ORDER BY table_name, ordinal_position`,
		)
		if err != nil {
			return nil, fmt.Errorf("querying postgres schema: %w", err)
		}
		defer rows.Close()

		for rows.Next() {
			var table, column string
			if err := rows.Scan(&table, &column); err != nil {
				return nil, fmt.Errorf("scanning postgres schema row: %w", err)
			}
			schema[table] = append(schema[table], column)
		}
		return schema, rows.Err()
	}

	// SQLite path
	tableRows, err := sqlDB.Query(
		`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`,
	)
	if err != nil {
		return nil, fmt.Erro
application_context.MahresourcesContext.DeleteQuery method · go · L181-L195 (15 LOC)
application_context/query_context.go
func (ctx *MahresourcesContext) DeleteQuery(queryId uint) error {
	// Load query name before deletion for audit log
	var query models.Query
	if err := ctx.db.First(&query, queryId).Error; err != nil {
		return err
	}
	queryName := query.Name

	err := ctx.db.Select(clause.Associations).Delete(&query).Error
	if err == nil {
		ctx.Logger().Info(models.LogActionDelete, "query", &queryId, queryName, "Deleted query", nil)
		ctx.InvalidateSearchCacheByType(EntityTypeQuery)
	}
	return err
}
Source: Repobility analyzer · https://repobility.com
application_context.MahresourcesContext.EditRelation method · go · L12-L31 (20 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) EditRelation(query query_models.GroupRelationshipQuery) (*models.GroupRelation, error) {
	var relation = &models.GroupRelation{ID: query.Id}

	if err := ctx.db.First(relation).Error; err != nil {
		return nil, err
	}

	if query.Name != "" {
		relation.Name = query.Name
	}
	relation.Description = query.Description

	if err := ctx.db.Save(relation).Error; err != nil {
		return nil, err
	}

	ctx.Logger().Info(models.LogActionUpdate, "relation", &relation.ID, relation.Name, "Updated relation", nil)

	return relation, nil
}
application_context.MahresourcesContext.AddRelation method · go · L33-L88 (56 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) AddRelation(fromGroupId, toGroupId, relationTypeId uint) (*models.GroupRelation, error) {
	var relationType models.GroupRelationType
	var fromGroup models.Group
	var toGroup models.Group
	var relation models.GroupRelation

	if fromGroupId == toGroupId {
		return nil, errors.New("cannot relate to self")
	}

	err := ctx.db.Transaction(func(tx *gorm.DB) error {
		if err := tx.First(&relationType, relationTypeId).Error; err != nil {
			return err
		}

		if err := tx.First(&fromGroup, fromGroupId).Error; err != nil {
			return err
		}

		if err := tx.First(&toGroup, toGroupId).Error; err != nil {
			return err
		}

		if *toGroup.CategoryId != *relationType.ToCategoryId || *fromGroup.CategoryId != *relationType.FromCategoryId {
			return errors.New("category mismatch")
		}

		relation = models.GroupRelation{
			FromGroupId:    &fromGroup.ID,
			ToGroupId:      &toGroup.ID,
			RelationTypeId: &relationType.ID,
		}

		if err := tx.Save(&relation).Error; err != n
application_context.MahresourcesContext.GetRelationType method · go · L96-L101 (6 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) GetRelationType(id uint) (*models.GroupRelationType, error) {
	var relationType models.GroupRelationType
	ctx.db.Preload(clause.Associations, pageLimit).First(&relationType, id)

	return &relationType, ctx.db.Preload(clause.Associations, pageLimit).First(&relationType, id).Error
}
application_context.MahresourcesContext.AddRelationType method · go · L103-L154 (52 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) AddRelationType(query *query_models.RelationshipTypeEditorQuery) (*models.GroupRelationType, error) {
	var relationType = models.GroupRelationType{
		Name:           query.Name,
		FromCategoryId: &query.FromCategory,
		ToCategoryId:   &query.ToCategory,
		Description:    query.Description,
	}

	err := ctx.db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Save(&relationType).Error; err != nil {
			return err
		}

		if query.ReverseName != "" {
			if query.ReverseName == query.Name {
				relationType.BackRelationId = &relationType.ID

				return tx.Save(&relationType).Error
			}

			backRelationType := models.GroupRelationType{
				Name:           query.ReverseName,
				FromCategoryId: &query.ToCategory,
				ToCategoryId:   &query.FromCategory,
			}

			if err := tx.Where(&backRelationType).First(&backRelationType).Error; err == nil {
				if backRelationType.BackRelationId != nil {
					return errors.New("back relation is already associated with some
application_context.MahresourcesContext.EditRelationType method · go · L156-L177 (22 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) EditRelationType(query *query_models.RelationshipTypeEditorQuery) (*models.GroupRelationType, error) {
	var relationType = models.GroupRelationType{}

	err := ctx.db.Transaction(func(tx *gorm.DB) error {
		if err := ctx.db.First(&relationType, query.Id).Error; err != nil {
			return err
		}

		if query.Name != "" {
			relationType.Name = query.Name
		}
		relationType.Description = query.Description

		return ctx.db.Save(&relationType).Error
	})

	if err == nil {
		ctx.Logger().Info(models.LogActionUpdate, "relationType", &relationType.ID, relationType.Name, "Updated relation type", nil)
		ctx.InvalidateSearchCacheByType(EntityTypeRelationType)
	}
	return &relationType, err
}
application_context.MahresourcesContext.GetRelationTypesCount method · go · L185-L190 (6 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) GetRelationTypesCount(query *query_models.RelationshipTypeQuery) (int64, error) {
	var relationType models.GroupRelationType
	var count int64

	return count, ctx.db.Scopes(database_scopes.RelationTypeQuery(query)).Model(&relationType).Count(&count).Error
}
application_context.MahresourcesContext.GetRelationsCount method · go · L198-L204 (7 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) GetRelationsCount(query *query_models.GroupRelationshipQuery) (int64, error) {
	var groupRelation models.GroupRelation
	var count int64
	err := ctx.db.Scopes(database_scopes.RelationQuery(query)).Model(&groupRelation).Count(&count).Error

	return count, err
}
application_context.MahresourcesContext.GetRelationTypesWithIds method · go · L206-L214 (9 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) GetRelationTypesWithIds(ids *[]uint) ([]*models.GroupRelationType, error) {
	var relationTypes []*models.GroupRelationType

	if len(*ids) == 0 {
		return relationTypes, nil
	}

	return relationTypes, ctx.db.Find(&relationTypes, ids).Error
}
Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
application_context.MahresourcesContext.DeleteRelationship method · go · L216-L229 (14 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) DeleteRelationship(relationshipId uint) error {
	// Load relation name before deletion for audit log
	var relation models.GroupRelation
	if err := ctx.db.First(&relation, relationshipId).Error; err != nil {
		return err
	}
	relationName := relation.Name

	err := ctx.db.Select(clause.Associations).Delete(&relation).Error
	if err == nil {
		ctx.Logger().Info(models.LogActionDelete, "relation", &relationshipId, relationName, "Deleted relation", nil)
	}
	return err
}
application_context.MahresourcesContext.DeleteRelationshipType method · go · L231-L245 (15 LOC)
application_context/relation_context.go
func (ctx *MahresourcesContext) DeleteRelationshipType(relationshipTypeId uint) error {
	// Load relation type name before deletion for audit log
	var relationType models.GroupRelationType
	if err := ctx.db.First(&relationType, relationshipTypeId).Error; err != nil {
		return err
	}
	relationTypeName := relationType.Name

	err := ctx.db.Select(clause.Associations).Delete(&relationType).Error
	if err == nil {
		ctx.Logger().Info(models.LogActionDelete, "relationType", &relationshipTypeId, relationTypeName, "Deleted relation type", nil)
		ctx.InvalidateSearchCacheByType(EntityTypeRelationType)
	}
	return err
}
application_context.MahresourcesContext.DeleteResource method · go · L22-L116 (95 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) DeleteResource(resourceId uint) error {
	resource := models.Resource{ID: resourceId}

	if err := ctx.db.Model(&resource).First(&resource).Error; err != nil {
		return err
	}

	fs, storageErr := ctx.GetFsForStorageLocation(resource.StorageLocation)

	if storageErr != nil {
		return storageErr
	}

	subFolder := "deleted"

	if resource.StorageLocation != nil && *resource.StorageLocation != "" {
		subFolder = *resource.StorageLocation
	}

	folder := fmt.Sprintf("/deleted/%v/", subFolder)

	if err := ctx.fs.MkdirAll(folder, 0777); err != nil {
		return err
	}

	ownerIdStr := "nil"
	if resource.OwnerId != nil {
		ownerIdStr = fmt.Sprintf("%v", *resource.OwnerId)
	}
	filePath := path.Join(folder, fmt.Sprintf("%v__%v__%v___%v", resource.Hash, resource.ID, ownerIdStr, strings.ReplaceAll(path.Clean(path.Base(resource.GetCleanLocation())), "\\", "_")))

	file, openErr := fs.Open(resource.GetCleanLocation())

	if openErr == nil {
		backup, createErr := ctx.fs.Create
application_context.MahresourcesContext.BulkRemoveTagsFromResources method · go · L122-L142 (21 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) BulkRemoveTagsFromResources(query *query_models.BulkEditQuery) error {
	if len(query.ID) == 0 || len(query.EditedId) == 0 {
		return nil
	}

	err := ctx.db.Transaction(func(tx *gorm.DB) error {
		return tx.Exec(
			"DELETE FROM resource_tags WHERE resource_id IN ? AND tag_id IN ?",
			query.ID, query.EditedId,
		).Error
	})

	if err == nil {
		ctx.Logger().Info(models.LogActionUpdate, "resource", nil, "", "Bulk removed tags from resources", map[string]interface{}{
			"resourceIds": query.ID,
			"tagIds":      query.EditedId,
		})
	}

	return err
}
application_context.MahresourcesContext.BulkReplaceTagsFromResources method · go · L144-L188 (45 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) BulkReplaceTagsFromResources(query *query_models.BulkEditQuery) error {
	if len(query.ID) == 0 {
		return nil
	}

	uniqueEditedIds := deduplicateUints(query.EditedId)

	err := ctx.db.Transaction(func(tx *gorm.DB) error {
		// Validate all tags exist
		if len(uniqueEditedIds) > 0 {
			var tagCount int64
			if err := tx.Model(&models.Tag{}).Where("id IN ?", uniqueEditedIds).Count(&tagCount).Error; err != nil {
				return err
			}
			if int(tagCount) != len(uniqueEditedIds) {
				return fmt.Errorf("one or more tags not found")
			}
		}

		// Remove all existing tags for these resources
		if err := tx.Exec("DELETE FROM resource_tags WHERE resource_id IN ?", query.ID).Error; err != nil {
			return err
		}

		// Add the new tags
		for _, tagID := range uniqueEditedIds {
			if err := tx.Exec(
				"INSERT INTO resource_tags (resource_id, tag_id) SELECT id, ? FROM resources WHERE id IN ? ON CONFLICT DO NOTHING",
				tagID, query.ID,
			).Error; err != nil {
				r
application_context.MahresourcesContext.BulkAddMetaToResources method · go · L190-L217 (28 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) BulkAddMetaToResources(query *query_models.BulkEditMetaQuery) error {
	if !json.Valid([]byte(query.Meta)) {
		return errors.New("invalid json")
	}

	var resource models.Resource

	var expr clause.Expr

	if ctx.Config.DbType == constants.DbTypePosgres {
		expr = gorm.Expr("meta || ?", query.Meta)
	} else {
		expr = gorm.Expr("json_patch(meta, ?)", query.Meta)
	}

	err := ctx.db.
		Model(&resource).
		Where("id in ?", query.ID).
		Update("Meta", expr).Error

	if err == nil {
		ctx.Logger().Info(models.LogActionUpdate, "resource", nil, "", "Bulk added meta to resources", map[string]interface{}{
			"resourceIds": query.ID,
		})
	}

	return err
}
application_context.MahresourcesContext.BulkAddTagsToResources method · go · L219-L256 (38 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) BulkAddTagsToResources(query *query_models.BulkEditQuery) error {
	if len(query.ID) == 0 || len(query.EditedId) == 0 {
		return nil
	}

	uniqueEditedIds := deduplicateUints(query.EditedId)

	err := ctx.db.Transaction(func(tx *gorm.DB) error {
		// Validate all tags exist (single query, no preloads)
		var tagCount int64
		if err := tx.Model(&models.Tag{}).Where("id IN ?", uniqueEditedIds).Count(&tagCount).Error; err != nil {
			return err
		}
		if int(tagCount) != len(uniqueEditedIds) {
			return fmt.Errorf("one or more tags not found")
		}

		// Batch insert: one INSERT per tag, skip conflicts
		for _, tagID := range uniqueEditedIds {
			if err := tx.Exec(
				"INSERT INTO resource_tags (resource_id, tag_id) SELECT id, ? FROM resources WHERE id IN ? ON CONFLICT DO NOTHING",
				tagID, query.ID,
			).Error; err != nil {
				return err
			}
		}
		return nil
	})

	if err == nil {
		ctx.Logger().Info(models.LogActionUpdate, "resource", nil, "", "Bulk added t
application_context.MahresourcesContext.BulkAddGroupsToResources method · go · L258-L293 (36 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) BulkAddGroupsToResources(query *query_models.BulkEditQuery) error {
	if len(query.ID) == 0 || len(query.EditedId) == 0 {
		return nil
	}

	uniqueEditedIds := deduplicateUints(query.EditedId)

	err := ctx.db.Transaction(func(tx *gorm.DB) error {
		var groupCount int64
		if err := tx.Model(&models.Group{}).Where("id IN ?", uniqueEditedIds).Count(&groupCount).Error; err != nil {
			return err
		}
		if int(groupCount) != len(uniqueEditedIds) {
			return fmt.Errorf("one or more groups not found")
		}

		for _, groupID := range uniqueEditedIds {
			if err := tx.Exec(
				"INSERT INTO groups_related_resources (resource_id, group_id) SELECT id, ? FROM resources WHERE id IN ? ON CONFLICT DO NOTHING",
				groupID, query.ID,
			).Error; err != nil {
				return err
			}
		}
		return nil
	})

	if err == nil {
		ctx.Logger().Info(models.LogActionUpdate, "resource", nil, "", "Bulk added groups to resources", map[string]interface{}{
			"resourceIds": query.ID,
			"group
Repobility · code-quality intelligence platform · https://repobility.com
application_context.MahresourcesContext.deleteResourceDBOnly method · go · L309-L368 (60 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) deleteResourceDBOnly(resourceId uint) (*FileCleanupAction, error) {
	resource := models.Resource{ID: resourceId}
	if err := ctx.db.Model(&resource).First(&resource).Error; err != nil {
		return nil, err
	}

	fs, storageErr := ctx.GetFsForStorageLocation(resource.StorageLocation)
	if storageErr != nil {
		return nil, storageErr
	}

	subFolder := "deleted"
	if resource.StorageLocation != nil && *resource.StorageLocation != "" {
		subFolder = *resource.StorageLocation
	}
	folder := fmt.Sprintf("/deleted/%v/", subFolder)

	ownerIdStr := "nil"
	if resource.OwnerId != nil {
		ownerIdStr = fmt.Sprintf("%v", *resource.OwnerId)
	}
	backupPath := path.Join(folder, fmt.Sprintf("%v__%v__%v___%v", resource.Hash, resource.ID, ownerIdStr, strings.ReplaceAll(path.Clean(path.Base(resource.GetCleanLocation())), "\\", "_")))

	// Clear CurrentVersionID to break circular reference before deletion
	if resource.CurrentVersionID != nil {
		if err := ctx.db.Model(&resource).Upd
application_context.MahresourcesContext.BulkDeleteResources method · go · L370-L417 (48 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) BulkDeleteResources(query *query_models.BulkQuery) error {
	var cleanupActions []*FileCleanupAction

	err := ctx.WithTransaction(func(altCtx *MahresourcesContext) error {
		for _, id := range query.ID {
			action, err := altCtx.deleteResourceDBOnly(id)
			if err != nil {
				return err
			}
			if action != nil {
				cleanupActions = append(cleanupActions, action)
			}
		}
		return nil
	})

	if err != nil {
		return err // Transaction rolled back, no file operations performed
	}

	// Phase 2: File operations after successful commit
	for _, action := range cleanupActions {
		// Create backup
		if err := ctx.fs.MkdirAll(path.Dir(action.BackupPath), 0777); err != nil {
			ctx.Logger().Warning(models.LogActionDelete, "resource", nil, "Failed to create backup dir", err.Error(), nil)
			continue
		}

		backupOK := false
		file, openErr := action.SourceFS.Open(action.SourcePath)
		if openErr == nil {
			backup, createErr := ctx.fs.Create(action.BackupPath)
			if
application_context.MahresourcesContext.GetPopularResourceTags method · go · L419-L432 (14 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) GetPopularResourceTags(query *query_models.ResourceSearchQuery) ([]PopularTag, error) {
	var res []PopularTag

	db := ctx.db.Table("resources").
		Scopes(database_scopes.ResourceQuery(query, true, ctx.db)).
		Joins("INNER JOIN resource_tags pt ON pt.resource_id = resources.id").
		Joins("INNER JOIN tags t ON t.id = pt.tag_id").
		Select("t.id AS id, t.name AS name, count(*) AS count").
		Group("t.id, t.name").
		Order("count DESC").
		Limit(20)

	return res, db.Scan(&res).Error
}
application_context.MahresourcesContext.MergeResources method · go · L434-L569 (136 LOC)
application_context/resource_bulk_context.go
func (ctx *MahresourcesContext) MergeResources(winnerId uint, loserIds []uint) error {
	if len(loserIds) == 0 || winnerId == 0 {
		return errors.New("incorrect parameters")
	}

	for i, id := range loserIds {
		if id == 0 {
			return fmt.Errorf("loser number %v has 0 id", i+1)
		}

		if id == winnerId {
			return errors.New("winner cannot be one of the losers")
		}
	}

	// Two-phase approach: DB operations in transaction, file I/O after commit
	var cleanupActions []*FileCleanupAction

	err := ctx.WithTransaction(func(transactionCtx *MahresourcesContext) error {
		tx := transactionCtx.db

		// Load losers WITHOUT associations — we only need their basic fields for backup
		var losers []*models.Resource
		if loadResourcesErr := tx.Find(&losers, &loserIds).Error; loadResourcesErr != nil {
			return loadResourcesErr
		}

		// Load winner WITHOUT associations
		var winner models.Resource
		if err := tx.First(&winner, winnerId).Error; err != nil {
			return err
		}

		// Transfer associations 
application_context.MahresourcesContext.GetResourceCategories method · go · L18-L23 (6 LOC)
application_context/resource_category_context.go
func (ctx *MahresourcesContext) GetResourceCategories(offset, maxResults int, query *query_models.ResourceCategoryQuery) ([]models.ResourceCategory, error) {
	var resourceCategories []models.ResourceCategory
	scope := database_scopes.ResourceCategoryQuery(query)

	return resourceCategories, ctx.db.Scopes(scope).Limit(maxResults).Offset(offset).Find(&resourceCategories).Error
}
application_context.MahresourcesContext.GetResourceCategoriesCount method · go · L25-L30 (6 LOC)
application_context/resource_category_context.go
func (ctx *MahresourcesContext) GetResourceCategoriesCount(query *query_models.ResourceCategoryQuery) (int64, error) {
	var resourceCategory models.ResourceCategory
	var count int64

	return count, ctx.db.Scopes(database_scopes.ResourceCategoryQuery(query)).Model(&resourceCategory).Count(&count).Error
}
application_context.MahresourcesContext.GetResourceCategoriesWithIds method · go · L32-L46 (15 LOC)
application_context/resource_category_context.go
func (ctx *MahresourcesContext) GetResourceCategoriesWithIds(ids *[]uint, limit int) ([]models.ResourceCategory, error) {
	var resourceCategories []models.ResourceCategory

	if len(*ids) == 0 {
		return resourceCategories, nil
	}

	query := ctx.db

	if limit > 0 {
		query = query.Limit(limit)
	}

	return resourceCategories, query.Find(&resourceCategories, *ids).Error
}
application_context.MahresourcesContext.CreateResourceCategory method · go · L48-L71 (24 LOC)
application_context/resource_category_context.go
func (ctx *MahresourcesContext) CreateResourceCategory(query *query_models.ResourceCategoryCreator) (*models.ResourceCategory, error) {
	if strings.TrimSpace(query.Name) == "" {
		return nil, errors.New("resource category name must be non-empty")
	}

	resourceCategory := models.ResourceCategory{
		Name:          query.Name,
		Description:   query.Description,
		CustomHeader:  query.CustomHeader,
		CustomSidebar: query.CustomSidebar,
		CustomSummary: query.CustomSummary,
		CustomAvatar:  query.CustomAvatar,
		MetaSchema:    query.MetaSchema,
	}

	if err := ctx.db.Create(&resourceCategory).Error; err != nil {
		return nil, err
	}

	ctx.Logger().Info(models.LogActionCreate, "resourceCategory", &resourceCategory.ID, resourceCategory.Name, "Created resource category", nil)

	ctx.InvalidateSearchCacheByType(EntityTypeResourceCategory)
	return &resourceCategory, nil
}
Want fix-PRs on findings? Install Repobility's GitHub App · github.com/apps/repobility-bot
application_context.MahresourcesContext.UpdateResourceCategory method · go · L73-L97 (25 LOC)
application_context/resource_category_context.go
func (ctx *MahresourcesContext) UpdateResourceCategory(query *query_models.ResourceCategoryEditor) (*models.ResourceCategory, error) {
	var resourceCategory models.ResourceCategory
	if err := ctx.db.First(&resourceCategory, query.ID).Error; err != nil {
		return nil, err
	}

	if strings.TrimSpace(query.Name) != "" {
		resourceCategory.Name = query.Name
	}
	resourceCategory.Description = query.Description
	resourceCategory.CustomHeader = query.CustomHeader
	resourceCategory.CustomSidebar = query.CustomSidebar
	resourceCategory.CustomSummary = query.CustomSummary
	resourceCategory.CustomAvatar = query.CustomAvatar
	resourceCategory.MetaSchema = query.MetaSchema

	if err := ctx.db.Save(&resourceCategory).Error; err != nil {
		return nil, err
	}

	ctx.Logger().Info(models.LogActionUpdate, "resourceCategory", &resourceCategory.ID, resourceCategory.Name, "Updated resource category", nil)

	ctx.InvalidateSearchCacheByType(EntityTypeResourceCategory)
	return &resourceCategory, nil
}
application_context.MahresourcesContext.DeleteResourceCategory method · go · L99-L112 (14 LOC)
application_context/resource_category_context.go
func (ctx *MahresourcesContext) DeleteResourceCategory(resourceCategoryId uint) error {
	var resourceCategory models.ResourceCategory
	if err := ctx.db.First(&resourceCategory, resourceCategoryId).Error; err != nil {
		return err
	}
	resourceCategoryName := resourceCategory.Name

	err := ctx.db.Select(clause.Associations).Delete(&resourceCategory).Error
	if err == nil {
		ctx.Logger().Info(models.LogActionDelete, "resourceCategory", &resourceCategoryId, resourceCategoryName, "Deleted resource category", nil)
		ctx.InvalidateSearchCacheByType(EntityTypeResourceCategory)
	}
	return err
}
application_context.MahresourcesContext.GetSimilarResources method · go · L27-L108 (82 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) GetSimilarResources(id uint) ([]*models.Resource, error) {
	var resources []*models.Resource

	// Find all resource IDs similar to this one from pre-computed similarities
	var similarIDs []uint

	// Query both directions using UNION ALL for better index utilization.
	// We store with ResourceID1 < ResourceID2, so we need to check both columns.
	rows, err := ctx.db.Raw(`
		SELECT resource_id2 as similar_id, hamming_distance FROM resource_similarities WHERE resource_id1 = ?
		UNION ALL
		SELECT resource_id1 as similar_id, hamming_distance FROM resource_similarities WHERE resource_id2 = ?
		ORDER BY hamming_distance ASC
	`, id, id).Rows()

	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var similarID uint
		var hammingDistance int
		if err := rows.Scan(&similarID, &hammingDistance); err != nil {
			return nil, err
		}
		similarIDs = append(similarIDs, similarID)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}

	if
application_context.MahresourcesContext.GetResourceCount method · go · L110-L115 (6 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) GetResourceCount(query *query_models.ResourceSearchQuery) (int64, error) {
	var resource models.Resource
	var count int64

	return count, ctx.db.Scopes(database_scopes.ResourceQuery(query, true, ctx.db)).Model(&resource).Count(&count).Error
}
application_context.MahresourcesContext.GetResources method · go · L117-L134 (18 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) GetResources(offset, maxResults int, query *query_models.ResourceSearchQuery) ([]models.Resource, error) {
	var resources []models.Resource
	resLimit := maxResults

	if query.MaxResults > 0 {
		resLimit = int(query.MaxResults)
	}

	return resources, ctx.db.Scopes(database_scopes.ResourceQuery(query, false, ctx.db)).
		Limit(resLimit).
		Offset(offset).
		Preload("Tags").
		Preload("Owner").
		Preload("ResourceCategory").
		Preload("Series").
		Find(&resources).
		Error
}
application_context.MahresourcesContext.GetResourcesWithIds method · go · L136-L144 (9 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) GetResourcesWithIds(ids *[]uint) ([]*models.Resource, error) {
	var resources []*models.Resource

	if len(*ids) == 0 {
		return resources, nil
	}

	return resources, ctx.db.Preload("Tags").Find(&resources, ids).Error
}
application_context.MahresourcesContext.EditResource method · go · L146-L279 (134 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) EditResource(resourceQuery *query_models.ResourceEditor) (*models.Resource, error) {
	var resource models.Resource

	err := ctx.WithTransaction(func(altCtx *MahresourcesContext) error {
		tx := altCtx.db

		if err := tx.Preload(clause.Associations, pageLimit).First(&resource, resourceQuery.ID).Error; err != nil {
			return err
		}

		if err := tx.Model(&resource).Association("Groups").Clear(); err != nil {
			return err
		}

		if err := tx.Model(&resource).Association("Tags").Clear(); err != nil {
			return err
		}

		if err := tx.Model(&resource).Association("Notes").Clear(); err != nil {
			return err
		}

		groups := BuildAssociationSlice(resourceQuery.Groups, GroupFromID)
		if err := tx.Model(&resource).Association("Groups").Append(&groups); err != nil {
			return err
		}

		notes := BuildAssociationSlice(resourceQuery.Notes, NoteFromID)
		if err := tx.Model(&resource).Association("Notes").Append(&notes); err != nil {
			return err
		}

		tags := Bui
application_context.MahresourcesContext.GetSeriesSiblings method · go · L282-L288 (7 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) GetSeriesSiblings(resourceID uint, seriesID uint) ([]*models.Resource, error) {
	var resources []*models.Resource
	return resources, ctx.db.
		Where("series_id = ? AND id != ?", seriesID, resourceID).
		Order("created_at ASC").
		Find(&resources).Error
}
Source: Repobility analyzer · https://repobility.com
application_context.MahresourcesContext.GetResourceByHash method · go · L293-L299 (7 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) GetResourceByHash(hash string) (*models.Resource, error) {
	var resource models.Resource
	if err := ctx.db.Where("hash = ?", hash).First(&resource).Error; err != nil {
		return nil, err
	}
	return &resource, nil
}
application_context.MahresourcesContext.ServeResourceByHash method · go · L303-L326 (24 LOC)
application_context/resource_crud_context.go
func (ctx *MahresourcesContext) ServeResourceByHash(w http.ResponseWriter, r *http.Request, hash string) {
	resource, err := ctx.GetResourceByHash(hash)
	if err != nil {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}

	// Get the appropriate filesystem for this resource
	fs, err := ctx.GetFsForStorageLocation(resource.StorageLocation)
	if err != nil {
		http.Error(w, "Storage not found", http.StatusNotFound)
		return
	}

	file, err := fs.Open(resource.GetCleanLocation())
	if err != nil {
		http.Error(w, "File not found", http.StatusNotFound)
		return
	}
	defer file.Close()

	w.Header().Set("Content-Type", resource.ContentType)
	http.ServeContent(w, r, resource.Name, resource.UpdatedAt, file)
}
application_context.uintPtrOrNil function · go · L328-L333 (6 LOC)
application_context/resource_crud_context.go
func uintPtrOrNil(v uint) *uint {
	if v == 0 {
		return nil
	}
	return &v
}
application_context.MahresourcesContext.LoadOrCreateThumbnailForResource method · go · L41-L138 (98 LOC)
application_context/resource_media_context.go
func (ctx *MahresourcesContext) LoadOrCreateThumbnailForResource(
	resourceId, width, height uint,
	httpContext context.Context,
) (*models.Preview, error) {
	// Acquire the ThumbnailGenerationLock for the given resourceId with context support
	if err := ctx.locks.ThumbnailGenerationLock.AcquireContext(httpContext, resourceId); err != nil {
		return nil, fmt.Errorf("failed to acquire thumbnail generation lock: %w", err)
	}
	defer ctx.locks.ThumbnailGenerationLock.Release(resourceId)

	// Ensure width and height do not exceed maximum allowed values
	width = uint(math.Min(constants.MaxThumbWidth, float64(width)))
	height = uint(math.Min(constants.MaxThumbHeight, float64(height)))

	// Attempt to retrieve an existing thumbnail with the specified dimensions
	existingThumbnail, err := ctx.getExistingThumbnail(resourceId, width, height, httpContext)
	if err == nil {
		return &existingThumbnail, nil
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fmt.Errorf("error retrieving ex
application_context.MahresourcesContext.getExistingThumbnail method · go · L145-L159 (15 LOC)
application_context/resource_media_context.go
func (ctx *MahresourcesContext) getExistingThumbnail(
	resourceId, width, height uint,
	httpContext context.Context,
) (models.Preview, error) {
	var thumbnail models.Preview
	err := ctx.db.WithContext(httpContext).
		Where(&models.Preview{
			Width:      width,
			Height:     height,
			ResourceId: &resourceId,
		}).
		Omit(clause.Associations).
		First(&thumbnail).Error
	return thumbnail, err
}
application_context.MahresourcesContext.getResourceForThumbnail method · go · L162-L171 (10 LOC)
application_context/resource_media_context.go
func (ctx *MahresourcesContext) getResourceForThumbnail(
	resourceId uint,
	httpContext context.Context,
) (models.Resource, error) {
	var resource models.Resource
	err := ctx.db.WithContext(httpContext).
		Omit(clause.Associations).
		First(&resource, resourceId).Error
	return resource, err
}
application_context.MahresourcesContext.getOrCreateNullThumbnail method · go · L174-L225 (52 LOC)
application_context/resource_media_context.go
func (ctx *MahresourcesContext) getOrCreateNullThumbnail(
	resource models.Resource,
	fs afero.Fs,
	httpContext context.Context,
) (models.Preview, []byte, error) {
	var nullThumbnail models.Preview
	var fileBytes []byte

	err := ctx.db.WithContext(httpContext).
		Where(&models.Preview{
			Width:      0,
			Height:     0,
			ResourceId: &resource.ID,
		}).
		Omit(clause.Associations).
		First(&nullThumbnail).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {
		// Null thumbnail doesn't exist; attempt to create it from the original image
		name := resource.GetCleanLocation() + constants.ThumbFileSuffix
		file, fopenErr := fs.Open(name)
		if fopenErr != nil {
			return nullThumbnail, fileBytes, nil // Return empty fileBytes; no null thumbnail
		}
		defer file.Close()

		// Read the file bytes
		fileBytes, readErr := io.ReadAll(file)
		if readErr != nil {
			return nullThumbnail, fileBytes, fmt.Errorf("failed to read null thumbnail file: %w", readErr)
		}

		// Initialize nullThumbnail c
application_context.getJPEGQuality function · go · L229-L245 (17 LOC)
application_context/resource_media_context.go
func getJPEGQuality(width, height uint) int {
	maxDim := width
	if height > width {
		maxDim = height
	}

	switch {
	case maxDim <= 100:
		return 70
	case maxDim <= 200:
		return 75
	case maxDim <= 400:
		return 80
	default:
		return 85
	}
}
Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
application_context.MahresourcesContext.generateImageThumbnail method · go · L248-L268 (21 LOC)
application_context/resource_media_context.go
func (ctx *MahresourcesContext) generateImageThumbnail(
	imageData []byte,
	width, height uint,
) ([]byte, error) {
	originalImage, _, err := image.Decode(bytes.NewReader(imageData))
	if err != nil {
		return nil, fmt.Errorf("failed to decode image data: %w", err)
	}

	// Use imaging library for faster, high-quality resize with Lanczos filter
	newImage := imaging.Resize(originalImage, int(width), int(height), imaging.Lanczos)

	// Use adaptive JPEG quality based on dimensions
	quality := getJPEGQuality(width, height)
	var buf bytes.Buffer
	if err := imaging.Encode(&buf, newImage, imaging.JPEG, imaging.JPEGQuality(quality)); err != nil {
		return nil, fmt.Errorf("failed to encode resized image: %w", err)
	}

	return buf.Bytes(), nil
}
application_context.MahresourcesContext.decodeImageWithFallback method · go · L272-L295 (24 LOC)
application_context/resource_media_context.go
func (ctx *MahresourcesContext) decodeImageWithFallback(
	httpContext context.Context,
	file io.ReadSeeker,
) (image.Image, error) {
	// First, try standard Go decoders (PNG, JPEG, GIF, WebP, BMP, TIFF)
	img, _, err := image.Decode(file)
	if err == nil {
		return img, nil
	}

	// Reset file position for fallback attempt
	if _, seekErr := file.Seek(0, io.SeekStart); seekErr != nil {
		return nil, fmt.Errorf("failed to seek file: %w", seekErr)
	}

	// Try ImageMagick as fallback for HEIC, AVIF, and other formats
	img, fallbackErr := ctx.decodeWithImageMagick(httpContext, file)
	if fallbackErr == nil {
		return img, nil
	}

	// Return original error if all decoders fail
	return nil, fmt.Errorf("failed to decode image (tried standard decoders and ImageMagick): %w", err)
}
application_context.truncateStderr function · go · L298-L303 (6 LOC)
application_context/resource_media_context.go
func truncateStderr(stderr string, maxLen int) string {
	if len(stderr) <= maxLen {
		return stderr
	}
	return stderr[:maxLen] + "... (truncated)"
}
‹ prevpage 3 / 16next ›