Update documentation

This commit is contained in:
2024-11-28 21:53:03 +01:00
parent 51ed9e53a4
commit f5d616fe00
13 changed files with 53 additions and 205 deletions

View File

@@ -62,31 +62,17 @@ func NewJWTService(config JWTConfig) (JWTManager, error) {
return &jwtService{config: config}, nil return &jwtService{config: config}, nil
} }
// GenerateAccessToken creates a new access token for a user // GenerateAccessToken creates a new access token for a user with the given userID and role
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// Returns the signed token string or an error
func (s *jwtService) GenerateAccessToken(userID int, role string) (string, error) { func (s *jwtService) GenerateAccessToken(userID int, role string) (string, error) {
return s.generateToken(userID, role, AccessToken, s.config.AccessTokenExpiry) return s.generateToken(userID, role, AccessToken, s.config.AccessTokenExpiry)
} }
// GenerateRefreshToken creates a new refresh token for a user // GenerateRefreshToken creates a new refresh token for a user with the given userID and role
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// Returns the signed token string or an error
func (s *jwtService) GenerateRefreshToken(userID int, role string) (string, error) { func (s *jwtService) GenerateRefreshToken(userID int, role string) (string, error) {
return s.generateToken(userID, role, RefreshToken, s.config.RefreshTokenExpiry) return s.generateToken(userID, role, RefreshToken, s.config.RefreshTokenExpiry)
} }
// generateToken is an internal helper function that creates a new JWT token // generateToken is an internal helper function that creates a new JWT token
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// - tokenType: the type of token (access or refresh)
// - expiry: how long the token should be valid
// Returns the signed token string or an error
func (s *jwtService) generateToken(userID int, role string, tokenType TokenType, expiry time.Duration) (string, error) { func (s *jwtService) generateToken(userID int, role string, tokenType TokenType, expiry time.Duration) (string, error) {
now := time.Now() now := time.Now()
@@ -113,9 +99,6 @@ func (s *jwtService) generateToken(userID int, role string, tokenType TokenType,
} }
// ValidateToken validates and parses a JWT token // ValidateToken validates and parses a JWT token
// Parameters:
// - tokenString: the token to validate
// Returns the token claims if valid, or an error if invalid
func (s *jwtService) ValidateToken(tokenString string) (*Claims, error) { func (s *jwtService) ValidateToken(tokenString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) { token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
// Validate the signing method // Validate the signing method
@@ -136,10 +119,7 @@ func (s *jwtService) ValidateToken(tokenString string) (*Claims, error) {
return nil, fmt.Errorf("invalid token claims") return nil, fmt.Errorf("invalid token claims")
} }
// RefreshAccessToken creates a new access token using a refresh token // RefreshAccessToken creates a new access token using a refreshToken
// Parameters:
// - refreshToken: the refresh token to use
// Returns a new access token if the refresh token is valid, or an error
func (s *jwtService) RefreshAccessToken(refreshToken string) (string, error) { func (s *jwtService) RefreshAccessToken(refreshToken string) (string, error) {
claims, err := s.ValidateToken(refreshToken) claims, err := s.ValidateToken(refreshToken)
if err != nil { if err != nil {

View File

@@ -13,10 +13,6 @@ type Middleware struct {
} }
// NewMiddleware creates a new authentication middleware // NewMiddleware creates a new authentication middleware
// Parameters:
// - jwtManager: the JWT manager to use for token operations
// Returns:
// - *Middleware: the new middleware instance
func NewMiddleware(jwtManager JWTManager) *Middleware { func NewMiddleware(jwtManager JWTManager) *Middleware {
return &Middleware{ return &Middleware{
jwtManager: jwtManager, jwtManager: jwtManager,
@@ -24,10 +20,6 @@ func NewMiddleware(jwtManager JWTManager) *Middleware {
} }
// Authenticate middleware validates JWT tokens and sets user information in context // Authenticate middleware validates JWT tokens and sets user information in context
// Parameters:
// - next: the next handler to call
// Returns:
// - http.Handler: the handler function
func (m *Middleware) Authenticate(next http.Handler) http.Handler { func (m *Middleware) Authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Extract token from Authorization header // Extract token from Authorization header
@@ -69,10 +61,6 @@ func (m *Middleware) Authenticate(next http.Handler) http.Handler {
} }
// RequireRole returns a middleware that ensures the user has the required role // RequireRole returns a middleware that ensures the user has the required role
// Parameters:
// - role: the required role
// Returns:
// - func(http.Handler) http.Handler: the middleware function
func (m *Middleware) RequireRole(role string) func(http.Handler) http.Handler { func (m *Middleware) RequireRole(role string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -92,10 +80,6 @@ func (m *Middleware) RequireRole(role string) func(http.Handler) http.Handler {
} }
// RequireWorkspaceAccess returns a middleware that ensures the user has access to the workspace // RequireWorkspaceAccess returns a middleware that ensures the user has access to the workspace
// Parameters:
// - next: the next handler to call
// Returns:
// - http.Handler: the handler function
func (m *Middleware) RequireWorkspaceAccess(next http.Handler) http.Handler { func (m *Middleware) RequireWorkspaceAccess(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, ok := context.GetRequestContext(w, r) ctx, ok := context.GetRequestContext(w, r)

View File

@@ -15,10 +15,7 @@ type SessionService struct {
jwtManager JWTManager // JWT Manager for token operations jwtManager JWTManager // JWT Manager for token operations
} }
// NewSessionService creates a new session service // NewSessionService creates a new session service with the given database and JWT manager
// Parameters:
// - db: database connection
// - jwtManager: JWT service for token operations
func NewSessionService(db db.SessionStore, jwtManager JWTManager) *SessionService { func NewSessionService(db db.SessionStore, jwtManager JWTManager) *SessionService {
return &SessionService{ return &SessionService{
db: db, db: db,
@@ -26,14 +23,7 @@ func NewSessionService(db db.SessionStore, jwtManager JWTManager) *SessionServic
} }
} }
// CreateSession creates a new user session // CreateSession creates a new user session for a user with the given userID and role
// Parameters:
// - userID: the ID of the user
// - role: the role of the user
// Returns:
// - session: the created session
// - accessToken: a new access token
// - error: any error that occurred
func (s *SessionService) CreateSession(userID int, role string) (*models.Session, string, error) { func (s *SessionService) CreateSession(userID int, role string) (*models.Session, string, error) {
// Generate both access and refresh tokens // Generate both access and refresh tokens
accessToken, err := s.jwtManager.GenerateAccessToken(userID, role) accessToken, err := s.jwtManager.GenerateAccessToken(userID, role)
@@ -69,12 +59,7 @@ func (s *SessionService) CreateSession(userID int, role string) (*models.Session
return session, accessToken, nil return session, accessToken, nil
} }
// RefreshSession creates a new access token using a refresh token // RefreshSession creates a new access token using a refreshToken
// Parameters:
// - refreshToken: the refresh token to use
// Returns:
// - string: a new access token
// - error: any error that occurred
func (s *SessionService) RefreshSession(refreshToken string) (string, error) { func (s *SessionService) RefreshSession(refreshToken string) (string, error) {
// Get session from database first // Get session from database first
session, err := s.db.GetSessionByRefreshToken(refreshToken) session, err := s.db.GetSessionByRefreshToken(refreshToken)
@@ -97,18 +82,12 @@ func (s *SessionService) RefreshSession(refreshToken string) (string, error) {
return s.jwtManager.GenerateAccessToken(claims.UserID, claims.Role) return s.jwtManager.GenerateAccessToken(claims.UserID, claims.Role)
} }
// InvalidateSession removes a session from the database // InvalidateSession removes a session with the given sessionID from the database
// Parameters:
// - sessionID: the ID of the session to invalidate
// Returns:
// - error: any error that occurred
func (s *SessionService) InvalidateSession(sessionID string) error { func (s *SessionService) InvalidateSession(sessionID string) error {
return s.db.DeleteSession(sessionID) return s.db.DeleteSession(sessionID)
} }
// CleanExpiredSessions removes all expired sessions from the database // CleanExpiredSessions removes all expired sessions from the database
// Returns:
// - error: any error that occurred
func (s *SessionService) CleanExpiredSessions() error { func (s *SessionService) CleanExpiredSessions() error {
return s.db.CleanExpiredSessions() return s.db.CleanExpiredSessions()
} }

View File

@@ -38,7 +38,7 @@ func (db *database) CreateUser(user *models.User) (*models.User, error) {
UserID: user.ID, UserID: user.ID,
Name: "Main", Name: "Main",
} }
defaultWorkspace.GetDefaultSettings() // Initialize default settings defaultWorkspace.SetDefaultSettings() // Initialize default settings
// Create workspace with settings // Create workspace with settings
err = db.createWorkspaceTx(tx, defaultWorkspace) err = db.createWorkspaceTx(tx, defaultWorkspace)

View File

@@ -10,7 +10,7 @@ import (
func (db *database) CreateWorkspace(workspace *models.Workspace) error { func (db *database) CreateWorkspace(workspace *models.Workspace) error {
// Set default settings if not provided // Set default settings if not provided
if workspace.Theme == "" { if workspace.Theme == "" {
workspace.GetDefaultSettings() workspace.SetDefaultSettings()
} }
// Encrypt token if present // Encrypt token if present

View File

@@ -77,7 +77,7 @@ func TestWorkspaceOperations(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
if tc.workspace.Theme == "" { if tc.workspace.Theme == "" {
tc.workspace.GetDefaultSettings() tc.workspace.SetDefaultSettings()
} }
err := database.CreateWorkspace(tc.workspace) err := database.CreateWorkspace(tc.workspace)
@@ -117,7 +117,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID, UserID: user.ID,
Name: "Get By ID Workspace", Name: "Get By ID Workspace",
} }
workspace.GetDefaultSettings() workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil { if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err) t.Fatalf("failed to create test workspace: %v", err)
} }
@@ -167,7 +167,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID, UserID: user.ID,
Name: "Get By Name Workspace", Name: "Get By Name Workspace",
} }
workspace.GetDefaultSettings() workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil { if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err) t.Fatalf("failed to create test workspace: %v", err)
} }
@@ -229,7 +229,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID, UserID: user.ID,
Name: "Update Workspace", Name: "Update Workspace",
} }
workspace.GetDefaultSettings() workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil { if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err) t.Fatalf("failed to create test workspace: %v", err)
} }
@@ -272,7 +272,7 @@ func TestWorkspaceOperations(t *testing.T) {
} }
for _, w := range testWorkspaces { for _, w := range testWorkspaces {
w.GetDefaultSettings() w.SetDefaultSettings()
if err := database.CreateWorkspace(w); err != nil { if err := database.CreateWorkspace(w); err != nil {
t.Fatalf("failed to create test workspace: %v", err) t.Fatalf("failed to create test workspace: %v", err)
} }
@@ -314,7 +314,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID, UserID: user.ID,
Name: "Last File Workspace", Name: "Last File Workspace",
} }
workspace.GetDefaultSettings() workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil { if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err) t.Fatalf("failed to create test workspace: %v", err)
} }
@@ -369,7 +369,7 @@ func TestWorkspaceOperations(t *testing.T) {
UserID: user.ID, UserID: user.ID,
Name: "Delete Workspace", Name: "Delete Workspace",
} }
workspace.GetDefaultSettings() workspace.SetDefaultSettings()
if err := database.CreateWorkspace(workspace); err != nil { if err := database.CreateWorkspace(workspace); err != nil {
t.Fatalf("failed to create test workspace: %v", err) t.Fatalf("failed to create test workspace: %v", err)
} }

