-
-
Notifications
You must be signed in to change notification settings - Fork 4
Feat/init script #154
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
liamb13
wants to merge
5
commits into
hex-digital:main
Choose a base branch
from
liamb13:feat/init-script
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat/init script #154
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
78d972e
feat: adds init script
liamb13 837c420
feat: require approval for sample data
liamb13 ae52477
Update apps/sanity/config/init.ts
liamb13 5431d54
Update apps/sanity/config/init.ts
liamb13 9a4fefa
chore: fix sanity init function, add jsdocs and clean up code
liamb13 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| name: Protect Sample Data | ||
|
|
||
| on: | ||
| pull_request: | ||
| types: [opened, synchronize, reopened] | ||
| paths: | ||
| - 'apps/sanity/sample-data.tar.gz' | ||
| - '.github/workflows/protect-sample-data.yml' | ||
|
|
||
| # Allows triggering this workflow from GitHub UI | ||
| workflow_dispatch: | ||
|
|
||
| permissions: | ||
| contents: read | ||
| pull-requests: write | ||
|
|
||
| jobs: | ||
| check-sample-data: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - name: Checkout 🛎 | ||
| uses: actions/checkout@v4 | ||
| with: | ||
| fetch-depth: 0 | ||
|
|
||
| - name: Check sample data modifications 🔒 | ||
| id: check-sample-data | ||
| run: | | ||
| # Get the list of files changed in the PR | ||
| CHANGED_FILES=$(git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.sha }}) | ||
|
|
||
| # Check if sample-data.tar.gz was modified | ||
| if echo "$CHANGED_FILES" | grep -q "apps/sanity/sample-data.tar.gz"; then | ||
| # Get the author of the PR | ||
| PR_AUTHOR="${{ github.event.pull_request.user.login }}" | ||
| # Get the repository owner | ||
| REPO_OWNER="${{ github.repository_owner }}" | ||
|
|
||
| if [ "$PR_AUTHOR" != "$REPO_OWNER" ]; then | ||
| echo "::error::Sample data file modification requires approval from the repository owner." | ||
| echo "::error::Please contact @$REPO_OWNER for approval." | ||
| exit 1 | ||
| else | ||
| echo "::warning::Sample data file modified by repository owner. Proceeding with caution." | ||
| fi | ||
| fi | ||
|
|
||
| - name: Comment on PR 💬 | ||
| if: failure() | ||
| uses: actions/github-script@v7 | ||
| with: | ||
| script: | | ||
| github.rest.issues.createComment({ | ||
| issue_number: context.issue.number, | ||
| owner: context.repo.owner, | ||
| repo: context.repo.repo, | ||
| body: `⚠️ **Sample Data Protection**\n\nThis PR modifies the sample data file (\`apps/sanity/sample-data.tar.gz\`). For security reasons, only the repository owner can modify this file.\n\nPlease contact @${{ github.repository_owner }} for approval.` | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| import { spawn } from 'child_process'; | ||
| import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'fs'; | ||
| import { join } from 'path'; | ||
| import { fileURLToPath } from 'url'; | ||
|
|
||
| const __dirname = fileURLToPath(new URL('.', import.meta.url)); | ||
| const rootDir = join(__dirname, '..'); | ||
| const webDir = join(rootDir, '..', 'web'); | ||
|
|
||
| async function main() { | ||
| try { | ||
| console.log('🚀 Initializing Sanity project...'); | ||
|
|
||
| // Run sanity init | ||
| console.log('\n📦 Running Sanity initialization...'); | ||
| console.log('Please follow the prompts to set up your Sanity project...'); | ||
|
|
||
| // Run Sanity init with full interactivity but capture stdout | ||
| const sanityInit = spawn('npx', ['sanity', 'init', '--bare'], { | ||
| stdio: ['inherit', 'pipe', 'inherit'], | ||
| cwd: rootDir, | ||
| env: { | ||
| ...process.env, | ||
| FORCE_COLOR: '1', | ||
| CI: 'false', | ||
| TERM: process.env.TERM || 'xterm-256color', | ||
| }, | ||
| }); | ||
|
|
||
| let output = ''; | ||
| sanityInit.stdout.on('data', (data) => { | ||
| const text = data.toString(); | ||
| output = text; | ||
|
|
||
| // Remove the first line of the project selection prompt | ||
| if (text.includes('Create new project') && !text.includes('(Use arrow keys)')) { | ||
| let cleanedText = text.replace( | ||
| '\x1B[32m?\x1B[39m \x1B[1mCreate a new project or select an existing one\x1B[22m\x1B[0m \x1B[0m\n', | ||
| '', | ||
| ); | ||
| console.log(cleanedText); | ||
| return; | ||
| } | ||
|
|
||
| if (text.includes('Select dataset to use') && !text.includes('(Use arrow keys)')) { | ||
| let cleanedText = text.replace( | ||
liamb13 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| '\x1B[32m?\x1B[39m \x1B[1mSelect dataset to use\x1B[22m\x1B[0m \x1B[0m\n', | ||
| '', | ||
| ); | ||
| console.log(cleanedText); | ||
| return; | ||
| } | ||
|
|
||
| console.log(text); | ||
| }); | ||
|
|
||
| await new Promise((resolve, reject) => { | ||
| sanityInit.on('close', (code) => { | ||
| if (code === 0) { | ||
| resolve(true); | ||
| } else { | ||
| reject(new Error(`Sanity init failed with code ${code}`)); | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| console.log('\n✅ Sanity initialization complete!'); | ||
|
|
||
| // Extract project details from output | ||
| const projectIdMatch = output.match(/Project ID:\s*\x1B\[36m([^\s]+)\x1B\[39m/); | ||
| const datasetMatch = output.match(/Dataset:\s*\x1B\[36m([^\s]+)\x1B\[39m/); | ||
|
|
||
| if (!projectIdMatch || !datasetMatch) { | ||
| throw new Error('Could not find project ID or dataset in Sanity CLI output'); | ||
| } | ||
|
|
||
| const projectId = projectIdMatch[1].trim(); | ||
| const dataset = datasetMatch[1].trim(); | ||
|
|
||
| console.log(`Project ID: ${projectId}`); | ||
| console.log(`Dataset: ${dataset}`); | ||
|
|
||
| // Update environment files | ||
| console.log('\n📝 Setting up environment variables...'); | ||
|
|
||
| // Sanity app environment files | ||
| const sanityEnvExamplePath = join(rootDir, '.env.example'); | ||
| const sanityEnvLocalPath = join(rootDir, '.env.local'); | ||
|
|
||
| // Web app environment files | ||
| const webEnvExamplePath = join(webDir, '.env.example'); | ||
| const webEnvLocalPath = join(webDir, '.env.local'); | ||
|
|
||
| // Sanity app environment setup | ||
| if (existsSync(sanityEnvExamplePath)) { | ||
| copyFileSync(sanityEnvExamplePath, sanityEnvLocalPath); | ||
| console.log('✓ Copied Sanity .env.example to .env.local'); | ||
| } else { | ||
| console.log('⚠️ No Sanity .env.example found, creating new environment file'); | ||
| } | ||
|
|
||
| // Web app environment setup | ||
| if (existsSync(webEnvExamplePath)) { | ||
| copyFileSync(webEnvExamplePath, webEnvLocalPath); | ||
| console.log('✓ Copied Web .env.example to .env.local'); | ||
| } else { | ||
| console.log('⚠️ No Web .env.example found, creating new environment file'); | ||
| } | ||
|
|
||
| // Update Sanity app environment file | ||
| let sanityEnvLocalContent = readFileSync(sanityEnvLocalPath, 'utf-8'); | ||
|
|
||
| // Update Sanity variables | ||
| sanityEnvLocalContent = sanityEnvLocalContent | ||
| .replace( | ||
| /SANITY_STUDIO_SANITY_PROJECT_ID=.*\n?/, | ||
| `SANITY_STUDIO_SANITY_PROJECT_ID=${projectId}\n`, | ||
| ) | ||
| .replace( | ||
| /SANITY_STUDIO_SANITY_DATASET=.*\n?/, | ||
| `SANITY_STUDIO_SANITY_DATASET=${dataset}\n`, | ||
| ); | ||
|
|
||
| writeFileSync(sanityEnvLocalPath, sanityEnvLocalContent.trim() + '\n'); | ||
|
|
||
| // Update Web app environment file | ||
| let webEnvLocalContent = readFileSync(webEnvLocalPath, 'utf-8'); | ||
|
|
||
| // Update Web variables | ||
| webEnvLocalContent = webEnvLocalContent | ||
| .replace( | ||
| /NEXT_PUBLIC_SANITY_PROJECT_ID=.*\n?/, | ||
| `NEXT_PUBLIC_SANITY_PROJECT_ID=${projectId}\n`, | ||
| ) | ||
| .replace(/NEXT_PUBLIC_SANITY_DATASET=.*\n?/, `NEXT_PUBLIC_SANITY_DATASET=${dataset}\n`); | ||
|
|
||
| writeFileSync(webEnvLocalPath, webEnvLocalContent.trim() + '\n'); | ||
|
|
||
| console.log('\n✅ Environment files updated successfully!'); | ||
|
|
||
| // Check for sample data | ||
| const sampleDataPath = join(rootDir, 'sample-data.tar.gz'); | ||
| if (existsSync(sampleDataPath)) { | ||
| console.log('\n📦 Found sample data! Would you like to import it?'); | ||
| console.log('This will populate your Sanity dataset with sample content.'); | ||
|
|
||
| // Prompt user for import | ||
| const { execSync } = await import('child_process'); | ||
| const readline = await import('readline'); | ||
| const rl = readline.createInterface({ | ||
| input: process.stdin, | ||
| output: process.stdout, | ||
| }); | ||
|
|
||
| const answer = await new Promise<string>((resolve) => { | ||
| rl.question('Import sample data? (y/N): ', resolve); | ||
| }); | ||
| rl.close(); | ||
|
|
||
| if (answer.toLowerCase() === 'y') { | ||
| console.log('\n📥 Importing sample data...'); | ||
| try { | ||
| execSync(`npx sanity dataset import sample-data.tar.gz ${dataset}`, { | ||
| stdio: 'inherit', | ||
| cwd: rootDir, | ||
| }); | ||
| console.log('✅ Sample data imported successfully!'); | ||
| } catch (error) { | ||
| console.error('❌ Error importing sample data:', error); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| console.log('\n🎉 Sanity project initialized successfully!'); | ||
| console.log('\nNext steps:'); | ||
| console.log('1. Start the development server: pnpm g:dev'); | ||
| console.log('2. Open the Sanity Studio: http://localhost:3333'); | ||
| console.log('3. Open the Next.js app: http://localhost:3000'); | ||
| if (existsSync(sampleDataPath)) { | ||
| console.log('4. Optionally import sample data using the command above'); | ||
| } | ||
| } catch (error) { | ||
| console.error('❌ Error during initialization:', error); | ||
| process.exit(1); | ||
| } | ||
| } | ||
|
|
||
| main(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.