로컬에 gradle depndencies 다운받은 jar 파일을 nexus서버에 일괄 업로드하는 방법

로컬 Gradle 캐시 경로 구조(~/.gradle/caches/modules-2/files-2.1/{groupId}/{artifactId}/{version}/)에서 GroupId를 자동으로 추출해 정확한 GAV로 Nexus에 업로드하는 스크립트를 완성했습니다. 사용자님의 Gradle 환경에 최적화된 버전입니다.

완전 자동화 Bash 스크립트 (권장)
Gradle 캐시 전체를 순회하며 경로에서 GAV를 파싱하고 업로드합니다.

bash
#!/bin/bash
# auto-upload-gradle-cache.sh <repoId> <nexus-url>

REPO_ID=$1
NEXUS_URL=$2
CACHE_DIR=”${HOME}/.gradle/caches/modules-2/files-2.1/”

if [[ ! -d “$CACHE_DIR” ]]; then
echo “Gradle 캐시 디렉토리 없음: $CACHE_DIR”
exit 1
fi

find “$CACHE_DIR” -type d -name ‘[0-9]*’ | while read version_dir; do
# 경로 파싱: …/files-2.1/group/artifact/version/
group_path=$(realpath –relative-to=”$CACHE_DIR” “$(dirname “$(dirname “$version_dir”)”)”)
artifact=$(basename “$(dirname “$version_dir”)”)
version=$(basename “$version_dir”)

# groupId 경로를 .으로 치환 (com/example/foo -> com.example.foo)
group_id=$(echo “$group_path” | tr ‘/’ ‘.’)

jar_file=”$version_dir/${artifact}-${version}.jar”

if [[ -f “$jar_file” ]]; then
echo “업로드: $group_id:$artifact:$version”
mvn deploy:deploy-file \
-DgroupId=”$group_id” \
-DartifactId=”$artifact” \
-Dversion=”$version” \
-DgeneratePom=true \
-Dpackaging=jar \
-DrepositoryId=”$REPO_ID” \
-Durl=”$NEXUS_URL” \
-Dfile=”$jar_file”
fi
done
사용법: ./auto-upload-gradle-cache.sh libs-releases http://nexus:8081/repository/libs-releases/

로컬에 gradle depndencies 다운받은 jar 파일을 nexus서버에 일괄 업로드하는 방법

Gradle 태스크 완성본
build.gradle에 추가하면 gradle uploadAllCache로 전체 캐시 업로드.

text
task uploadAllCache {
doLast {
def cacheDir = “${System.getProperty(‘user.home’)}/.gradle/caches/modules-2/files-2.1/”
def nexusUrl = ‘http://your-nexus:8081/repository/maven-releases/’
def repoId = ‘nexus-releases’

file(cacheDir).traverse(type: groovy.io.FileType.FILES) { file ->
if (file.name.endsWith(‘.jar’) && file.name =~ /(.+)-(.+)\.jar/) {
def jarName = file.name
def versionDir = file.parent
def artifactDir = versionDir.parentFile
def groupPath = artifactDir.parentFile.parentFile.absolutePath.replace(cacheDir, ”).split(‘/’)*.replace(‘/’, ‘.’).join(‘.’)

def matcher = (jarName =~ /(.+)-(.+)\.jar/)
def artifactId = matcher[0][1]
def version = matcher[0][2]

println “업로드: ${groupPath}:${artifactId}:${version}”

exec {
workingDir file.parentFile
commandLine ‘mvn’, ‘deploy:deploy-file’,
“-DgroupId=${groupPath}”,
“-DartifactId=${artifactId}”,
“-Dversion=${version}”,
‘-DgeneratePom=true’,
‘-Dpackaging=jar’,
“-DrepositoryId=${repoId}”,
“-Durl=${nexusUrl}”,
“-Dfile=${file.absolutePath}”
}
}
}
}
}
특정 프로젝트 캐시만 업로드
현재 프로젝트의 build/dependency-cache/ 또는 gradle/dependency-cache/ 대상:

bash
# 프로젝트 루트에서 실행
find .gradle/dependency-cache -type f -name “*.jar” | while read jar; do
group_id=$(echo $jar | sed ‘s|^\./||; s|/|.|g; s|\([^/]*\)-\([^/]*\)\.jar$|\1|’)
# … (위 로직 동일)
done
설정 및 실행 체크리스트
settings.xml: <server><id>libs-releases</id><username>deployer</username><password>***</password></server>

Nexus 권한: nx-deploy 롤 확인

테스트: find ~/.gradle/caches/modules-2/files-2.1/ -name “*.jar” | head -5으로 샘플 확인

로그: -X 플래그로 디버깅 (mvn … -X)

이제 GroupId, ArtifactId, Version 모두 파일 경로에서 자동 추출되어 Nexus에 정확히 업로드됩니다.

 

Windows Shell

<#
.SYNOPSIS
    Gradle 캐시 JAR 파일 Nexus 일괄 업로드 스크립트 (인증 포함)