View File

@@ -33,14 +33,7 @@ type client struct {
repo *git.Repository repo *git.Repository
} }
// New creates a new Client instance // New creates a new git Client instance
// Parameters:
// - url: the URL of the Git repository
// - username: the username for the Git repository
// - token: the access token for the Git repository
// - workDir: the local directory to clone the repository to
// Returns:
// - Client: the Git client
func New(url, username, token, workDir string) Client { func New(url, username, token, workDir string) Client {
return &client{ return &client{
Config: Config{ Config: Config{
@@ -53,8 +46,6 @@ func New(url, username, token, workDir string) Client {
} }
// Clone clones the Git repository to the local directory // Clone clones the Git repository to the local directory
// Returns:
// - error: any error that occurred during cloning
func (c *client) Clone() error { func (c *client) Clone() error {
auth := &http.BasicAuth{ auth := &http.BasicAuth{
Username: c.Username, Username: c.Username,
@@ -76,8 +67,6 @@ func (c *client) Clone() error {
} }
// Pull pulls the latest changes from the remote repository // Pull pulls the latest changes from the remote repository
// Returns:
// - error: any error that occurred during pulling
func (c *client) Pull() error { func (c *client) Pull() error {
if c.repo == nil { if c.repo == nil {
return fmt.Errorf("repository not initialized") return fmt.Errorf("repository not initialized")
@@ -105,11 +94,7 @@ func (c *client) Pull() error {
return nil return nil
} }
// Commit commits the changes in the repository // Commit commits the changes in the repository with the given message
// Parameters:
// - message: the commit message
// Returns:
// - error: any error that occurred during committing
func (c *client) Commit(message string) error { func (c *client) Commit(message string) error {
if c.repo == nil { if c.repo == nil {
return fmt.Errorf("repository not initialized") return fmt.Errorf("repository not initialized")
@@ -134,8 +119,6 @@ func (c *client) Commit(message string) error {
} }
// Push pushes the changes to the remote repository // Push pushes the changes to the remote repository
// Returns:
// - error: any error that occurred during pushing
func (c *client) Push() error { func (c *client) Push() error {
if c.repo == nil { if c.repo == nil {
return fmt.Errorf("repository not initialized") return fmt.Errorf("repository not initialized")
@@ -158,9 +141,7 @@ func (c *client) Push() error {
return nil return nil
} }
// EnsureRepo ensures the local repository is up-to-date // EnsureRepo ensures the local repository is cloned and up-to-date
// Returns:
// - error: any error that occurred during the operation
func (c *client) EnsureRepo() error { func (c *client) EnsureRepo() error {
if _, err := os.Stat(filepath.Join(c.WorkDir, ".git")); os.IsNotExist(err) { if _, err := os.Stat(filepath.Join(c.WorkDir, ".git")); os.IsNotExist(err) {
return c.Clone() return c.Clone()

View File

@@ -8,14 +8,17 @@ import (
var validate = validator.New() var validate = validator.New()
// UserRole represents the role of a user in the system
type UserRole string type UserRole string
// User roles
const ( const (
RoleAdmin UserRole = "admin" RoleAdmin UserRole = "admin"
RoleEditor UserRole = "editor" RoleEditor UserRole = "editor"
RoleViewer UserRole = "viewer" RoleViewer UserRole = "viewer"
) )
// User represents a user in the system
type User struct { type User struct {
ID int `json:"id" validate:"required,min=1"` ID int `json:"id" validate:"required,min=1"`
Email string `json:"email" validate:"required,email"` Email string `json:"email" validate:"required,email"`
@@ -26,6 +29,7 @@ type User struct {
LastWorkspaceID int `json:"lastWorkspaceId"` LastWorkspaceID int `json:"lastWorkspaceId"`
} }
// Validate validates the user struct
func (u *User) Validate() error { func (u *User) Validate() error {
return validate.Struct(u) return validate.Struct(u)
} }

View File

@@ -4,6 +4,7 @@ import (
"time" "time"
) )
// Workspace represents a user's workspace in the system
type Workspace struct { type Workspace struct {
ID int `json:"id" validate:"required,min=1"` ID int `json:"id" validate:"required,min=1"`
UserID int `json:"userId" validate:"required,min=1"` UserID int `json:"userId" validate:"required,min=1"`
@@ -23,11 +24,13 @@ type Workspace struct {
GitCommitMsgTemplate string `json:"gitCommitMsgTemplate"` GitCommitMsgTemplate string `json:"gitCommitMsgTemplate"`
} }
// Validate validates the workspace struct
func (w *Workspace) Validate() error { func (w *Workspace) Validate() error {
return validate.Struct(w) return validate.Struct(w)
} }
func (w *Workspace) GetDefaultSettings() { // SetDefaultSettings sets the default settings for the workspace
func (w *Workspace) SetDefaultSettings() {
w.Theme = "light" w.Theme = "light"
w.AutoSave = false w.AutoSave = false
w.ShowHiddenFiles = false w.ShowHiddenFiles = false

View File

@@ -30,12 +30,7 @@ type FileNode struct {
} }
// ListFilesRecursively returns a list of all files in the workspace directory and its subdirectories. // ListFilesRecursively returns a list of all files in the workspace directory and its subdirectories.
// Parameters: // Workspace is identified by the given userID and workspaceID.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to list files in
// Returns:
// - nodes: a list of files and directories in the workspace
// - error: any error that occurred during listing
func (s *Service) ListFilesRecursively(userID, workspaceID int) ([]FileNode, error) { func (s *Service) ListFilesRecursively(userID, workspaceID int) ([]FileNode, error) {
workspacePath := s.GetWorkspacePath(userID, workspaceID) workspacePath := s.GetWorkspacePath(userID, workspaceID)
return s.walkDirectory(workspacePath, "") return s.walkDirectory(workspacePath, "")
@@ -106,13 +101,8 @@ func (s *Service) walkDirectory(dir, prefix string) ([]FileNode, error) {
} }
// FindFileByName returns a list of file paths that match the given filename. // FindFileByName returns a list of file paths that match the given filename.
// Parameters: // Files are searched recursively in the workspace directory and its subdirectories.
// - userID: the ID of the user who owns the workspace // Workspace is identified by the given userID and workspaceID.
// - workspaceID: the ID of the workspace to search for the file
// - filename: the name of the file to search for
// Returns:
// - foundPaths: a list of file paths that match the filename
// - error: any error that occurred during the search
func (s *Service) FindFileByName(userID, workspaceID int, filename string) ([]string, error) { func (s *Service) FindFileByName(userID, workspaceID int, filename string) ([]string, error) {
var foundPaths []string var foundPaths []string
workspacePath := s.GetWorkspacePath(userID, workspaceID) workspacePath := s.GetWorkspacePath(userID, workspaceID)
@@ -144,14 +134,8 @@ func (s *Service) FindFileByName(userID, workspaceID int, filename string) ([]st
return foundPaths, nil return foundPaths, nil
} }
// GetFileContent returns the content of the file at the given path. // GetFileContent returns the content of the file at the given filePath.
// Parameters: // Path must be a relative path within the workspace directory given by userID and workspaceID.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to get the file from
// - filePath: the path of the file to get
// Returns:
// - content: the content of the file
// - error: any error that occurred during reading
func (s *Service) GetFileContent(userID, workspaceID int, filePath string) ([]byte, error) { func (s *Service) GetFileContent(userID, workspaceID int, filePath string) ([]byte, error) {
fullPath, err := s.ValidatePath(userID, workspaceID, filePath) fullPath, err := s.ValidatePath(userID, workspaceID, filePath)
if err != nil { if err != nil {
@@ -160,14 +144,8 @@ func (s *Service) GetFileContent(userID, workspaceID int, filePath string) ([]by
return s.fs.ReadFile(fullPath) return s.fs.ReadFile(fullPath)
} }
// SaveFile writes the content to the file at the given path. // SaveFile writes the content to the file at the given filePath.
// Parameters: // Path must be a relative path within the workspace directory given by userID and workspaceID.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to save the file to
// - filePath: the path of the file to save
// - content: the content to write to the file
// Returns:
// - error: any error that occurred during saving
func (s *Service) SaveFile(userID, workspaceID int, filePath string, content []byte) error { func (s *Service) SaveFile(userID, workspaceID int, filePath string, content []byte) error {
fullPath, err := s.ValidatePath(userID, workspaceID, filePath) fullPath, err := s.ValidatePath(userID, workspaceID, filePath)
if err != nil { if err != nil {
@@ -182,13 +160,8 @@ func (s *Service) SaveFile(userID, workspaceID int, filePath string, content []b
return s.fs.WriteFile(fullPath, content, 0644) return s.fs.WriteFile(fullPath, content, 0644)
} }
// DeleteFile deletes the file at the given path. // DeleteFile deletes the file at the given filePath.
// Parameters: // Path must be a relative path within the workspace directory given by userID and workspaceID.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to delete the file from
// - filePath: the path of the file to delete
// Returns:
// - error: any error that occurred during deletion
func (s *Service) DeleteFile(userID, workspaceID int, filePath string) error { func (s *Service) DeleteFile(userID, workspaceID int, filePath string) error {
fullPath, err := s.ValidatePath(userID, workspaceID, filePath) fullPath, err := s.ValidatePath(userID, workspaceID, filePath)
if err != nil { if err != nil {
@@ -204,12 +177,7 @@ type FileCountStats struct {
} }
// GetFileStats returns the total number of files and related statistics in a workspace // GetFileStats returns the total number of files and related statistics in a workspace
// Parameters: // Workspace is identified by the given userID and workspaceID
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to count files in
// Returns:
// - result: statistics about the files in the workspace
// - error: any error that occurred during counting
func (s *Service) GetFileStats(userID, workspaceID int) (*FileCountStats, error) { func (s *Service) GetFileStats(userID, workspaceID int) (*FileCountStats, error) {
workspacePath := s.GetWorkspacePath(userID, workspaceID) workspacePath := s.GetWorkspacePath(userID, workspaceID)
@@ -223,8 +191,6 @@ func (s *Service) GetFileStats(userID, workspaceID int) (*FileCountStats, error)
} }
// GetTotalFileStats returns the total file statistics for the storage. // GetTotalFileStats returns the total file statistics for the storage.
// Returns:
// - result: statistics about the files in the storage
func (s *Service) GetTotalFileStats() (*FileCountStats, error) { func (s *Service) GetTotalFileStats() (*FileCountStats, error) {
return s.countFilesInPath(s.RootDir) return s.countFilesInPath(s.RootDir)
} }

View File

@@ -13,15 +13,8 @@ type RepositoryManager interface {
Pull(userID, workspaceID int) error Pull(userID, workspaceID int) error
} }
// SetupGitRepo sets up a Git repository for the given user and workspace IDs. // SetupGitRepo sets up a Git repository for the given userID and workspaceID.
// Parameters: // The repository is cloned from the given gitURL using the given gitUser and gitToken.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to set up the Git repository for
// - gitURL: the URL of the Git repository
// - gitUser: the username for the Git repository
// - gitToken: the access token for the Git repository
// Returns:
// - error: any error that occurred during setup
func (s *Service) SetupGitRepo(userID, workspaceID int, gitURL, gitUser, gitToken string) error { func (s *Service) SetupGitRepo(userID, workspaceID int, gitURL, gitUser, gitToken string) error {
workspacePath := s.GetWorkspacePath(userID, workspaceID) workspacePath := s.GetWorkspacePath(userID, workspaceID)
if _, ok := s.GitRepos[userID]; !ok { if _, ok := s.GitRepos[userID]; !ok {
@@ -31,10 +24,7 @@ func (s *Service) SetupGitRepo(userID, workspaceID int, gitURL, gitUser, gitToke
return s.GitRepos[userID][workspaceID].EnsureRepo() return s.GitRepos[userID][workspaceID].EnsureRepo()
} }
// DisableGitRepo disables the Git repository for the given user and workspace IDs. // DisableGitRepo disables the Git repository for the given userID and workspaceID.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to disable the Git repository for
func (s *Service) DisableGitRepo(userID, workspaceID int) { func (s *Service) DisableGitRepo(userID, workspaceID int) {
if userRepos, ok := s.GitRepos[userID]; ok { if userRepos, ok := s.GitRepos[userID]; ok {
delete(userRepos, workspaceID) delete(userRepos, workspaceID)
@@ -44,13 +34,8 @@ func (s *Service) DisableGitRepo(userID, workspaceID int) {
} }
} }
// StageCommitAndPush stages, commits, and pushes the changes to the Git repository. // StageCommitAndPush stages, commit with the message, and pushes the changes to the Git repository.
// Parameters: // The git repository belongs to the given userID and is associated with the given workspaceID.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to commit and push
// - message: the commit message
// Returns:
// - error: any error that occurred during the operation
func (s *Service) StageCommitAndPush(userID, workspaceID int, message string) error { func (s *Service) StageCommitAndPush(userID, workspaceID int, message string) error {
repo, ok := s.getGitRepo(userID, workspaceID) repo, ok := s.getGitRepo(userID, workspaceID)
if !ok { if !ok {
@@ -65,11 +50,7 @@ func (s *Service) StageCommitAndPush(userID, workspaceID int, message string) er
} }
// Pull pulls the changes from the remote Git repository. // Pull pulls the changes from the remote Git repository.
// Parameters: // The git repository belongs to the given userID and is associated with the given workspaceID.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to pull changes for
// Returns:
// - error: any error that occurred during the operation
func (s *Service) Pull(userID, workspaceID int) error { func (s *Service) Pull(userID, workspaceID int) error {
repo, ok := s.getGitRepo(userID, workspaceID) repo, ok := s.getGitRepo(userID, workspaceID)
if !ok { if !ok {

View File

@@ -25,11 +25,7 @@ type Options struct {
NewGitClient func(url, user, token, path string) git.Client NewGitClient func(url, user, token, path string) git.Client
} }
// NewService creates a new Storage instance. // NewService creates a new Storage instance with the default options and the given rootDir root directory.
// Parameters:
// - rootDir: the root directory for the storage
// Returns:
// - result: the new Storage instance
func NewService(rootDir string) *Service { func NewService(rootDir string) *Service {
return NewServiceWithOptions(rootDir, Options{ return NewServiceWithOptions(rootDir, Options{
Fs: &osFS{}, Fs: &osFS{},
@@ -37,16 +33,11 @@ func NewService(rootDir string) *Service {
}) })
} }
// NewServiceWithOptions creates a new Storage instance with the given options. // NewServiceWithOptions creates a new Storage instance with the given options and the given rootDir root directory.
// Parameters: func NewServiceWithOptions(rootDir string, options Options) *Service {
// - rootDir: the root directory for the storage
// - opts: the options for the storage service
// Returns:
// - result: the new Storage instance
func NewServiceWithOptions(rootDir string, opts Options) *Service {
return &Service{ return &Service{
fs: opts.Fs, fs: options.Fs,
newGitClient: opts.NewGitClient, newGitClient: options.NewGitClient,
RootDir: rootDir, RootDir: rootDir,
GitRepos: make(map[int]map[int]git.Client), GitRepos: make(map[int]map[int]git.Client),
} }

View File

@@ -14,14 +14,8 @@ type WorkspaceManager interface {
DeleteUserWorkspace(userID, workspaceID int) error DeleteUserWorkspace(userID, workspaceID int) error
} }
// ValidatePath validates the given path and returns the cleaned path if it is valid. // ValidatePath validates the if the given path is valid within the workspace directory.
// Parameters: // Workspace directory is defined as the directory for the given userID and workspaceID.
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to validate the path for
// - path: the path to validate
// Returns:
// - result: the cleaned path if it is valid
// - error: any error that occurred during validation
func (s *Service) ValidatePath(userID, workspaceID int, path string) (string, error) { func (s *Service) ValidatePath(userID, workspaceID int, path string) (string, error) {
workspacePath := s.GetWorkspacePath(userID, workspaceID) workspacePath := s.GetWorkspacePath(userID, workspaceID)
@@ -42,22 +36,12 @@ func (s *Service) ValidatePath(userID, workspaceID int, path string) (string, er
return cleanPath, nil return cleanPath, nil
} }
// GetWorkspacePath returns the path to the workspace directory for the given user and workspace IDs. // GetWorkspacePath returns the path to the workspace directory for the given userID and workspaceID.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace
// Returns:
// - result: the path to the workspace directory
func (s *Service) GetWorkspacePath(userID, workspaceID int) string { func (s *Service) GetWorkspacePath(userID, workspaceID int) string {
return filepath.Join(s.RootDir, fmt.Sprintf("%d", userID), fmt.Sprintf("%d", workspaceID)) return filepath.Join(s.RootDir, fmt.Sprintf("%d", userID), fmt.Sprintf("%d", workspaceID))
} }
// InitializeUserWorkspace creates the workspace directory for the given user and workspace IDs. // InitializeUserWorkspace creates the workspace directory for the given userID and workspaceID.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to initialize
// Returns:
// - error: any error that occurred during the operation
func (s *Service) InitializeUserWorkspace(userID, workspaceID int) error { func (s *Service) InitializeUserWorkspace(userID, workspaceID int) error {
workspacePath := s.GetWorkspacePath(userID, workspaceID) workspacePath := s.GetWorkspacePath(userID, workspaceID)
err := s.fs.MkdirAll(workspacePath, 0755) err := s.fs.MkdirAll(workspacePath, 0755)
@@ -68,12 +52,7 @@ func (s *Service) InitializeUserWorkspace(userID, workspaceID int) error {
return nil return nil
} }
// DeleteUserWorkspace deletes the workspace directory for the given user and workspace IDs. // DeleteUserWorkspace deletes the workspace directory for the given userID and workspaceID.
// Parameters:
// - userID: the ID of the user who owns the workspace
// - workspaceID: the ID of the workspace to delete
// Returns:
// - error: any error that occurred during the operation
func (s *Service) DeleteUserWorkspace(userID, workspaceID int) error { func (s *Service) DeleteUserWorkspace(userID, workspaceID int) error {
workspacePath := s.GetWorkspacePath(userID, workspaceID) workspacePath := s.GetWorkspacePath(userID, workspaceID)
err := s.fs.RemoveAll(workspacePath) err := s.fs.RemoveAll(workspacePath)