programing

어떻게 하면 비주얼 스튜디오 코드, 유닉스 계열의 모든 파일에서 모든 줄 끝(EOL)을 만들 수 있습니까?

showcode 2023. 6. 4. 10:45
반응형

어떻게 하면 비주얼 스튜디오 코드, 유닉스 계열의 모든 파일에서 모든 줄 끝(EOL)을 만들 수 있습니까?

저는 Windows 10 Home을 사용하며 주로 Visual Studio Code(VS Code)를 사용하여 Linux Bash 스크립트와 PHP 및 JavaScript를 편집합니다.

Windows 전용으로 개발하는 것은 없으며 편집하는 모든 파일의 기본 EOL이 Unix(nix)와 같은 것이 되는 것도 개의치 않습니다.

Visual Studio Code에서 모든 파일(확장자에 관계없이)의 모든 EOL이 nix인지 확인하려면 어떻게 해야 합니까?


Visual Studio Code를 사용하여 Windows에서 Bash 스크립트를 몇 개 작성하고 프로젝트의 일부로 GitHub에 업로드한 후 이 질문을 던집니다. 프로젝트를 검토한 선임 프로그래머가 Windows EOL이 있으며 EOL을 9로 변경하면 해결할 수 있는 BOM 문제도 있다고 말했습니다.


제가 개발한 모든 것이 Linux 기반이기 때문에 Windows 고유의 파일이라도 기본적으로 편집하는 모든 파일에 9개의 EOL을 선호합니다.

허용된 대답은 모든 파일에 대해 이 작업을 수행하는 방법을 설명합니다(설정에서 files.eol 사용). 그러나 해당 설정을 재정의해야 할 경우 오른쪽 아래에 이 파일을 클릭하여 변경할 수 있는 표시기가 있습니다.클릭할 수 있다는 것을 깨닫는 데 시간이 좀 걸렸습니다.

오른쪽 아래의 메시지 표시줄에서 CRLF 참조

며칠 동안 간단한 솔루션을 검색했지만 모든 파일을 변경하는 Git 명령을 찾을 때까지 아무런 성공도 거두지 못했습니다.CRLF로.LF.

Mats가 지적했듯이 다음 명령을 실행하기 전에 변경 사항을 커밋해야 합니다.

루트 폴더에 다음을 입력합니다.

git config core.autocrlf false

git rm --cached -r .         # Don’t forget the dot at the end

git reset --hard

프로젝트 기본 설정에서 다음 구성 옵션을 추가/편집합니다.

"files.eol": "\n"

이것은 커밋 639a3cb 기준으로 추가되었으므로 커밋 후 버전을 사용해야 합니다.

참고: 싱글이 있더라도CRLF파일에서, 위의 설정은 무시될 것이고 전체 파일은 다음으로 변환될 것입니다.CRLF먼저 모두 변환해야 합니다.CRLF안으로LFVisual Studio Code에서 열기 전에.

참고 항목: https://github.com/Microsoft/vscode/issues/2957

Visual Studio Code 설정에서 옵션을 찾을 수 있습니다.그것은 "텍스트 편집기"→"파일"→"얼" 아래에 있습니다.여기서 \n 또는 \r\n 또는 auto를 선택할 수 있습니다.

여기에 이미지 설명 입력

기존 파일의 끝 줄을 변환하려면 다음과 같이 하십시오.

WSL

WSL이나 Shell 터미널에서 dos2unix를 사용할 수 있습니다.

도구를 설치합니다.

sudo apt install dos2unix

현재 디렉터리의 줄 끝을 변환합니다.

find -type f -print0 | xargs -0 dos2unix

변환에서 제외할 폴더가 있으면 다음을 사용합니다.

find -type f \
     -not -path "./<dir_to_exclude>/*" \
     -not -path "./<other_dir_to_exclude>/*" \
     -print0 | xargs -0 dos2unix

2023년 편집

직접 PowerShell 7+(더 빠른 멀티 스레드)

Windows에 PowerShell 7을 설치하려면 여기에 있는 지침을 따르십시오.

Chocolaty를 설치하고 Chocolaty용 dos2unix를 설치해야 합니다.

  1. Chocolaty가 아직 없다면 이 지침에 따라 Chocolaty를 설치합니다.

  2. Chocolaty를 위한 dos2unix 설치

    1. 관리자로 PowerShell 터미널 열기

      pwsh.exe -new_console:a
      
    2. dos2unix 설치

      choco install dos2unix
      
    3. 관리자 터미널을 닫습니다.

      exit
      

는 이리, 우는을 할 수 있습니다.dos2unixPowerShell에서 다운로드할 수 있습니다.

# Set the parameters
$path = Get-Location
$numbOfThreads = 50
$exclude_patterns = "^.*(\.git|\.idea|node_modules|\.next|\.(jpeg|jpg|png|gif|mp4|mkv|mp3|wav)$).*$"

# Find files to convert
$files = Get-ChildItem -Path $path -Recurse -Include *.* -File -Force | Where-Object {$_.FullName -notmatch $exclude_patterns}
Write-Host "Found $($files.Count) files"

# Convert the files
$files | ForEach-Object -Parallel {
    dos2unix $_.FullName
} -ThrottleLimit $numbOfThreads

