Home > front end >  Although seemingly correct Syntax .gitignore File is ignored
Although seemingly correct Syntax .gitignore File is ignored

Time:10-28

I have written some powershell code, since I wanted to achive two things. The first one was to organize my gists and the second one to learn ps1 script syntax. Until now I guess I've managed some impressive things on one hand, on the other I got stuck...

I read lots of interesting and sophisticated articles on git and earlier on I also used .gitignore files quite successfully.

Now this particular script does EVERYTIME Ignore the .gitignore seamingly not dependend on what im doing.

May somebody of you help me busting this mystery why this script always ignores my gitignore - it sucks that everytime on the first hand it uploads itself everywhere (which is the reason why it writes itself to the .gitignore in line: 40 ) and even more it gets wierd if everytime the node_modules where uploaded too

(testing this script on a freshly generated npx create-react-app testapp in the apps root folder)

By the way, to make things easier I also cleaned the cache with git rm -r --cached . in line 88 before the git add . this also does not work

Filename : git-create-repo.ps1

Sourcecode:

$workdir = Convert-Path $pwd

$gituser = "l00tz1ffer"
$gitserver = "lootziffers-welt.de"
$defaultRemoteName = "origin"
$targetBranchName = "master"

$gitHubExists = 0

$workDirName = $workdir.Substring(($workdir.LastIndexOf("\")   1), ($workdir.Length - 1 ) - $workdir.LastIndexOf("\"))

$git_dir_string = $workDirName   ".git"
echo $workDirName



git remote -v | Out-File -FilePath remotes.temp -Encoding utf8 -Append
$File = 'remotes.temp'

foreach ($line in Get-Content $File) {
    $remoteListingLine = $line
    $remoteHostName = $remoteListingLine.Substring(($remoteListingLine.IndexOf("@")   1), ($remoteListingLine.LastIndexOf(":") - 1 ) - $remoteListingLine.IndexOf("@"))
    echo $remoteHostName
    if ($remoteHostName -contains "github.com") {
        echo "GitHub Repo found"
        $remoteListingLine = $remoteListingLine -replace $defaultRemoteName, "github"
        echo "Renaming properly ..."
        echo $remoteListingLine

        git remote rename $defaultRemoteName "github"
        $gitHubExists = 1

    }

}
Remove-Item 'remotes.temp'



if (-not (Test-Path -Path .gitignore)) {
    New-Item -Path '.gitignore' -ItemType File
}


If ( $workDirName -ne "git-create-repo" -and $workDirName -ne "git-create-repo.git") {
    $File = '.gitignore'

    foreach ($line in Get-Content $File) {
        if (-not (Test-Path -Path new.gitignore)) {
            New-Item -Path 'new.gitignore' -ItemType File
        }

        echo ".gitignore enthält folgenden Wert: $line" 
        if ($line -contains "git-create-repo.ps1") {
            echo "Duplicate entry found, Removing it"
        }
        elseif ($line.Length -eq 0) {
            echo "Empty Line Found in .gitignore -> Removing it"
        }
        elseif ($line -contains $null) {
            echo "Empty Line Found in .gitignore -> Removing it"
        }
        else {
            line | Out-File -FilePath new.gitignore -Encoding utf8 -Append
 
        }
    }
    
    Remove-Item '.gitignore'
    Rename-Item 'new.gitignore' '.gitignore'
    "git-create-repo.ps1" >> | Out-File -FilePath .gitignore -Encoding utf8 -Append

}

Start-Sleep -Seconds 3


git remote rm $defaultRemoteName
git branch -mv main $targetBranchName


ssh git@$gitserver "cd  $gituser && mkdir $git_dir_string && cd $git_dir_string && git init --bare"


#if (Test-Path -Path '.git' -PathType Container) {
git init
echo "Lokales Repo wurde Initialisiert"

git rm -r --cached .
git add .\.gitignore

$timestamp = (get-date).ToString('G')
git commit -m "Autogenerated Commit from ${[System.Environment]::UserName} -> Zeit: $timestamp"
echo "Autogenerated Commit -> Zeit: $timestamp"
    
git rm -r --cached .
git add .
echo "Dateien wurden zum Lokalen Repository hinzugefuegt"
#}


$timestamp = (get-date).ToString('G')
git commit -m "Autogenerated Commit from ${[System.Environment]::UserName} -> Zeit: $timestamp"
echo "Autogenerated Commit -> Zeit: $timestamp"


$git_repo_string = "[email protected]:"   $gituser   "/"   $workDirName   ".git"
echo "Der Verwendete Remote Git Repo string lautet: $git_repo_string" 

git remote add $defaultRemoteName $git_repo_string
git push $defaultRemoteName $targetBranchName
if ($gitHubExists -eq 1) {
    git push github $targetBranchName
}

 

scp git@${gitserver}:${gituser}/repos.txt repos.txt
if (-not (Test-Path -Path .gitignore)) {
    New-Item -Path 'repos.txt' -ItemType File
}
$File = "repos.txt"
foreach ($line in Get-Content $File) {
    echo "repos.txt enthält folgenden Wert: $line" 
    if ($line -contains $git_repo_string) {
        echo "Duplicate entry found, Removing it"
    }
    elseif ($line.Length -eq 0) {
        echo "Empty Line Found in .gitignore -> Removing it"
    }
    elseif ($line -contains $null) {
        echo "Empty Line Found in .gitignore -> Removing it"
    }
    else {
        line | Out-File -FilePath new.repos.txt -Encoding utf8 -Append
    }
}
Remove-Item 'repos.txt'
Rename-Item 'new.repos.txt' 'repos.txt'



${git_repo_string}.ToString() | Out-File -FilePath repos.txt -Encoding utf8 -Append
scp repos.txt git@${gitserver}:${gituser}/repos.txt
Remove-Item 'repos.txt'




Start-Sleep -Seconds 5

Here i will give you a basic idea of how my .gitignore file looks like

# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules/*
node_modules/
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
git-create-repo.ps1

Thank you my dear friends out there for your quick support and taking time to overview this huge bulk of code.

Sincierly

CodePudding user response:

PowerShell 5, by default, appends text in ASCII and git expects your .gitignore to be in UTF8.

You can solve this in 2 ways.

  1. Upgrade to PowerShell Core (6 ) by launching your script from pwsh instead of from powershell. pwsh will launch PowerShell core. PowerShell Core defaults to UTF-8.
  2. Use "text" | Out-File -append -Encoding UTF8 -filepath .gitignore instead of "text" >> .gitignore.

CodePudding user response:

As promised i want to show you my answer how i solved this - by sharing the whole code.

Its not perfect but it manages github connected repos and this code is specially designed for connecting and managing my own private git server, setup for my coding experiments

#----------------------------------------------------------------------------------------
#
# Definieren der Notwendigen Basisvariablen
#
$workdir = Convert-Path $pwd


$git_already_managed = 1
$projectFolder = ""
$commit_string = "" 
$gitHubExists = 0

$userName = [System.Environment]::UserName

$workDirName = $workdir.Substring(($workdir.LastIndexOf("\")   1), ($workdir.Length - 1 ) - $workdir.LastIndexOf("\"))

$git_dir_string = $workDirName   ".git"
Write-Output $workDirName


#----------------------------------------------------------------------------------------
#
# Erstelle Nutzerdaten Verzeichnis
#
if (-not (Test-Path -Path ./.gitSriptData)) {
    New-Item -Path '.gitSriptData' -ItemType Directory
}



#----------------------------------------------------------------------------------------
#
# frage nach Hostname
#
if (-not (Test-Path -Path ./.gitSriptData/gitServer)) {
    New-Item -Path './.gitSriptData/gitServer' -ItemType File
    $gitserver = Read-Host "Please enter Hostname for this tool to work"
    $gitserver | Out-File -FilePath ./.gitSriptData/gitServer -Encoding utf8
}
else {
    $File = './.gitSriptData/gitServer'
    foreach ($line in Get-Content $File) {
        $gitserver = $line
    }
}


#----------------------------------------------------------------------------------------
#
# Frage nach username
#
if (-not (Test-Path -Path ./.gitSriptData/gituserName)) {
    New-Item -Path './.gitSriptData/gituserName' -ItemType File
    $gituser = Read-Host "Please Enter your Git User on this Host"
    $gituser | Out-File -FilePath ./.gitSriptData/gituserName -Encoding utf8
}
else {
    $File = './.gitSriptData/gituserName'
    foreach ($line in Get-Content $File) {
        $gituser = $line
    }
}


#----------------------------------------------------------------------------------------
#
# frage nach Projektverzeichnis
#
if (-not (Test-Path -Path ./.gitSriptData/gitprojectdir)) {
    New-Item -Path './.gitSriptData/gitprojectdir' -ItemType File
    $projectFolder = Read-Host "Please Enter Project Dir (leave empty if none)"
    $projectFolder | Out-File -FilePath ./.gitSriptData/gitprojectdir -Encoding utf8
}
else {
    $File = './.gitSriptData/gitprojectdir'
    foreach ($line in Get-Content $File) {
        $projectFolder = $line
    }
}


#----------------------------------------------------------------------------------------
#
# frage nach wie die eingerichtete Remmote heißen soll
#
if (-not (Test-Path -Path ./.gitSriptData/managedRemote)) {
    New-Item -Path './.gitSriptData/managedRemote' -ItemType File
    $defaultRemoteName = Read-Host "Please give the Remote you want to Manage a Name (leave empty for origin)"
    if ($defaultRemoteName.Length -le 3){
        $defaultRemoteName  = "origin"
    }
    $defaultRemoteName | Out-File -FilePath ./.gitSriptData/managedRemote -Encoding utf8

}
else {
    $File = './.gitSriptData/managedRemote'
    foreach ($line in Get-Content $File) {
        $defaultRemoteName = $line
    }
}



#----------------------------------------------------------------------------------------
#
# frage nach wie die eingerichtete Branch heißen soll
#
if (-not (Test-Path -Path ./.gitSriptData/managedBranch)) {
    New-Item -Path './.gitSriptData/managedBranch' -ItemType File
    $targetBranchName = Read-Host "Please give the Branch you want to Manage a Name (leave empty for master)"
    if ($targetBranchName.Length -le 3) {
        $targetBranchName = "master"
    }
    $targetBranchName | Out-File -FilePath ./.gitSriptData/managedBranch -Encoding utf8
    
}
else {
    $File = './.gitSriptData/managedBranch'
    foreach ($line in Get-Content $File) {
        $targetBranchName = $line
    }
}





$commit_string = Read-Host "Custom Commit Message: "
$commit_string = $commit_string.ToString()





#----------------------------------------------------------------------------------------
#
# Korrigieren der Remotes - Hinzufuegen des eigenen Gitservers
#
git remote -v | Out-File -FilePath remotes.temp -Encoding utf8 -Append
$File = 'remotes.temp'

foreach ($line in Get-Content $File) {
    $remoteListingLine = $line
    $remoteHostName = $remoteListingLine.Substring(($remoteListingLine.IndexOf("@")   1), ($remoteListingLine.LastIndexOf(":") - 1 ) - $remoteListingLine.IndexOf("@"))
    Write-Output $remoteHostName
    if ($remoteHostName -contains "github.com") {
        Write-Output "GitHub Repo found"
        $remoteListingLine = $remoteListingLine -replace $defaultRemoteName, "github"
        Write-Output "Renaming properly ..."
        Write-Output $remoteListingLine

        git remote rename $defaultRemoteName "github"
        $gitHubExists = 1

    }

}
Remove-Item 'remotes.temp'





#----------------------------------------------------------------------------------------
#
# Erstelle .gitignore Datei
#

if (-not (Test-Path -Path .gitignore)) {
    New-Item -Path '.gitignore' -ItemType File

}
if (-not (Test-Path -Path new.gitignore)) {
    New-Item -Path 'new.gitignore' -ItemType File
}


$File = '.gitignore'

foreach ($line in Get-Content $File) {
    Write-Output ".gitignore: $line" 
    if ($line -contains "git-create-repo.ps1") {
        Write-Output "Duplicate entry found, Removing it"
        $git_already_managed = 1;
    }
    elseif ($line -contains ".gitScriptData") {
        Write-Output "Duplicate entry found, Removing it"
    }
    elseif ($line.Length -le 1) {
        Write-Output "Empty Line Found in .gitignore -> Removing it"
    }
    elseif ($line -contains $null) {
        Write-Output "Empty Line Found in .gitignore -> Removing it"
    }
    else {
        $line | Out-File -FilePath new.gitignore -Encoding utf8 -Append
    }
}

    
Remove-Item '.gitignore'
Rename-Item 'new.gitignore' '.gitignore'

#check if its not its own project and append itself if not
If ( $workDirName -ne "ps.git-create-repo" -and $workDirName -ne "ps.git-create-repo.git") {
    "git-create-repo.ps1" | Out-File -FilePath .gitignore -Encoding utf8 -Append

}
".gitScriptData" | Out-File -FilePath .gitignore -Encoding utf8 -Append

Start-Sleep -Seconds 1

#----------------------------------------------------------------------------------------
#
# Anpassen der Git Branch und Neuanlegen von Remote
#
git remote rm $defaultRemoteName
git branch -mv main $targetBranchName



#----------------------------------------------------------------------------------------
#
# Auf dem Remote Server das Repo anlegen
#

if ($projectFolder -ne "") {
    Write-Output "erzeuge Remotes Git Repo im Projektordner"

    if (-not (ssh [email protected]  "test -d $gituser && echo exists")) {
        ssh git@${gitserver} "mkdir $gituser"
    }


    foreach ($string in $projectFolder.Split("//")) {
        $oldstring = ""
        $num = 1
        foreach ($string in $projectFolder.Split("//")) {

            if ($num -gt 1) {
                ssh git@${gitserver} "cd $gituser && mkdir $oldstring/$string"     
        
                $oldstring = "$oldstring/$string"
            }
            else {
                ssh git@${gitserver} "cd $gituser && mkdir $string"
                $oldstring = $string
            }

            
            
            $num = $num   1
        }
    }
    
    ssh git@${gitserver} "cd $gituser/$projectFolder && mkdir $git_dir_string"
    ssh git@${gitserver} "cd $gituser/$projectFolder/$git_dir_string && git init --bare"


}
else {
    ssh git@${gitserver} "mkdir $gituser"
    ssh git@${gitserver} "cd $gituser && mkdir $git_dir_string"
    ssh git@${gitserver} "cd $gituser/$git_dir_string && git init --bare"
}


#----------------------------------------------------------------------------------------
#
# Prüfe ob bereits ein Git Repo lokal (.git) existiert und andernfalls erzeugen
#
if (-not (Test-Path -Path '.git' -PathType Container)) {
    git init
    Write-Output "Lokales Repo wurde Initialisiert"
}
else {
    Write-Output "Ein Repository existiert bereits -> Verwende Vorhandenes Repository"
}


#----------------------------------------------------------------------------------------
#
# Prüfung ob das REpository bereits verwaltet wird und korrekt mit .gitignore Dateien umgeht
#
if (-not (Test-Path -Path .gitignore)) {
    New-Item -Path '.gitignore' -ItemType File
}
if ( $git_already_managed -eq 0) {
    git rm -r --cached .
    git add .\.gitignore


    
        
    git rm -r --cached .

}
else {
    Write-Output "Git Repository wird bereits vom Script verwaltet - keine Recachings notwendig!"
}



#----------------------------------------------------------------------------------------
#
# Entfernen von Überflüssigen Dateien
#

git ls-files -i -c --exclude-from=.gitignore | Out-File -FilePath cached.git.temp -Encoding utf8 -Append


Write-Output "Dateien wurden zum Lokalen Repository hinzugefuegt"

$File = 'cached.git.temp'

foreach ($line in Get-Content $File) {
    Write-Output "Entferne Datei $line"
    git rm --cached $line

}
Remove-Item 'cached.git.temp'

Start-Sleep -Seconds 1
git add .



#----------------------------------------------------------------------------------------
#
# Commit erstellen
#
$timestamp = (get-date).ToString('G')
if ($commit_string -eq "") {
    $messagestring = 'Autogenerated Commit from '   $userName   '-> Timestamp: '   $timestamp
    git commit -m $messagestring


}
else {
    
    $messagestring = 'Commit with Message: '   $commit_string   ' , by User: '   $userName   ' -> Timestamp: '   $timestamp

    git commit -m $messagestring
   
}





#----------------------------------------------------------------------------------------
#
# Repo anlegen anlegen
#
$timestamp = (get-date).ToString('G')
if ($projectFolder -ne "") {
    $git_repo_string = "[email protected]:${gituser}/${projectFolder}/${workDirName}.git"
}
else {
    $git_repo_string = "[email protected]:${gituser}/${workDirName}.git"
}

Write-Output "Der Verwendete Remote Git Repo string lautet: $git_repo_string" 


#----------------------------------------------------------------------------------------
#
# Eigene Remote hinzufügen & pushen
#
git remote add $defaultRemoteName $git_repo_string
git push $defaultRemoteName $targetBranchName
if ($gitHubExists -eq 1) {
    git push github $targetBranchName
}

#----------------------------------------------------------------------------------------
#
# Repoliste auf dem Server aktualisieren
#
scp git@${gitserver}:${gituser}/repos.txt repos.txt
if (-not (Test-Path -Path repos.txt)) {
    New-Item -Path 'repos.txt' -ItemType File
}
if (-not (Test-Path -Path new.repos.txt)) {
    New-Item -Path 'new.repos.txt' -ItemType File
}

$File = "repos.txt"
Write-Output "Kown Repos on this Server: "
foreach ($line in Get-Content $File) {
    Write-Output $line
    if ($line -contains $git_repo_string) {
        Write-Output "Duplicate entry found, Removing it"
    }
    elseif ($line.Length -eq 0) {
        Write-Output "Empty Line Found in repos.txt -> Removing it"
    }
    elseif ($line -contains $null) {
        Write-Output "Empty Line Found in .repos.txt -> Removing it"
    }
    else {
        $line | Out-File -FilePath new.repos.txt -Encoding utf8 -Append
    }
}
Remove-Item 'repos.txt'
Rename-Item 'new.repos.txt' 'repos.txt'

${git_repo_string}.ToString() | Out-File -FilePath repos.txt -Encoding utf8 -Append
scp repos.txt git@${gitserver}:${gituser}/repos.txt
Remove-Item 'repos.txt'




Start-Sleep -Seconds 2
  • Related