.DESCRIPTION
    로컬 Gradle 캐시를 스캔하여 Nexus로 업로드합니다.
    실행 시 입력받은 ID/PW로 임시 settings.xml을 생성하여 인증합니다.
.PARAMETER RepoId
    Nexus Repository ID (예: gjf-msa)
.PARAMETER NexusUrl
    Nexus Repository URL
.PARAMETER RepoUser
    Nexus 로그인 ID (관리자 등)
.PARAMETER RepoPassword
    Nexus 로그인 비밀번호
.EXAMPLE
    .\auto-upload-gradle-cache.ps1 -RepoId “gjf-msa” -NexusUrl “http://…” -RepoUser “admin” -RepoPassword “admin123”
#>
param(
    [Parameter(Mandatory=$true)]
    [string]$RepoId,
    [Parameter(Mandatory=$true)]
    [string]$NexusUrl,
    [Parameter(Mandatory=$true)]
    [string]$RepoUser,
    [Parameter(Mandatory=$true)]
    [string]$RepoPassword
)
# 1. 임시 settings.xml 생성 (인증 정보 포함)
# Maven은 커맨드라인에서 직접 password를 넣기 어렵으므로, 임시 설정 파일을 만들어 사용합니다.
$TempSettingsFile = [System.IO.Path]::GetTempFileName()
$SettingsXml = @”
<settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0″
          xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
          xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd”>
  <servers>
    <server>
      <id>$RepoId</id>
      <username>$RepoUser</username>
      <password>$RepoPassword</password>
    </server>
  </servers>
</settings>
“@
Set-Content -Path $TempSettingsFile -Value $SettingsXml -Encoding UTF8
Write-Host “인증용 임시 설정 파일 생성됨: $TempSettingsFile” -ForegroundColor Gray
# 2. Gradle 캐시 디렉토리 설정
$HomeDir = $env:USERPROFILE
$CacheDir = Join-Path $HomeDir “.gradle\caches\modules-2\files-2.1”
if (-not (Test-Path -Path $CacheDir)) {
    Write-Error “Gradle 캐시 디렉토리를 찾을 수 없습니다: $CacheDir”
    Remove-Item -Path $TempSettingsFile -ErrorAction SilentlyContinue
    exit 1
}
Write-Host “검색 시작: $CacheDir” -ForegroundColor Cyan
try {
    # 3. JAR 파일 검색 및 업로드 루프
    Get-ChildItem -Path $CacheDir -Filter “*.jar” -Recurse -File | ForEach-Object {
        $JarFile = $_
        $HashDir = $JarFile.Directory
        if ($HashDir.Parent -and $HashDir.Parent.Parent) {
            $VersionDir = $HashDir.Parent
            $Version = $VersionDir.Name
            $ArtifactDir = $VersionDir.Parent
            $Artifact = $ArtifactDir.Name
            $ExpectedFileName = “${Artifact}-${Version}.jar”
            if ($JarFile.Name -eq $ExpectedFileName) {
                # GroupId 추출
                $RelativePath = $ArtifactDir.FullName.Substring($CacheDir.Length)
                if ($RelativePath.StartsWith(“\”)) { $RelativePath = $RelativePath.Substring(1) }
                $GroupPath = Split-Path -Path $RelativePath -Parent
                $GroupId = $GroupPath -replace ‘\\’, ‘.’
                if ([string]::IsNullOrWhiteSpace($GroupId)) {
                    $GroupId = $ArtifactDir.Parent.Name
                }
                Write-Host “업로드 중: $GroupId:$Artifact:$Version” -ForegroundColor Green
                # Maven 배포 명령어
                # -s 옵션으로 위에서 만든 임시 설정 파일을 지정합니다.
                $MvnArgs = @(
                    “-s”, “$TempSettingsFile”,
                    “deploy:deploy-file”,
                    “-DgroupId=$GroupId”,
                    “-DartifactId=$Artifact”,
                    “-Dversion=$Version”,
                    “-DgeneratePom=true”,
                    “-Dpackaging=jar”,
                    “-DrepositoryId=$RepoId”,
                    “-Durl=$NexusUrl”,
                    “-Dfile=$($JarFile.FullName)”
                )
                try {
                    # 성공 시 출력 숨김 (Out-Null), 오류 발생 시만 표시하려면 제거하세요.
                    & mvn $MvnArgs | Out-Null
                }
                catch {
                    Write-Warning “업로드 실패: $($JarFile.Name)”
                }
            }
        }
    }
}
finally {
    # 4. 종료 시 임시 파일 삭제 (보안 및 정리)
    if (Test-Path -Path $TempSettingsFile) {
        Remove-Item -Path $TempSettingsFile -Force
        Write-Host “임시 설정 파일 삭제 완료.” -ForegroundColor Gray
    }
}
Write-Host “모든 작업이 완료되었습니다.” -ForegroundColor Cyan
# Set-ExecutionPolicy RemoteSigned -Scope Process
# Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
# ./auto-upload-gradle-cache.ps1 -RepoId “gjf-msa” -NexusUrl “http://192.168.110.100:8081/repository/gjf-msa” -RepoUser “admin” -RepoPassword “admin123”