기존의 두 답변 모두 도움이 되지만 제가 필요로 했던 것은 아닙니다.작업영역의 모든 새 줄 문자를 CRLF에서 LF로 대량 변환하고 싶었습니다.

나는 그것을 하기 위해 간단한 연장을 했습니다.

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.keyoti-changeallendoflinesequence

사실, 여기 참조용 확장 코드가 있습니다.

'use strict';

import * as vscode from 'vscode';
import { posix } from 'path';


export function activate(context: vscode.ExtensionContext) {

    // Runs 'Change All End Of Line Sequence' on all files of specified type.
    vscode.commands.registerCommand('keyoti/changealleol', async function () {

        async function convertLineEndingsInFilesInFolder(folder: vscode.Uri, fileTypeArray: Array<string>, newEnding: string): Promise<{ count: number }> {
            let count = 0;
            for (const [name, type] of await vscode.workspace.fs.readDirectory(folder)) {

                if (type === vscode.FileType.File && fileTypeArray.filter( (el)=>{return name.endsWith(el);} ).length>0){ 
                    const filePath = posix.join(folder.path, name);

                    var doc = await vscode.workspace.openTextDocument(filePath);

                    await vscode.window.showTextDocument(doc);
                    if(vscode.window.activeTextEditor!==null){
                        await vscode.window.activeTextEditor!.edit(builder => { 
                            if(newEnding==="LF"){
                                builder.setEndOfLine(vscode.EndOfLine.LF);
                            } else {
                                builder.setEndOfLine(vscode.EndOfLine.CRLF);
                            }
                            count ++; 
                        });

                    } else {
                        vscode.window.showInformationMessage(doc.uri.toString());
                    }
                }

                if (type === vscode.FileType.Directory && !name.startsWith(".")){
                    count += (await convertLineEndingsInFilesInFolder(vscode.Uri.file(posix.join(folder.path, name)), fileTypeArray, newEnding)).count;
                }
            }
            return { count };
        }

        let options: vscode.InputBoxOptions = {prompt: "File types to convert", placeHolder: ".cs, .txt", ignoreFocusOut: true};
        let fileTypes = await vscode.window.showInputBox(options);
        fileTypes = fileTypes!.replace(' ', '');
        let fileTypeArray: Array<string> = [];

        let newEnding = await vscode.window.showQuickPick(["LF", "CRLF"]);

        if(fileTypes!==null && newEnding!=null){
            fileTypeArray = fileTypes!.split(',');

            if(vscode.workspace.workspaceFolders!==null && vscode.workspace.workspaceFolders!.length>0){
                const folderUri = vscode.workspace.workspaceFolders![0].uri;
                const info = await convertLineEndingsInFilesInFolder(folderUri, fileTypeArray, newEnding);
                vscode.window.showInformationMessage(info.count+" files converted");

            }
        }

    });

}

다른 사용자가 "Files.eol" 설정을 사용하여 모든 파일의 끝 줄을 변경할 수 있습니다.

"Files.eol": "\n"   // Unix
"Files.eol": "\r\n" // Windows

방금 Windows 컴퓨터에서 동일한 문제가 발생했습니다.을 열 이 파을열때다로 됩니다.CRLF으로 (에 대한 을 설정했음에도 불구하고)lf사람들이 권하는 바와 같이)문제는 잘못된 Git 구성으로 저장소를 복제했다는 것입니다.그랬다.CRLF 완벽하게했습니다.어쨌든, 제가 한 일은 이렇고 완벽하게 작동했습니다. 그만.CRLF내 작업 공간에서.

  1. 을 Git 성을설정다니로 합니다.lf 명령으로git config --global core.autocrlf false
  2. 다시 합니다.git clone ...
  3. Visual Studio Code 인스턴스, 메뉴 파일 → 기본 설정 → 설정파일: Eol을 "\n"로 설정합니다.
  4. 프로젝트를 열면 모든 것이 예상대로 되어야 합니다.

유형 스크립트 제거

달려.

npm install -g typescript
git config --global core.autocrlf false

확인.

git config --global core.autocrlf 

거짓이 드러나면요프로젝트 복제 및 재실행 시도

줄끝이 " ", vscode"로 설정되어 합니다.crlf 글로벌설로사면를누릅다니려하용으정다누▁if니릅▁as를▁press▁setting▁you▁this▁global글▁a를 누릅니다.ctr+shift+p 및형을 합니다.user settings json첫 번째 옵션을 선택하여 글로벌 설정 파일을 엽니다.특정 프로젝트에 대해 원하는 경우settings.json의 내부에 ..vscode폴더를 선택합니다.그런 다음 여기에 이 줄을 추가합니다.

    ...
    "files.eol": "\r\n"

하지만 이것은 문제를 해결하지 못합니다. 매번 풀을 한 후 또는 vscode를 시작한 후에도 변경 사항이 계속 표시됩니다. 행중실을 입니다.git add .더 이상 원하는 변경 사항을 표시하지 않을 것이지만 매번 이 작업을 수행하지는 않을 것입니다.

이 문제를 해결하려면 프로젝트의 기본에 .editor config 파일이 있어야 합니다.여기에 다음을 추가할 수 있습니다.

   [*]
   ...
   end_of_line = crlf

나의 원래 게시물

언급URL : https://stackoverflow.com/questions/48692741/how-can-i-make-all-line-endings-eols-in-all-files-in-visual-studio-code-unix

반응형