dentimoer_setup/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use std::process::Command;
use std::fs;
use std::path::Path;
use regex::Regex;

pub fn install_essential_equipments() {
    // PowerShell을 관리자 모드로 열고, choco --help 명령 실행
    let install_cmd = "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))";
    let install_choco = Command::new("powershell")
        .args(&[
            "-Command",
            &format!(
                "Start-Process powershell -Verb runAs -ArgumentList \"-NoProfile -ExecutionPolicy Bypass -Command {}\"",
                install_cmd.replace("\"", "`\"")  // PowerShell 내에서 따옴표 이스케이프
            )
        ]).spawn();

    match install_choco {
        Ok(_) => {
            println!("Choco has installed");
        }
        Err(e) => {
            eprintln!("PowerShell 실행 중 오류 발생: {}", e);
        }
    }

    let install_opencv_and_llvm = Command::new("powershell")
        .args(&[
            "-Command",
            "Start-Process powershell -Verb runAs -ArgumentList '-Command \"choco install llvm opencv\"'",
        ])
        .status();

    match install_opencv_and_llvm {
        Ok(status) if status.success() => {
            println!("choco --help 명령 실행이 완료되었습니다.");
        }
        Ok(status) => {
            eprintln!("choco --help 명령 실행이 실패했습니다. 종료 코드: {}", status);
        }
        Err(e) => {
            eprintln!("choco --help 명령 실행 중 오류 발생: {}", e);
        }
    }

    let opencv_version = get_opencv_num_and_version().unwrap_or(0);

    set_opencv_env(opencv_version);
}

pub fn get_opencv_num_and_version() -> Option<u16> {
    let opencv_lib_path = "C:\\tools\\opencv\\build\\x64\\lib"; // OpenCV 라이브러리 경로
    let opencv_world_prefix = "opencv_world";

    // 라이브러리 경로가 존재하는지 확인
    if !Path::new(opencv_lib_path).exists() {
        eprintln!("OpenCV 라이브러리 경로가 존재하지 않습니다: {}", opencv_lib_path);
        return None;
    }

    // 디렉토리에서 파일 목록 읽기
    match fs::read_dir(opencv_lib_path) {
        Ok(entries) => {
            // opencv_world 뒤의 숫자를 찾기 위한 정규식
            let re = Regex::new(&format!(r"{}(\d+)\.lib", opencv_world_prefix)).unwrap();

            for entry in entries {
                if let Ok(entry) = entry {
                    let file_name = entry.file_name();
                    let file_name = file_name.to_string_lossy();

                    // 정규식에 매칭되는 파일 찾기
                    if let Some(captures) = re.captures(&file_name) {
                        if let Some(version_str) = captures.get(1) {
                            if let Ok(version) = version_str.as_str().parse::<u16>() {
                                println!("발견된 OpenCV 라이브러리: {}", file_name);
                                println!("추출된 버전 숫자: {}", version);
                                return Some(version); // 버전을 u16 값으로 반환
                            } else {
                                eprintln!("버전 숫자가 u16 형식으로 변환되지 않습니다.");
                                return None;
                            }
                        }
                    }
                }
            }

            println!("opencv_world 라이브러리를 찾을 수 없습니다.");
            None
        }
        Err(e) => {
            eprintln!("디렉토리를 읽을 수 없습니다: {}", e);
            None
        }
    }
}

pub fn set_opencv_env(opencv_version: u16) { // for windows 11
    let opencv_include_paths = "C:\\tools\\opencv\\build\\include";
    let opencv_link_string = format!("opencv_world{}", opencv_version);
    let opencv_link_libs = opencv_link_string.as_str();
    let opencv_link_paths = "C:\\tools\\opencv\\build\\x64\\lib";
    let opencv_bin_paths = "C:\\tools\\opencv\\build\\x64\\vc16\\bin";

    // 명령어를 실행하기 위한 PowerShell 스크립트 생성
    let script = format!(
        r#"
        [Environment]::SetEnvironmentVariable('OPENCV_INCLUDE_PATHS', '{0}', [EnvironmentVariableTarget]::Machine)
        [Environment]::SetEnvironmentVariable('OPENCV_LINK_LIBS', '{1}', [EnvironmentVariableTarget]::Machine)
        [Environment]::SetEnvironmentVariable('OPENCV_LINK_PATHS', '{2}', [EnvironmentVariableTarget]::Machine)
        $currentPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::Machine)
        if (-not ($currentPath -like '*{3}*')) {{
            [Environment]::SetEnvironmentVariable('Path', \"$currentPath;{3}\", [EnvironmentVariableTarget]::Machine)
        }}
        "#,
        opencv_include_paths, opencv_link_libs, opencv_link_paths, opencv_bin_paths
    );

    // PowerShell 명령 실행
    let output = Command::new("powershell")
        .args(["-Command", &script])
        .output()
        .expect("Failed to execute PowerShell command");

    // 결과 출력
    if output.status.success() {
        println!("환경 변수가 성공적으로 설정되었습니다.");
    } else {
        eprintln!(
            "오류 발생: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
}