repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
v-analyzer
github_2023
others
74
v-analyzer
spytheman
@@ -18,7 +18,6 @@ const PREC = { or: 1, resolve: 1, composite_literal: -1, - empty_array: -2, strictly_expression_list: -3,
should not removing ` empty_array: -2,`, make `strictly_expression_list` be -2 now?
v-analyzer
github_2023
others
74
v-analyzer
spytheman
@@ -116,7 +116,7 @@ mut: Interface with field with default type and attribute ================================================================================ interface Foo { - name string [json: 'Name'] = '' + name string = '' [json: 'Name']
```suggestion name string = '' @[json: 'Name'] ```
v-analyzer
github_2023
others
74
v-analyzer
spytheman
@@ -447,8 +447,8 @@ Simple struct with fields with attributes and default values ================================================================================ struct Foo { name string [attr] - age int [attr] = 10 - other f32 [attr; omitempty] = 3.14
these are valid for the old attributes (before `@[attr]`)
v-analyzer
github_2023
others
73
v-analyzer
spytheman
@@ -18,8 +19,8 @@ jobs: - os: windows-latest target: windows-x86_64 bin_ext: .exe - cc: msvc - - os: ubuntu-20.04 + cc: gcc
why use gcc on windows, instead of msvc?
v-analyzer
github_2023
others
65
v-analyzer
spytheman
@@ -0,0 +1,1269 @@ +/**
What is the difference between a .cjs and a .js file in this context?
v-analyzer
github_2023
others
47
v-analyzer
spytheman
@@ -34,7 +34,7 @@ pub const ( vroot_is_deprecated_message = '@VROOT is deprecated, use @VMODROOT or @VEXEROOT instead' ) -[heap; minify] +@[heap; minify]
afaik stuff under `tests/testdata/` should not be formatted for now, since it is used by `v-analyzer` itself, while it has no support yet for the @[attribute] syntax.
v-analyzer
github_2023
others
47
v-analyzer
spytheman
@@ -57,7 +57,7 @@ mut: // runes returns an array of all the utf runes in the string `s` // which is useful if you want random access to them -[direct_array_access] +@[direct_array_access]
same; do not format the files under tests/testdata/ for now
tchMaterial-parser
github_2023
others
16
happycola233
wuziqian211
@@ -108,38 +147,44 @@ def download_file(url: str, save_path: str) -> None: # 下载文件 download_states.append(current_state) try: + # 确保目标目录存在 + os.makedirs(os.path.dirname(save_path), exist_ok=True) + with open(save_path, "wb") as file: - for chunk in response.iter_content(chunk_size=131072): # 分块下载,每次下载 131072 字节(128 KB) - file.write(chunk) - current_state["downloaded_size"] += len(chunk) - all_downloaded_size = sum(state["downloaded_size"] for state in download_states) - all_total_size = sum(state["total_size"] for state in download_states) - downloaded_number = len([state for state in download_states if state["finished"]]) - total_number = len(download_states) - - if all_total_size > 0: # 防止下面一行代码除以 0 而报错 - download_progress = (all_downloaded_size / all_total_size) * 100 - # 更新进度条 - download_progress_bar["value"] = download_progress - # 更新标签以显示当前下载进度 - progress_label.config(text=f"{format_bytes(all_downloaded_size)}/{format_bytes(all_total_size)} ({download_progress:.2f}%) 已下载 {downloaded_number}/{total_number}") # 更新标签 + for chunk in response.iter_content(chunk_size=131072): # 分块下载,每次下载 128 KB + if chunk: # 过滤掉keep-alive新chunk + file.write(chunk) + file.flush() # 确保数据写入磁盘 + current_state["downloaded_size"] += len(chunk) + all_downloaded_size = sum(state["downloaded_size"] for state in download_states) + all_total_size = sum(state["total_size"] for state in download_states) + downloaded_number = len([state for state in download_states if state["finished"]]) + total_number = len(download_states) + + if all_total_size > 0: + download_progress = (all_downloaded_size / all_total_size) * 100 + download_progress_bar["value"] = download_progress + progress_label.config(text=f"{format_bytes(all_downloaded_size)}/{format_bytes(all_total_size)} ({download_progress:.2f}%) 已下载 {downloaded_number}/{total_number}") current_state["downloaded_size"] = current_state["total_size"] current_state["finished"] = True - except: + except Exception as e: + print(f"下载失败: {url}\n错误信息: {str(e)}") current_state["downloaded_size"], current_state["total_size"] = 0, 0 current_state["finished"], current_state["failed"] = True, True if all(state["finished"] for state in download_states): - download_progress_bar["value"] = 0 # 重置进度条 - progress_label.config(text="等待下载") # 清空进度标签 - download_btn.config(state="normal") # 设置下载按钮为启用状态 + download_progress_bar["value"] = 0 + progress_label.config(text="等待下载") + download_btn.config(state="normal") failed_urls = [state["download_url"] for state in download_states if state["failed"]] if len(failed_urls) > 0: - messagebox.showwarning("下载完成", f"文件已下载到:{os.path.dirname(save_path)}\n以下链接下载失败:\n{"\n".join(failed_urls)}") + failed_str = '\n'.join(failed_urls) + print(f"文件已下载到:{os.path.dirname(save_path)}/{os.path.basename(save_path)}") + print(f"以下链接下载失败:\n{failed_str}") else: - messagebox.showinfo("下载完成", f"文件已下载到:{os.path.dirname(save_path)}") # 显示完成对话框 + print(f"文件已下载到:{os.path.dirname(save_path)}")
此处建议还是恢复到原来的显示对话框,因为我们最终编译的程序不会显示命令行窗口,`print` 的内容并不会被显示😂
tchMaterial-parser
github_2023
others
2
happycola233
ourines
@@ -8,7 +8,7 @@ 电子课本预览页面的网址格式如 <https://basic.smartedu.cn/tchMaterial/detail?contentType=assets_document&contentId=b8e9a3fe-dae7-49c0-86cb-d146f883fd8e&catalogType=tchMaterial&subCatalog=tchMaterial>。 -**本工具暂时仅支持 Windows 操作系统。** +本工具支持 Windows、Linux 等操作系统。
为啥要加个“等”?
nix-flatpak
github_2023
others
127
gmodena
gmodena
@@ -61,6 +61,37 @@ let updateOptions = _: { options = { + restartDelay = mkOption {
Why do you declare these options under `update`? Regular activation could benefit from retry-on-error too IMHO. How about we move this retry-on-error logic into a dedicated attrset? E.g. `services.flatpak.onServiceFailure = { restartDelay = "60s", ... }` I'm bad at naming things; let's bikeshed on `onServiceFailure` alternatives, if something better comes to mind.
nix-flatpak
github_2023
others
35
gmodena
gmodena
@@ -64,7 +64,7 @@ Using flake, installing `nix-flatpak` as a NixOs module would look something lik ``` Depending on how config and inputs are derived `homeManagerModules` import can be flaky. Here's an example of how `homeManagerModules` is imported on my nixos systems config in [modules/home-manager/desktop/nixos/default.nix](https://github.com/gmodena/config/blob/5b3c1ce979881700f9f5ead88f2827f06143512f/modules/home-manager/desktop/nixos/default.nix#L17). `flake-inputs` is a special extra arg set in the repo `flake.nix` -[mkNixosConfiguration]([https://github.com/gmodena/config/blob/main/flake.nix#L29](https://github.com/gmodena/config/blob/5b3c1ce979881700f9f5ead88f2827f06143512f/flake.nix#L29). +[mkNixosConfiguration](https://github.com/gmodena/config/blob/5b3c1ce979881700f9f5ead88f2827f06143512f/flake.nix#L29).
In this case I'd rather keep pointing to the specific commit id. The purpose is to avoid changes to main (e.g. refactoring my config) would break the example. FYI: in the future I plan to avoid linking to my config (it's a bit messy), and add examples to `testing-base`.
nix-flatpak
github_2023
others
23
gmodena
gmodena
@@ -43,7 +43,7 @@ in }; home.activation = { - start-service = lib.hm.dag.entryAfter [ "writeBoundary" ] '' + flatpak-managed-install = lib.hm.dag.entryAfter [ "reloadSystemd" ] ''
Already left a comment in thread. Great catch!
nix-flatpak
github_2023
others
23
gmodena
gmodena
@@ -1,20 +1,28 @@ { cfg, pkgs, lib, installation ? "system", ... }: let + gcroots =
Could you maybe add a comment here wrt the risk of stateFile not getting GCed? Not a concern for now IMHO (see comments in thread), but I'd like to be reminded of this..
nix-flatpak
github_2023
others
10
gmodena
gmodena
@@ -1,13 +1,20 @@ -{ config, lib, pkgs, osConfig, ... }: +{ config, lib, pkgs, ... }@args: let cfg = config.services.flatpak; installation = "user"; in { - options.services.flatpak = import ./options.nix { inherit cfg lib pkgs; }; + options.services.flatpak = (import ./options.nix { inherit cfg lib pkgs; }) + // { + enable = with lib; mkOption { + type = types.bool; + default = args.osConfig.services.flatpak.enable or false;
Nice. I wonder if we could move this block to `options.nix`, but that's not a blocker for merging. I think the `or false` clause can be omitted here? `osConfig.services.flatpak.enable` is declared via a `mkEnableOption` https://github.com/NixOS/nixpkgs/blob/70ccb0dec2983e576833de94fe35081dd5d60b5b/nixos/modules/services/desktops/flatpak.nix#L17C16-L17C30 that defaults to `false` https://github.com/NixOS/nixpkgs/blob/468356287fe4ce68f58fa5cf16e8ed6fc40a1a7f/lib/options.nix#L98
sessionic
github_2023
others
103
navorite
navorite
@@ -378,5 +378,21 @@ "shortcutDeleteSelected":{ "message": "Delete selected session", "description": "The label for deleting selected session keyboard shortcut" + }, + "aboutTranslationsLabel":{ + "message": "Translations", + "description": "The label for Translations in About page" + }, + "aboutLicenseLabel":{ + "message": "Licence AGPL v3", + "description": "The label for License in About page" + }, + "aboutChangelogLabel":{ + "message": "Changelog", + "description": "The label for Changelog in About page" + }, + "aboutSourceCodeLabel":{ + "message": "Source code", + "description": "The label for Source code in About page"
```suggestion ``` Remove all of this, it was already added.
sessionic
github_2023
others
116
navorite
navorite
@@ -119,8 +119,8 @@ <div class="session-card" use:tooltip={{ - title: `${$session?.windows?.length} Window${ - $session?.windows?.length > 0 ? 's' : '' + title: `${$session?.windows?.length} ${ + $session?.windows?.length > 1 ? i18n.getMessage('WindowsTitle'), : i18n.getMessage('WindowTitle')
```suggestion i18n.getMessage($session?.windows?.length > 1 ? 'labelWindows' : 'labelWindow') ```
sessionic
github_2023
others
116
navorite
navorite
@@ -131,8 +131,8 @@ <div class="session-card" use:tooltip={{ - title: `${$session?.tabsNumber} Tab${ - $session?.tabsNumber > 0 ? 's' : '' + title: `${$session?.tabsNumber} ${ + $session?.tabsNumber > 1 ? i18n.getMessage('TabsTitle'), : i18n.getMessage('TabTitle')
```suggestion i18n.getMessage($session?.tabsNumber > 1 ? 'labelTabs' : 'labelTab') ```
sessionic
github_2023
others
116
navorite
navorite
@@ -88,7 +90,7 @@ type="text" minlength="1" maxlength="15" - placeholder="e.g. Personal" + placeholder={i18n.getMessage('NewTagInputPlaceholder')}
```suggestion placeholder={i18n.getMessage('tagPlaceholder')} ```
sessionic
github_2023
others
116
navorite
navorite
@@ -31,7 +31,7 @@ <Section title={i18n.getMessage('settingsAutosaveHeading')}> <Switch title={i18n.getMessage('settingsAutosave')} - description="Greatly reduce memory usage by not loading tab until selected" + description={i18n.getMessage('settingsAutosaveDescription')}
```suggestion ``` Oops, seems like I forgot to remove this description while adding it to settings. This has nothing to do with autosave.
sessionic
github_2023
others
104
navorite
navorite
@@ -67,6 +67,10 @@ You can contribute to the localization of the extension at [Weblate](https://hos <img src="https://hosted.weblate.org/widgets/sessionic/-/multi-auto.svg" alt="Translation status"/> </a> +## Common Questions and Answers + +You can read the project's Common Questions and Answers [here](https://github.com/navorite/sessionic/discussions/69).
```suggestion You can read the extension's Common Questions and Answers [here](https://github.com/navorite/sessionic/discussions/69). ```
sessionic
github_2023
others
64
navorite
navorite
@@ -24,7 +24,7 @@ body: label: Alternatives considered description: "Please provide a clear and concise description of any alternative solutions or features you've considered."
Maybe change it so that it is more concise ```suggestion description: "Please provide any alternative solutions or features you've considered." ```
chatgpt-demo
github_2023
typescript
346
anse-app
ddiu8081
@@ -20,7 +21,7 @@ export const post: APIRoute = async(context) => { }, }), { status: 400 }) } - if (sitePassword && sitePassword !== pass) { + if (sitePassword && (sitePassword !== pass || !passList.includes(pass))) {
wrong logic, should use `sitePassword !== pass && !passList.includes(pass))` or I prefer `!(sitePassword === pass || passList.includes(pass))`
chatgpt-demo
github_2023
others
256
anse-app
ddiu8081
@@ -10,10 +10,23 @@ ></path></svg > </button> - +<button id="backbottom_btn" class="gpt-back-bottom-btn"> + <svg + xmlns="http://www.w3.org/2000/svg" + width="1.2em" + height="1.2em" + viewBox="0 0 32 32" + ><path + fill="currentColor" + d="M16 4L6 14l1.41 1.41L15 7.83V28h2V7.83l7.59 7.58L26 14L16 4z" + ></path></svg + > +</button> <script> const backtop_btn = document.getElementById("backtop_btn") as HTMLElement; + const backbottom_btn = document.getElementById("backbottom_btn") as HTMLElement; backtop_btn.style.display = "none"; + backbottom_btn.style.display = "block";
I think the button should be hidden when the page scrolls to the bottom.
chatgpt-demo
github_2023
others
256
anse-app
yzh990918
@@ -22,7 +35,11 @@ backtop_btn.style.display = "none"; } }); - + backbottom_btn.onclick = () => { + const scrollHeight = document.documentElement.scrollHeight + console.log(scrollHeight);
debug code should be removed.
chatgpt-demo
github_2023
typescript
199
anse-app
yzh990918
@@ -1,25 +1,34 @@ import type { ChatMessage } from '@/types' -import { createSignal, Index, Show } from 'solid-js' +import { createSignal, Index, Show, onMount } from 'solid-js' import IconClear from './icons/Clear' import MessageItem from './MessageItem' import SystemRoleSettings from './SystemRoleSettings' import _ from 'lodash' import { generateSignature } from '@/utils/auth' +import KeySetting from "./KeySetting"; export default () => { - let inputRef: HTMLTextAreaElement + onMount(() => { + setCurrentKey(localStorage.getItem("key")) + }) + let inputRef: HTMLTextAreaElement,keyRef:HTMLInputElement const [currentSystemRoleSettings, setCurrentSystemRoleSettings] = createSignal('') + const [currentKey,setCurrentKey]=createSignal('') const [systemRoleEditing, setSystemRoleEditing] = createSignal(false) + const [showKey,setKey] = createSignal(false) const [messageList, setMessageList] = createSignal<ChatMessage[]>([]) - const [currentAssistantMessage, setCurrentAssistantMessage] = createSignal('') + const [currentAssistantMessage, setCurrentAssistantMessage ] = createSignal('') const [loading, setLoading] = createSignal(false) const [controller, setController] = createSignal<AbortController>(null) - const handleButtonClick = async () => { + localStorage.setItem("key", currentKey())
I think our local api-key should be encrypted.
chatgpt-demo
github_2023
others
188
anse-app
ddiu8081
@@ -32,8 +32,14 @@ </style> <script> - const darkSchema = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches - document.documentElement.classList.toggle('dark', darkSchema) + const initTheme = () => { + const darkSchema = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches + document.documentElement.classList.toggle('dark', darkSchema) + + if(localStorage.getItem('theme') === 'dark') { + document.documentElement.classList.add('dark') + } + }
1. I think it would potentially set the className twice if `localStorage.theme === 'dark'`. Try to set it once time. 2. If the user's mediaSchema is `dark` but manually set light theme in localStorage, it will stay in the dark. It may be necessary to add `else` condition.
chatgpt-demo
github_2023
typescript
107
anse-app
cyio
@@ -3,6 +3,7 @@ import { createSignal, Index, Show } from 'solid-js' import IconClear from './icons/Clear' import MessageItem from './MessageItem' import SystemRoleSettings from './SystemRoleSettings' +import _ from 'lodash'
改成按需引入好些
chatgpt-demo
github_2023
typescript
126
anse-app
ddiu8081
@@ -1,26 +1,33 @@ +import { sha256 } from "js-sha256";
Do not change the code format, please keep **single quotes** and **no semicolons**.
chatgpt-demo
github_2023
typescript
126
anse-app
ddiu8081
@@ -1,26 +1,33 @@ +import { sha256 } from "js-sha256"; + + interface AuthPayload { - t: number - m: string + t: number; + m: string; } async function digestMessage(message: string) { - const msgUint8 = new TextEncoder().encode(message); - const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); - const hashArray = Array.from(new Uint8Array(hashBuffer)); - return hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); + if (crypto && crypto.subtle && crypto.subtle.digest) { + const msgUint8 = new TextEncoder().encode(message); + const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8); + const hashArray = Array.from(new Uint8Array(hashBuffer)); + return hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); + } else { + return sha256(message).toString(); + } } export const generateSignature = async (payload: AuthPayload) => { - const { t: timestamp, m: lastMessage } = payload - const secretKey = import.meta.env.PUBLIC_SECRET_KEY as string - const signText = `${timestamp}:${lastMessage}:${secretKey}` - return await digestMessage(signText) -} + const { t: timestamp, m: lastMessage } = payload; + const secretKey = import.meta.env.PUBLIC_SECRET_KEY as string; + const signText = `${timestamp}:${lastMessage}:${secretKey}`; + return await digestMessage(signText); +}; export const verifySignature = async (payload: AuthPayload, sign: string) => { - // if (Math.abs(payload.t - Date.now()) > 1000 * 60 * 5) { - // return false - // } - const payloadSign = await generateSignature(payload) - return payloadSign === sign -} \ No newline at end of file + if (Math.abs(payload.t - Date.now()) > 1000 * 60 * 5) { + return false; + }
Before solving the issue #117, it is necessary to comment out timestamp verification.
anse
github_2023
typescript
115
anse-app
ddiu8081
@@ -0,0 +1,14 @@ +export interface GoogleFetchPayload { + apiKey: string + body: Record<string, any> +} + +export const fetchChatCompletion = async(payload: GoogleFetchPayload) => { + const { apiKey, body } = payload || {} + const initOptions = { + headers: { 'Content-Type': 'application/json' }, + method: 'POST', + body: JSON.stringify({ ...body }), + } + return fetch(`https://generativelanguage.googleapis.com/v1beta3/models/text-bison-001:generateText?key=${apiKey}`, initOptions);
I think you might want to use `models/gemini-pro` instead of `models/text-bison-001`? See https://ai.google.dev/models and curl: ``` curl https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key=$API_KEY \ -H 'Content-Type: application/json' \ -X POST \ -d '{ "contents":[ { "parts":[{"text": "Write a story about a magic backpack"}]} ] }' ```
anse
github_2023
others
79
anse-app
yzh990918
@@ -39,7 +33,6 @@ const { title } = Astro.props; (function() { const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches const setting = localStorage.getItem('theme') || 'auto' - if (setting === 'dark' || (prefersDark && setting !== 'light')) - document.documentElement.classList.toggle('dark', true) + if (setting === 'dark' || (prefersDark && setting !== 'light')) document.documentElement.classList.toggle('dark', true)
This formatting code may need to be removed.
anse
github_2023
others
4
anse-app
Sysamin478
@@ -0,0 +1,71 @@ +--- +import Layout from '../layouts/Layout.astro' +--- + +<Layout title="Password Protection">
Protect
anse
github_2023
others
4
anse-app
Sysamin478
@@ -21,3 +21,23 @@ import BuildStores from '@/components/client-only/BuildStores' <ModalsLayer client:only /> <BuildStores client:only /> </Layout> + + +<script> + async function checkCurrentAuth() { + const password = localStorage.getItem('pass') + const response = await fetch('/api/auth', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + pass: password, + }), + }) + const responseJson = await response.json() + if (responseJson.code !== 0) + window.location.href = '/password'
Protect
anse
github_2023
others
4
anse-app
Sysamin478
@@ -0,0 +1,71 @@ +--- +import Layout from '../layouts/Layout.astro' +--- + +<Layout title="Password Protection"> + <main class="h-screen col-fcc"> + <div class="op-30">Please input password</div> + <div id="input_container" class="flex mt-4"> + <input id="password_input" type="password" class="gpt-password-input" />
Protect
cargo-packager
github_2023
others
289
crabnebula-dev
lucasfernog-crabnebula
@@ -72,6 +72,13 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { tracing::debug!("Copying resources"); config.copy_resources(&resources_dir)?; + tracing::debug!("Copying embedded.provisionprofile"); + #[cfg(target_os = "macos")]
we can do this on non-macOS platforms too
cargo-packager
github_2023
others
289
crabnebula-dev
lucasfernog-crabnebula
@@ -697,7 +697,7 @@ pub struct MacOsConfig { /// /// - arranging for the compiled binary to link against those frameworks (e.g. by emitting lines like `cargo:rustc-link-lib=framework=SDL2` from your `build.rs` script) /// - /// - embedding the correct rpath in your binary (e.g. by running `install_name_tool -add_rpath "@executable_path/../Frameworks" path/to/binary` after compiling) + /// - embedding the correct path in your binary (e.g. by running `install_name_tool -add_rpath "@executable_path/../Frameworks" path/to/binary` after compiling)
this should indeed refer to rpath, it's not a typo :)
cargo-packager
github_2023
others
271
crabnebula-dev
amr-crabnebula
@@ -52,22 +52,15 @@ pub fn current_format() -> crate::Result<PackageFormat> { // maybe having a special crate for the Config struct, // that both packager and resource-resolver could be a // better alternative - if cfg!(CARGO_PACKAGER_FORMAT = "app") { - Ok(PackageFormat::App) - } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { - Ok(PackageFormat::Dmg) - } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { - Ok(PackageFormat::Wix) - } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { - Ok(PackageFormat::Nsis) - } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { - Ok(PackageFormat::Deb) - } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { - Ok(PackageFormat::AppImage) - } else if cfg!(CARGO_PACKAGER_FORMAT = "pacman") { - Ok(PackageFormat::Pacman) - } else { - Err(Error::UnkownPackageFormat) + match std::option_env!("CARGO_PACKAGER_FORMAT") {
yeah I did remove the whole build script
cargo-packager
github_2023
others
254
crabnebula-dev
amr-crabnebula
@@ -288,6 +299,49 @@ impl DebianConfig { } } + +/// A list of dependencies specified as either a list of Strings +/// or as a path to a file that lists the dependencies, one per line. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(untagged)] +#[non_exhaustive] +pub enum Dependencies { + /// The list of dependencies provided directly as a vector of Strings. + List(Vec<String>), + /// A path to the file containing the list of dependences, formatted as one per line: + /// ```text + /// libc6 + /// libxcursor1 + /// libdbus-1-3 + /// libasyncns0 + /// ... + /// ``` + Path(PathBuf),
This seems a bit unconventional, how about adding support for specifying dependencies as environment variables, `CARGO_PACKAGER_DEB_DEPS="dep1,dep2,dep3"` and `CARGO_PACKAGER_PACMAN_DEPS="dep1,dep2,dep3"`?
cargo-packager
github_2023
others
256
crabnebula-dev
amr-crabnebula
@@ -133,6 +141,11 @@ fn generate_desktop_file(config: &Config, data_dir: &Path) -> crate::Result<()> } if let Some(protocols) = &config.deep_link_protocols { + if !protocols.is_empty() { + // Use "%U" even if file associations were already provided, + // as it can also accommodate file names in addition to URLs. + exec_arg = Some("%U");
can't we use `%U` for both? will that make file associations be passed as `file://path/to/file`? because I know on macOS you can either handle file associations or handle urls and if you chose urls, file associations will be passed as `file://<path>` URL, hopefully this is the case on Linux too?
cargo-packager
github_2023
others
256
crabnebula-dev
amr-crabnebula
@@ -203,6 +203,21 @@ pub struct DebianConfig { /// MimeType={{mime_type}} /// {{/if}} /// ``` + /// + /// The `exec_arg` will be set to:
```suggestion /// The `{{exec_arg}}` will be set to: ```
cargo-packager
github_2023
others
256
crabnebula-dev
amr-crabnebula
@@ -203,6 +203,21 @@ pub struct DebianConfig { /// MimeType={{mime_type}} /// {{/if}} /// ``` + /// + /// The `exec_arg` will be set to: + /// * "%U", if at least one [Config::deep_link_protocols] was specified. + /// * This means that your application can accommodate being invoked with multiple URLs. + /// * "%F", if at least one [Config::file_associations] was specified but no deep link protocols were given, or + /// * This means that your application can accommodate being invoked with multiple file paths.
I would switch the order of these, i.e explain `%F` first and then `%U` and should also mention that `%U` will make file paths into file urls
cargo-packager
github_2023
others
246
crabnebula-dev
amr-crabnebula
@@ -158,6 +158,7 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { m.notarization_credentials .clone() .ok_or_else(|| crate::Error::MissingNotarizeAuthVars) + .or_else(|_| codesign::notarize_auth())
instead of duplicating the call here we can just make the option fall through by using `.and_then` instead of `.map`, ```rs match config .macos() .and_then(|m| m.notarization_credentials.clone()) .unwrap_or_else(codesign::notarize_auth) ```
cargo-packager
github_2023
others
246
crabnebula-dev
amr-crabnebula
@@ -154,12 +154,9 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { // notarization is required for distribution match config .macos() - .map(|m| { - m.notarization_credentials - .clone() - .ok_or_else(|| crate::Error::MissingNotarizeAuthVars) - }) - .unwrap_or_else(codesign::notarize_auth) + .and_then(|m| m.notarization_credentials.clone()) + .ok_or(crate::Error::MissingNotarizeAuthVars) + .or_else(|_| codesign::notarize_auth())
No need to add an error variant here, since if `notarization_credentials` is not set, it will fallback to `codesign::notarize_auth` and that one returns `crate::Error::MissingNotarizeAuthVars` if the needed environment variables are not set. ```suggestion .and_then(|m| m.notarization_credentials.clone()) .unwrap_or_else(codesign::notarize_auth) ```
cargo-packager
github_2023
others
196
crabnebula-dev
amr-crabnebula
@@ -285,6 +285,9 @@ where if !cli.quite { init_tracing_subscriber(cli.verbose); + if std::env::var_os("CARGO_TERM_COLOR").is_none() { + std::env::set_var("CARGO_TERM_COLOR", "always"); + }
shouldn't this be set by the user invoking the packager? or at least kept as `auto` so it automatically detects whether the current terminal has color support or not?
cargo-packager
github_2023
others
196
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,5 @@ +--- +"cargo-packager": patch +--- + +Always show command output and enhance formatting.
```suggestion --- "cargo-packager": patch "@crabnebula/packager": patch --- Show shell commands output (ex: `beforePackageCommand`) if it fails. ```
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,77 @@ +// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
this is now a replica of `updater/src/starting_binary.rs`, we should pull it into a common crate so we don't have duplicate code on our hand. Probably `cargo-packager-utils`
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,192 @@ +use error::Result; +use std::{env, path::PathBuf}; + +mod error; +mod starting_binary; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-formats")] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retrieves the currently running binary's path, taking into account security considerations. +/// +/// The path is cached as soon as possible (before even `main` runs) and that value is returned +/// repeatedly instead of fetching the path every time. It is possible for the path to not be found, +/// or explicitly disabled (see following macOS specific behavior). +/// +/// # Platform-specific behavior +/// +/// On `macOS`, this function will return an error if the original path contained any symlinks +/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the +/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*. +/// +/// # Security +/// +/// If the above platform-specific behavior does **not** take place, this function uses the +/// following resolution. +/// +/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links. +/// This avoids the usual issue of needing the file to exist at the passed path because a valid +/// current executable result for our purpose should always exist. Notably, +/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using +/// hard links. Let's cover some specific topics that relate to different ways an attacker might +/// try to trick this function into returning the wrong binary path. +/// +/// ## Symlinks ("Soft Links") +/// +/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path, +/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include +/// a symlink are rejected by default due to lesser symlink protections. This can be disabled, +/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature. +/// +/// ## Hard Links +/// +/// A [Hard Link] is a named entry that points to a file in the file system. +/// On most systems, this is what you would think of as a "file". The term is +/// used on filesystems that allow multiple entries to point to the same file. +/// The linked [Hard Link] Wikipedia page provides a decent overview. +/// +/// In short, unless the attacker was able to create the link with elevated +/// permissions, it should generally not be possible for them to hard link +/// to a file they do not have permissions to - with exception to possible +/// operating system exploits. +/// +/// There are also some platform-specific information about this below. +/// +/// ### Windows +/// +/// Windows requires a permission to be set for the user to create a symlink +/// or a hard link, regardless of ownership status of the target. Elevated +/// permissions users have the ability to create them. +/// +/// ### macOS +/// +/// macOS allows for the creation of symlinks and hard links to any file. +/// Accessing through those links will fail if the user who owns the links +/// does not have the proper permissions on the original file. +/// +/// ### Linux +/// +/// Linux allows for the creation of symlinks to any file. Accessing the +/// symlink will fail if the user who owns the symlink does not have the +/// proper permissions on the original file. +/// +/// Linux additionally provides a kernel hardening feature since version +/// 3.6 (30 September 2012). Most distributions since then have enabled +/// the protection (setting `fs.protected_hardlinks = 1`) by default, which +/// means that a vast majority of desktop Linux users should have it enabled. +/// **The feature prevents the creation of hardlinks that the user does not own +/// or have read/write access to.** [See the patch that enabled this]. +/// +/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link +/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7 +pub fn current_exe() -> Result<PathBuf> {
ditto
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,8 @@ +# cargo-packager-resource-resolver + +Most of the code in this crate comes from [tauri-utils](https://github.com/tauri-apps/tauri/tree/dev/core/tauri-utils).
We should remove this and document what this crate does and how to use it. We should also mention it in `cargo-packager` rust docs and README.md
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,192 @@ +use error::Result; +use std::{env, path::PathBuf}; + +mod error; +mod starting_binary; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-formats")] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retrieves the currently running binary's path, taking into account security considerations. +/// +/// The path is cached as soon as possible (before even `main` runs) and that value is returned +/// repeatedly instead of fetching the path every time. It is possible for the path to not be found, +/// or explicitly disabled (see following macOS specific behavior). +/// +/// # Platform-specific behavior +/// +/// On `macOS`, this function will return an error if the original path contained any symlinks +/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the +/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*. +/// +/// # Security +/// +/// If the above platform-specific behavior does **not** take place, this function uses the +/// following resolution. +/// +/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links. +/// This avoids the usual issue of needing the file to exist at the passed path because a valid +/// current executable result for our purpose should always exist. Notably, +/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using +/// hard links. Let's cover some specific topics that relate to different ways an attacker might +/// try to trick this function into returning the wrong binary path. +/// +/// ## Symlinks ("Soft Links") +/// +/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path, +/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include +/// a symlink are rejected by default due to lesser symlink protections. This can be disabled, +/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature. +/// +/// ## Hard Links +/// +/// A [Hard Link] is a named entry that points to a file in the file system. +/// On most systems, this is what you would think of as a "file". The term is +/// used on filesystems that allow multiple entries to point to the same file. +/// The linked [Hard Link] Wikipedia page provides a decent overview. +/// +/// In short, unless the attacker was able to create the link with elevated +/// permissions, it should generally not be possible for them to hard link +/// to a file they do not have permissions to - with exception to possible +/// operating system exploits. +/// +/// There are also some platform-specific information about this below. +/// +/// ### Windows +/// +/// Windows requires a permission to be set for the user to create a symlink +/// or a hard link, regardless of ownership status of the target. Elevated +/// permissions users have the ability to create them. +/// +/// ### macOS +/// +/// macOS allows for the creation of symlinks and hard links to any file. +/// Accessing through those links will fail if the user who owns the links +/// does not have the proper permissions on the original file. +/// +/// ### Linux +/// +/// Linux allows for the creation of symlinks to any file. Accessing the +/// symlink will fail if the user who owns the symlink does not have the +/// proper permissions on the original file. +/// +/// Linux additionally provides a kernel hardening feature since version +/// 3.6 (30 September 2012). Most distributions since then have enabled +/// the protection (setting `fs.protected_hardlinks = 1`) by default, which +/// means that a vast majority of desktop Linux users should have it enabled. +/// **The feature prevents the creation of hardlinks that the user does not own +/// or have read/write access to.** [See the patch that enabled this]. +/// +/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link +/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7 +pub fn current_exe() -> Result<PathBuf> { + starting_binary::STARTING_BINARY + .cloned() + .map_err(|e| Error::Io("Can't detect the path of the current exe".to_string(), e)) +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver as resource_resolver; +/// use resource_resolver::{PackageFormat, resource_dir_with_suffix}; +/// +/// resource_dir_with_suffix(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resource_dir_with_suffix(package_format: PackageFormat, suffix: &str) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR") + .map_err(|e| { + match e { + env::VarError::NotPresent => { + Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string()) + }, + _ => Error::Var("Can't access CARGO_MANIFEST_DIR environnement variable".to_string(), e) + } + })?; + Ok(PathBuf::from(root_crate_dir).join(suffix)) + } + PackageFormat::App | PackageFormat::Dmg => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + exe_dir + .join("../Resources") + .canonicalize() + .map_err(|e| Error::Io("".to_string(), e)) + } + PackageFormat::Wix => Err(Error::UnsupportedPlatform), + PackageFormat::Nsis => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + Ok(exe_dir.to_path_buf()) + } + PackageFormat::Deb => { + // maybe this is not reliable, and we need to get the app name from argument + let exe = current_exe()?; + let binary_name = exe.file_name().unwrap().to_string_lossy(); + + let path = format!("/usr/lib/{}/", binary_name); + Ok(PathBuf::from(path)) + } + PackageFormat::AppImage => todo!(), + } +} + +/// Retreive the resource path of your app, packaged with cargo packager. +#[inline] +pub fn resource_dir(package_format: PackageFormat) -> Result<PathBuf> {
```suggestion pub fn resources_dir(package_format: PackageFormat) -> Result<PathBuf> { ```
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,192 @@ +use error::Result; +use std::{env, path::PathBuf}; + +mod error; +mod starting_binary; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-formats")] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retrieves the currently running binary's path, taking into account security considerations. +/// +/// The path is cached as soon as possible (before even `main` runs) and that value is returned +/// repeatedly instead of fetching the path every time. It is possible for the path to not be found, +/// or explicitly disabled (see following macOS specific behavior). +/// +/// # Platform-specific behavior +/// +/// On `macOS`, this function will return an error if the original path contained any symlinks +/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the +/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*. +/// +/// # Security +/// +/// If the above platform-specific behavior does **not** take place, this function uses the +/// following resolution. +/// +/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links. +/// This avoids the usual issue of needing the file to exist at the passed path because a valid +/// current executable result for our purpose should always exist. Notably, +/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using +/// hard links. Let's cover some specific topics that relate to different ways an attacker might +/// try to trick this function into returning the wrong binary path. +/// +/// ## Symlinks ("Soft Links") +/// +/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path, +/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include +/// a symlink are rejected by default due to lesser symlink protections. This can be disabled, +/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature. +/// +/// ## Hard Links +/// +/// A [Hard Link] is a named entry that points to a file in the file system. +/// On most systems, this is what you would think of as a "file". The term is +/// used on filesystems that allow multiple entries to point to the same file. +/// The linked [Hard Link] Wikipedia page provides a decent overview. +/// +/// In short, unless the attacker was able to create the link with elevated +/// permissions, it should generally not be possible for them to hard link +/// to a file they do not have permissions to - with exception to possible +/// operating system exploits. +/// +/// There are also some platform-specific information about this below. +/// +/// ### Windows +/// +/// Windows requires a permission to be set for the user to create a symlink +/// or a hard link, regardless of ownership status of the target. Elevated +/// permissions users have the ability to create them. +/// +/// ### macOS +/// +/// macOS allows for the creation of symlinks and hard links to any file. +/// Accessing through those links will fail if the user who owns the links +/// does not have the proper permissions on the original file. +/// +/// ### Linux +/// +/// Linux allows for the creation of symlinks to any file. Accessing the +/// symlink will fail if the user who owns the symlink does not have the +/// proper permissions on the original file. +/// +/// Linux additionally provides a kernel hardening feature since version +/// 3.6 (30 September 2012). Most distributions since then have enabled +/// the protection (setting `fs.protected_hardlinks = 1`) by default, which +/// means that a vast majority of desktop Linux users should have it enabled. +/// **The feature prevents the creation of hardlinks that the user does not own +/// or have read/write access to.** [See the patch that enabled this]. +/// +/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link +/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7 +pub fn current_exe() -> Result<PathBuf> { + starting_binary::STARTING_BINARY + .cloned() + .map_err(|e| Error::Io("Can't detect the path of the current exe".to_string(), e)) +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver as resource_resolver; +/// use resource_resolver::{PackageFormat, resource_dir_with_suffix}; +/// +/// resource_dir_with_suffix(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resource_dir_with_suffix(package_format: PackageFormat, suffix: &str) -> Result<PathBuf> {
let's rename this ```suggestion pub fn resolve_resource<P: AsRef<Path>>(package_format: PackageFormat, path: P) -> Result<PathBuf> { ```
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,192 @@ +use error::Result;
Missing documentation for the crate
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,192 @@ +use error::Result; +use std::{env, path::PathBuf}; + +mod error; +mod starting_binary; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-formats")] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retrieves the currently running binary's path, taking into account security considerations. +/// +/// The path is cached as soon as possible (before even `main` runs) and that value is returned +/// repeatedly instead of fetching the path every time. It is possible for the path to not be found, +/// or explicitly disabled (see following macOS specific behavior). +/// +/// # Platform-specific behavior +/// +/// On `macOS`, this function will return an error if the original path contained any symlinks +/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the +/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*. +/// +/// # Security +/// +/// If the above platform-specific behavior does **not** take place, this function uses the +/// following resolution. +/// +/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links. +/// This avoids the usual issue of needing the file to exist at the passed path because a valid +/// current executable result for our purpose should always exist. Notably, +/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using +/// hard links. Let's cover some specific topics that relate to different ways an attacker might +/// try to trick this function into returning the wrong binary path. +/// +/// ## Symlinks ("Soft Links") +/// +/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path, +/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include +/// a symlink are rejected by default due to lesser symlink protections. This can be disabled, +/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature. +/// +/// ## Hard Links +/// +/// A [Hard Link] is a named entry that points to a file in the file system. +/// On most systems, this is what you would think of as a "file". The term is +/// used on filesystems that allow multiple entries to point to the same file. +/// The linked [Hard Link] Wikipedia page provides a decent overview. +/// +/// In short, unless the attacker was able to create the link with elevated +/// permissions, it should generally not be possible for them to hard link +/// to a file they do not have permissions to - with exception to possible +/// operating system exploits. +/// +/// There are also some platform-specific information about this below. +/// +/// ### Windows +/// +/// Windows requires a permission to be set for the user to create a symlink +/// or a hard link, regardless of ownership status of the target. Elevated +/// permissions users have the ability to create them. +/// +/// ### macOS +/// +/// macOS allows for the creation of symlinks and hard links to any file. +/// Accessing through those links will fail if the user who owns the links +/// does not have the proper permissions on the original file. +/// +/// ### Linux +/// +/// Linux allows for the creation of symlinks to any file. Accessing the +/// symlink will fail if the user who owns the symlink does not have the +/// proper permissions on the original file. +/// +/// Linux additionally provides a kernel hardening feature since version +/// 3.6 (30 September 2012). Most distributions since then have enabled +/// the protection (setting `fs.protected_hardlinks = 1`) by default, which +/// means that a vast majority of desktop Linux users should have it enabled. +/// **The feature prevents the creation of hardlinks that the user does not own +/// or have read/write access to.** [See the patch that enabled this]. +/// +/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link +/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7 +pub fn current_exe() -> Result<PathBuf> { + starting_binary::STARTING_BINARY + .cloned() + .map_err(|e| Error::Io("Can't detect the path of the current exe".to_string(), e)) +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver as resource_resolver; +/// use resource_resolver::{PackageFormat, resource_dir_with_suffix}; +/// +/// resource_dir_with_suffix(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resource_dir_with_suffix(package_format: PackageFormat, suffix: &str) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR")
`CARGO_MANIFEST_DIR` is a build time only environment variable. We should ignore this format and return the path as is.
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,192 @@ +use error::Result; +use std::{env, path::PathBuf}; + +mod error; +mod starting_binary; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-formats")] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retrieves the currently running binary's path, taking into account security considerations. +/// +/// The path is cached as soon as possible (before even `main` runs) and that value is returned +/// repeatedly instead of fetching the path every time. It is possible for the path to not be found, +/// or explicitly disabled (see following macOS specific behavior). +/// +/// # Platform-specific behavior +/// +/// On `macOS`, this function will return an error if the original path contained any symlinks +/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the +/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*. +/// +/// # Security +/// +/// If the above platform-specific behavior does **not** take place, this function uses the +/// following resolution. +/// +/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links. +/// This avoids the usual issue of needing the file to exist at the passed path because a valid +/// current executable result for our purpose should always exist. Notably, +/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using +/// hard links. Let's cover some specific topics that relate to different ways an attacker might +/// try to trick this function into returning the wrong binary path. +/// +/// ## Symlinks ("Soft Links") +/// +/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path, +/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include +/// a symlink are rejected by default due to lesser symlink protections. This can be disabled, +/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature. +/// +/// ## Hard Links +/// +/// A [Hard Link] is a named entry that points to a file in the file system. +/// On most systems, this is what you would think of as a "file". The term is +/// used on filesystems that allow multiple entries to point to the same file. +/// The linked [Hard Link] Wikipedia page provides a decent overview. +/// +/// In short, unless the attacker was able to create the link with elevated +/// permissions, it should generally not be possible for them to hard link +/// to a file they do not have permissions to - with exception to possible +/// operating system exploits. +/// +/// There are also some platform-specific information about this below. +/// +/// ### Windows +/// +/// Windows requires a permission to be set for the user to create a symlink +/// or a hard link, regardless of ownership status of the target. Elevated +/// permissions users have the ability to create them. +/// +/// ### macOS +/// +/// macOS allows for the creation of symlinks and hard links to any file. +/// Accessing through those links will fail if the user who owns the links +/// does not have the proper permissions on the original file. +/// +/// ### Linux +/// +/// Linux allows for the creation of symlinks to any file. Accessing the +/// symlink will fail if the user who owns the symlink does not have the +/// proper permissions on the original file. +/// +/// Linux additionally provides a kernel hardening feature since version +/// 3.6 (30 September 2012). Most distributions since then have enabled +/// the protection (setting `fs.protected_hardlinks = 1`) by default, which +/// means that a vast majority of desktop Linux users should have it enabled. +/// **The feature prevents the creation of hardlinks that the user does not own +/// or have read/write access to.** [See the patch that enabled this]. +/// +/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link +/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7 +pub fn current_exe() -> Result<PathBuf> { + starting_binary::STARTING_BINARY + .cloned() + .map_err(|e| Error::Io("Can't detect the path of the current exe".to_string(), e)) +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver as resource_resolver; +/// use resource_resolver::{PackageFormat, resource_dir_with_suffix}; +/// +/// resource_dir_with_suffix(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resource_dir_with_suffix(package_format: PackageFormat, suffix: &str) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR") + .map_err(|e| { + match e { + env::VarError::NotPresent => { + Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string()) + }, + _ => Error::Var("Can't access CARGO_MANIFEST_DIR environnement variable".to_string(), e) + } + })?; + Ok(PathBuf::from(root_crate_dir).join(suffix)) + } + PackageFormat::App | PackageFormat::Dmg => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + exe_dir + .join("../Resources") + .canonicalize() + .map_err(|e| Error::Io("".to_string(), e)) + } + PackageFormat::Wix => Err(Error::UnsupportedPlatform),
This should be the same as `Nsis` format.
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,192 @@ +use error::Result; +use std::{env, path::PathBuf}; + +mod error; +mod starting_binary; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-formats")] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retrieves the currently running binary's path, taking into account security considerations. +/// +/// The path is cached as soon as possible (before even `main` runs) and that value is returned +/// repeatedly instead of fetching the path every time. It is possible for the path to not be found, +/// or explicitly disabled (see following macOS specific behavior). +/// +/// # Platform-specific behavior +/// +/// On `macOS`, this function will return an error if the original path contained any symlinks +/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the +/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*. +/// +/// # Security +/// +/// If the above platform-specific behavior does **not** take place, this function uses the +/// following resolution. +/// +/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links. +/// This avoids the usual issue of needing the file to exist at the passed path because a valid +/// current executable result for our purpose should always exist. Notably, +/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using +/// hard links. Let's cover some specific topics that relate to different ways an attacker might +/// try to trick this function into returning the wrong binary path. +/// +/// ## Symlinks ("Soft Links") +/// +/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path, +/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include +/// a symlink are rejected by default due to lesser symlink protections. This can be disabled, +/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature. +/// +/// ## Hard Links +/// +/// A [Hard Link] is a named entry that points to a file in the file system. +/// On most systems, this is what you would think of as a "file". The term is +/// used on filesystems that allow multiple entries to point to the same file. +/// The linked [Hard Link] Wikipedia page provides a decent overview. +/// +/// In short, unless the attacker was able to create the link with elevated +/// permissions, it should generally not be possible for them to hard link +/// to a file they do not have permissions to - with exception to possible +/// operating system exploits. +/// +/// There are also some platform-specific information about this below. +/// +/// ### Windows +/// +/// Windows requires a permission to be set for the user to create a symlink +/// or a hard link, regardless of ownership status of the target. Elevated +/// permissions users have the ability to create them. +/// +/// ### macOS +/// +/// macOS allows for the creation of symlinks and hard links to any file. +/// Accessing through those links will fail if the user who owns the links +/// does not have the proper permissions on the original file. +/// +/// ### Linux +/// +/// Linux allows for the creation of symlinks to any file. Accessing the +/// symlink will fail if the user who owns the symlink does not have the +/// proper permissions on the original file. +/// +/// Linux additionally provides a kernel hardening feature since version +/// 3.6 (30 September 2012). Most distributions since then have enabled +/// the protection (setting `fs.protected_hardlinks = 1`) by default, which +/// means that a vast majority of desktop Linux users should have it enabled. +/// **The feature prevents the creation of hardlinks that the user does not own +/// or have read/write access to.** [See the patch that enabled this]. +/// +/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link +/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7 +pub fn current_exe() -> Result<PathBuf> { + starting_binary::STARTING_BINARY + .cloned() + .map_err(|e| Error::Io("Can't detect the path of the current exe".to_string(), e)) +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver as resource_resolver; +/// use resource_resolver::{PackageFormat, resource_dir_with_suffix}; +/// +/// resource_dir_with_suffix(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resource_dir_with_suffix(package_format: PackageFormat, suffix: &str) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR") + .map_err(|e| { + match e { + env::VarError::NotPresent => { + Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string()) + }, + _ => Error::Var("Can't access CARGO_MANIFEST_DIR environnement variable".to_string(), e) + } + })?; + Ok(PathBuf::from(root_crate_dir).join(suffix)) + } + PackageFormat::App | PackageFormat::Dmg => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + exe_dir + .join("../Resources") + .canonicalize() + .map_err(|e| Error::Io("".to_string(), e)) + } + PackageFormat::Wix => Err(Error::UnsupportedPlatform), + PackageFormat::Nsis => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + Ok(exe_dir.to_path_buf()) + } + PackageFormat::Deb => { + // maybe this is not reliable, and we need to get the app name from argument + let exe = current_exe()?; + let binary_name = exe.file_name().unwrap().to_string_lossy(); + + let path = format!("/usr/lib/{}/", binary_name);
@lucasfernog-crabnebula what do you think about this?
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,13 @@ +use std::env; + +fn main() { + track_var("CARGO_PACKAGER_FORMAT"); + track_var("CARGO_PACKAGER_MAIN_BINARY_NAME"); +} + +fn track_var(key: &str) { + println!("cargo:rerun-if-env-changed={}", key); + if let Ok(var) = env::var(key) { + println!("cargo:rustc-cfg={}=\"{}\"", key, var); + } +}
let's simplify this since we only need to track `CARGO_PACKAGER_FORMAT`, also this tracking should be done only if `auto-detect-format` feature is active.
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,17 @@ +[package] +name = "cargo-packager-resource-resolver" +description = "Cargo packager resource resolver" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" + +[dependencies] +thiserror = "1" +ctor = "0.2" + +[features] +process-relaunch-dangerous-allow-symlink-macos = [ ] +auto-detect-formats = [ ]
```suggestion auto-detect-format = [ ] ```
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -182,6 +182,10 @@ fn run_before_each_packaging_command_hook( let output = cmd .env("CARGO_PACKAGER_FORMATS", formats_comma_separated) .env("CARGO_PACKAGER_FORMAT", format) + .env( + "CARGO_PACKAGER_MAIN_BINARY_NAME", + config.main_binary_name()?, + )
Let's remove this for now since it doesn't have a usecase atm.
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,24 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +/// The result type of `resource-resolver`. +pub type Result<T> = std::result::Result<T, Error>; + +/// The error type of `resource-resolver`. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// Tried to get resource on an unsupported platform + #[error("Unsupported platform for reading resources")] + UnsupportedPlatform, + /// IO error + #[error("{0}: {1}")] + Io(String, std::io::Error), + /// Environement error
```suggestion /// Environment error ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,24 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +/// The result type of `resource-resolver`. +pub type Result<T> = std::result::Result<T, Error>; + +/// The error type of `resource-resolver`. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// Tried to get resource on an unsupported platform + #[error("Unsupported platform for reading resources")] + UnsupportedPlatform, + /// IO error + #[error("{0}: {1}")] + Io(String, std::io::Error), + /// Environement error + #[error("{0}")] + Env(String), + /// Environement variable error
```suggestion /// Environment variable error ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager).
```suggestion //! Resource resolver for apps that were packaged by [`cargo-packager`](https://docs.rs/cargo-packager). ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path
we should add an example here of the detect feature
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! + +use error::Result; +use std::{ + env, + path::{Path, PathBuf}, +}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-format")] +#[must_use] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver::{resolve_resource, PackageFormat}; +/// +/// resolve_resource(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resolve_resource<P: AsRef<Path>>(package_format: PackageFormat, path: P) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR") + .map_err(|e| { + match e { + env::VarError::NotPresent => { + Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string()) + }, + _ => Error::Var("Can't access CARGO_MANIFEST_DIR environnement variable".to_string(), e) + } + })?; + Ok(PathBuf::from(root_crate_dir).join(path)) + } + PackageFormat::App | PackageFormat::Dmg => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + exe_dir + .join("../Resources") + .canonicalize() + .map_err(|e| Error::Io("".to_string(), e)) + } + PackageFormat::Wix | PackageFormat::Nsis => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + Ok(exe_dir.to_path_buf()) + } + PackageFormat::Deb => { + // maybe this is not reliable, and we need to get the app name from argument + let exe = current_exe()?; + let binary_name = exe.file_name().unwrap().to_string_lossy(); + + let path = format!("/usr/lib/{}/", binary_name); + Ok(PathBuf::from(path)) + } + PackageFormat::AppImage => Err(Error::UnsupportedPlatform), + } +} + +/// Retreive the resource path of your app, packaged with cargo packager.
```suggestion /// Retrieve the resource path of your app, packaged with cargo packager. ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! + +use error::Result; +use std::{ + env, + path::{Path, PathBuf}, +}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-format")] +#[must_use] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retreive the resource path of your app, packaged with cargo packager.
```suggestion /// Retrieve the resource path of your app, packaged with cargo packager. ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! + +use error::Result; +use std::{ + env, + path::{Path, PathBuf}, +}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute.
```suggestion /// and when the `before-each-package-command` Cargo feature is enabled. ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,16 @@ +[package] +name = "cargo-packager-resource-resolver" +description = "Cargo packager resource resolver" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true
```suggestion repository.workspace = true [package.metadata.docs.rs] features = [ "auto-detect-format " ] ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! + +use error::Result; +use std::{ + env, + path::{Path, PathBuf}, +}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-format")] +#[must_use] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver::{resolve_resource, PackageFormat}; +/// +/// resolve_resource(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resolve_resource<P: AsRef<Path>>(package_format: PackageFormat, path: P) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR") + .map_err(|e| { + match e { + env::VarError::NotPresent => { + Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string())
```suggestion Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string()) ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! + +use error::Result; +use std::{ + env, + path::{Path, PathBuf}, +}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-format")] +#[must_use] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver::{resolve_resource, PackageFormat}; +/// +/// resolve_resource(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resolve_resource<P: AsRef<Path>>(package_format: PackageFormat, path: P) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR") + .map_err(|e| { + match e { + env::VarError::NotPresent => { + Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string()) + }, + _ => Error::Var("Can't access CARGO_MANIFEST_DIR environnement variable".to_string(), e)
```suggestion _ => Error::Var("Can't access CARGO_MANIFEST_DIR environnement variable".to_string(), e) ```
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! + +use error::Result; +use std::{ + env, + path::{Path, PathBuf}, +}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-format")] +#[must_use] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver::{resolve_resource, PackageFormat}; +/// +/// resolve_resource(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resolve_resource<P: AsRef<Path>>(package_format: PackageFormat, path: P) -> Result<PathBuf> {
this function name is kinda weird, in Tauri it appends the `path` to the resources path, but here it's more of a fallback for the None package format.. can't we force the user to provide that path via the None variant itself? like `PackageFormat::None { local_resources_path: &'static str }`
cargo-packager
github_2023
others
106
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,149 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that was packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! + +use error::Result; +use std::{ + env, + path::{Path, PathBuf}, +}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and the `before-each-package-command` atribute. +#[cfg(feature = "auto-detect-format")] +#[must_use] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retreive the resource path of your app, packaged with cargo packager. +/// This function behave the same as [`resource_dir`], except it accepts +/// a parameter that will be happened to the resource path when no packaging format +/// is used. +/// +/// Example: You want to include the folder `crate/resource/icons/`. +/// +/// - With `cargo run` command, you will have to execute +/// `resource_dir().unwrap().join("resource/icons/")` to get the path. +/// - With any other formats, it will be `resource_dir().unwrap().join("icons/")`. +/// +/// ``` +/// use cargo_packager_resource_resolver::{resolve_resource, PackageFormat}; +/// +/// resolve_resource(PackageFormat::None, "resource").unwrap().join("icons/"); +/// ``` +pub fn resolve_resource<P: AsRef<Path>>(package_format: PackageFormat, path: P) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + let root_crate_dir = env::var("CARGO_MANIFEST_DIR") + .map_err(|e| { + match e { + env::VarError::NotPresent => { + Error::Env("PackageFormat::None was use, but CARGO_MANIFEST_DIR environnement variable was not defined".to_string()) + }, + _ => Error::Var("Can't access CARGO_MANIFEST_DIR environnement variable".to_string(), e) + } + })?; + Ok(PathBuf::from(root_crate_dir).join(path)) + } + PackageFormat::App | PackageFormat::Dmg => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + exe_dir + .join("../Resources") + .canonicalize() + .map_err(|e| Error::Io("".to_string(), e)) + } + PackageFormat::Wix | PackageFormat::Nsis => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + Ok(exe_dir.to_path_buf()) + } + PackageFormat::Deb => { + // maybe this is not reliable, and we need to get the app name from argument + let exe = current_exe()?; + let binary_name = exe.file_name().unwrap().to_string_lossy(); + + let path = format!("/usr/lib/{}/", binary_name); + Ok(PathBuf::from(path)) + } + PackageFormat::AppImage => Err(Error::UnsupportedPlatform),
tauri supports it: https://github.com/tauri-apps/tauri/blob/97e334129956159bbd60e1c531b6acd3bc6139a6/core/tauri-utils/src/platform.rs#L226
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,129 @@ +// Copyright 2023-2023 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! # cargo-packager-updater +//! +//! Resource resolver for apps that were packaged by [`cargo-packager`](https://docs.rs/cargo-packager). +//! +//! It resolves the root path which contains resources, which was set using the `resources` +//! field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html). +//! +//! ## Get the resource path +//! +//! ``` +//! use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +//! +//! let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +//! ``` +//! ## Automatically detect formats +//! +//! <div class="warning"> +//! +//! This feature is only available for apps that were built with cargo packager. So the node js binding will not work. +//! +//! </div> +//! +//! 1. Make sure to use the `before_each_package_command` field of [cargo packager configuration](https://docs.rs/cargo-packager/latest/cargo_packager/config/struct.Config.html) to build your app (this will not work with the `before_packaging_command` field). +//! 2. Active the feature `auto-detect-format`. +//! +//! ```rs +//! use cargo_packager_resource_resolver::{resources_dir, current_format}; +//! +//! let resource_path = resources_dir(current_format()).unwrap(); +//! ``` +//! +use error::Result; +use std::{env, path::PathBuf}; + +mod error; + +pub use error::Error; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PackageFormat { + /// When no format is used (`cargo run`) + None, + /// The macOS application bundle (.app). + App, + /// The macOS DMG package (.dmg). + Dmg, + /// The Microsoft Software Installer (.msi) through WiX Toolset. + Wix, + /// The NSIS installer (.exe). + Nsis, + /// The Linux Debian package (.deb). + Deb, + /// The Linux AppImage package (.AppImage). + AppImage, +} + +/// Get the current package format. +/// Can only be used if the app was build with cargo-packager +/// and when the `before-each-package-command` Cargo feature is enabled. +#[cfg(feature = "auto-detect-format")] +#[must_use] +pub fn current_format() -> PackageFormat { + // sync with PackageFormat::short_name function of packager crate + // maybe having a special crate for the Config struct, + // that both packager and resource-resolver could be a + // better alternative + if cfg!(CARGO_PACKAGER_FORMAT = "app") { + PackageFormat::App + } else if cfg!(CARGO_PACKAGER_FORMAT = "dmg") { + PackageFormat::Dmg + } else if cfg!(CARGO_PACKAGER_FORMAT = "wix") { + PackageFormat::Wix + } else if cfg!(CARGO_PACKAGER_FORMAT = "nsis") { + PackageFormat::Nsis + } else if cfg!(CARGO_PACKAGER_FORMAT = "deb") { + PackageFormat::Deb + } else if cfg!(CARGO_PACKAGER_FORMAT = "appimage") { + PackageFormat::AppImage + } else { + PackageFormat::None + } +} + +/// Retrieve the resource path of your app, packaged with cargo packager. +/// +/// ## Example +/// +/// ``` +/// use cargo_packager_resource_resolver::{resources_dir, PackageFormat}; +/// +/// let resource_path = resources_dir(PackageFormat::Nsis).unwrap(); +/// ``` +/// +pub fn resources_dir(package_format: PackageFormat) -> Result<PathBuf> { + match package_format { + PackageFormat::None => { + env::current_dir().map_err(|e| Error::Io("Can't access current dir".to_string(), e)) + } + PackageFormat::App | PackageFormat::Dmg => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + exe_dir + .join("../Resources") + .canonicalize() + .map_err(|e| Error::Io("".to_string(), e)) + } + PackageFormat::Wix | PackageFormat::Nsis => { + let exe = current_exe()?; + let exe_dir = exe.parent().unwrap(); + Ok(exe_dir.to_path_buf()) + } + PackageFormat::Deb | PackageFormat::AppImage => {
we should port the implementation for this from https://github.com/tauri-apps/tauri/blob/97e334129956159bbd60e1c531b6acd3bc6139a6/core/tauri-utils/src/platform.rs#L226
cargo-packager
github_2023
others
106
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,19 @@ +[package] +name = "cargo-packager-resource-resolver" +description = "Cargo packager resource resolver" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[package.metadata.docs.rs] +features = [ "auto-detect-format " ]
```suggestion features = [ "auto-detect-format" ] ```
cargo-packager
github_2023
others
148
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,6 @@ +--- +"cargo-packager": minor +"@crabnebula/packager": minor +--- + +Added config feature to control excluded libs in build_appimage.sh
```suggestion Added config option to control excluded libs when packaging AppImage ```
cargo-packager
github_2023
others
148
crabnebula-dev
lucasfernog-crabnebula
@@ -267,6 +267,10 @@ pub struct AppImageConfig { /// you'd specify `gtk` as the key and its url as the value. #[serde(alias = "linuxdeploy-plugins", alias = "linuxdeploy_plugins")] pub linuxdeploy_plugins: Option<HashMap<String, String>>, + /// List of globs of libraries to exclude from the final APpImage.
```suggestion /// List of globs of libraries to exclude from the final AppImage. ```
cargo-packager
github_2023
others
140
crabnebula-dev
amr-crabnebula
@@ -145,12 +146,64 @@ pub fn delete_keychain() { .output_ok(); } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub struct SignTarget { pub path: PathBuf, pub is_native_binary: bool, } +impl Ord for SignTarget { + fn cmp(&self, other: &Self) -> Ordering { + // This ordering implementation ensures that signing targets with + // a shorter path are greater than signing targets with a longer path. + // + // When sorting in ascending order, this means we first get the long paths + // and then the shorter paths (aka depth-first). This is required in order + // for signing to work properly on macOS since more deeply nested files + // need to be signed first. + + let mut self_iter = self.path.iter(); + let mut other_iter = other.path.iter(); + + let mut self_prev = None; + let mut other_prev = None; + + loop { + match (self_iter.next(), other_iter.next()) { + (Some(s), Some(o)) => { + self_prev = Some(s); + other_prev = Some(o); + } + // This path has less components than the other path + // and thus should come later (Ordering greater) + (None, Some(_)) => return Ordering::Greater, + + // This path has more components than the previous path + // and thus should come earlier + (Some(_), None) => return Ordering::Less, + + (None, None) => { + return match (self_prev, other_prev) { + // Compare by name + (Some(s), Some(o)) => s.cmp(o), + + // See above for ordering when component size is not the same + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (None, None) => Ordering::Equal, + }; + } + } + } + }
Can't we just check the components count? if higher, path is longer, less, path is shorter, otherwise equal
cargo-packager
github_2023
others
143
crabnebula-dev
lucasfernog-crabnebula
@@ -0,0 +1,5 @@ +--- +"@crabnebula/updater": minor
```suggestion "@crabnebula/updater": patch ```
cargo-packager
github_2023
others
143
crabnebula-dev
lucasfernog-crabnebula
@@ -178,94 +179,196 @@ impl Update { } } +type TaskCallbackFunction<T> = Option<ThreadsafeFunction<T, ErrorStrategy::Fatal>>; + +pub struct DownloadTask { + update: cargo_packager_updater::Update, + on_chunk: TaskCallbackFunction<(u32, Option<u32>)>, + on_download_finished: TaskCallbackFunction<()>, +} + +impl DownloadTask { + pub fn create( + update: &Update, + on_chunk: TaskCallbackFunction<(u32, Option<u32>)>, + on_download_finished: TaskCallbackFunction<()>, + ) -> Result<Self> { + Ok(Self { + update: update.create_update()?, + on_chunk, + on_download_finished, + }) + } +} + +impl Task for DownloadTask {
could use a `#[derive(napi_derive::napi)] impl Task for T` instead of the `ts_return_type` hack but it's still not perfect for the JsArrayBuffer type, so doesn't matter
cargo-packager
github_2023
others
136
crabnebula-dev
naman-crabnebula
@@ -90,8 +90,15 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { let mut buffer = [0; 4]; std::io::Read::read_exact(&mut open_file, &mut buffer)?; - const MACH_O_MAGIC_NUMBERS: [u32; 5] = - [0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcefaedfe, 0xcffaedfe]; + const MACH_O_MAGIC_NUMBERS: [u32; 5] = [
Replace this with [u32; 7]
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -488,6 +509,84 @@ impl AppImageConfig { } } +/// The Linux pacman configuration. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[non_exhaustive] +pub struct PacmanConfig { + // Arch Linux Specific settings.
```suggestion ```
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -488,6 +509,84 @@ impl AppImageConfig { } } +/// The Linux pacman configuration. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[non_exhaustive] +pub struct PacmanConfig { + // Arch Linux Specific settings. + /// List of Pacman dependencies. + pub depends: Option<Vec<String>>, + /// Additional packages that are provided by this app. + pub provides: Option<Vec<String>>,
Should sidecars (external binaries) be included in this or rather what does this option do?
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -488,6 +509,84 @@ impl AppImageConfig { } } +/// The Linux pacman configuration. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[non_exhaustive] +pub struct PacmanConfig { + // Arch Linux Specific settings. + /// List of Pacman dependencies. + pub depends: Option<Vec<String>>, + /// Additional packages that are provided by this app. + pub provides: Option<Vec<String>>, + /// Packages that conflict with the app. + pub conflicts: Option<Vec<String>>, + /// Only use if this app replaces some obsolete packages + pub replaces: Option<Vec<String>>, + /// Source of the package to be stored at PKGBUILD. + /// PKGBUILD is a bash script, so version can be referred as ${pkgver} + pub source: Option<Vec<String>>,
Can we give a bit of more information about each option and add some links to the official docs?
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) {
we shouldn't depend on `deb` config here, if a `files` option is needed, we should add it under `pacman` config
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?;
why do we need to make it kebab case? and also why do we add `-bin` suffix?
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?;
we should add an option to control this
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?;
do we need to set this?
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?;
do we need to join with a new line, shouldn't a space be enough?
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default(); + writeln!(file, "provides=({})", provides.join(" \n"))?;
ditto
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default(); + writeln!(file, "provides=({})", provides.join(" \n"))?; + + let conflicts = config + .pacman() + .cloned() + .and_then(|d| d.conflicts) + .unwrap_or_default(); + writeln!(file, "conflicts=({})", conflicts.join(" \n"))?;
ditto
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default(); + writeln!(file, "provides=({})", provides.join(" \n"))?; + + let conflicts = config + .pacman() + .cloned() + .and_then(|d| d.conflicts) + .unwrap_or_default(); + writeln!(file, "conflicts=({})", conflicts.join(" \n"))?; + + let replaces = config + .pacman() + .cloned() + .and_then(|d| d.replaces) + .unwrap_or_default(); + writeln!(file, "replaces=({})", replaces.join(" \n"))?;
ditto
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default(); + writeln!(file, "provides=({})", provides.join(" \n"))?; + + let conflicts = config + .pacman() + .cloned() + .and_then(|d| d.conflicts) + .unwrap_or_default(); + writeln!(file, "conflicts=({})", conflicts.join(" \n"))?; + + let replaces = config + .pacman() + .cloned() + .and_then(|d| d.replaces) + .unwrap_or_default(); + writeln!(file, "replaces=({})", replaces.join(" \n"))?; + + writeln!(file, "options=(!lto)")?; + let source = config + .pacman() + .cloned() + .and_then(|d| d.source) + .unwrap_or_default(); + + if source.is_empty() { + writeln!(file, "source=({:?})", package_path.file_name().unwrap())?;
do we need to set this if not provided by user?
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default();
instead of cloning the whole object, we can do ```suggestion let dependencies = config .pacman() .and_then(|d| d.depends.as_ref()) .cloned() .unwrap_or_default(); ``` I realize, this is a mistake I made in `deb/mod.rs` as well, so feel free to change that too.
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default();
ditto
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default(); + writeln!(file, "provides=({})", provides.join(" \n"))?; + + let conflicts = config + .pacman() + .cloned() + .and_then(|d| d.conflicts) + .unwrap_or_default();
ditto
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default(); + writeln!(file, "provides=({})", provides.join(" \n"))?; + + let conflicts = config + .pacman() + .cloned() + .and_then(|d| d.conflicts) + .unwrap_or_default(); + writeln!(file, "conflicts=({})", conflicts.join(" \n"))?; + + let replaces = config + .pacman() + .cloned() + .and_then(|d| d.replaces) + .unwrap_or_default();
ditto
cargo-packager
github_2023
others
137
crabnebula-dev
amr-crabnebula
@@ -0,0 +1,145 @@ +// Copyright 2024-2024 CrabNebula Ltd. +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use super::{ + deb::{copy_custom_files, generate_data, tar_and_gzip_dir}, + Context, +}; +use crate::{config::Config, util}; +use heck::AsKebabCase; +use sha2::{Digest, Sha512}; +use std::{ + fs::File, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[tracing::instrument(level = "trace")] +pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { + let Context { + config, + intermediates_path, + .. + } = ctx; + + let arch = match config.target_arch()? { + "x86" => "i386", + "arm" => "armhf", + other => other, + }; + + let intermediates_path = intermediates_path.join("pacman"); + util::create_clean_dir(&intermediates_path)?; + + let package_base_name = format!("{}_{}_{}", config.main_binary_name()?, config.version, arch); + let package_name = format!("{}.tar.gz", package_base_name); + + let pkg_dir = intermediates_path.join(&package_base_name); + let pkg_path = config.out_dir().join(&package_name); + let pkgbuild_path = pkg_path.with_file_name("PKGBUILD"); + + tracing::info!("Packaging {} ({})", package_name, pkg_path.display()); + + tracing::debug!("Generating data"); + let _ = generate_data(config, &pkg_dir)?; + + tracing::debug!("Copying files specified in `deb.files`"); + if let Some(files) = config.deb().and_then(|d| d.files.as_ref()) { + copy_custom_files(files, &pkg_dir)?; + } + + // Apply tar/gzip to create the final package file. + tracing::debug!("Creating package archive using tar and gzip"); + let data_tar_gz_path = tar_and_gzip_dir(pkg_dir)?; + std::fs::copy(data_tar_gz_path, &pkg_path)?; + + tracing::info!("Generating PKGBUILD: {}", pkgbuild_path.display()); + generate_pkgbuild_file(config, arch, pkgbuild_path.as_path(), pkg_path.as_path())?; + + Ok(vec![pkg_path]) +} + +/// Generates the pacman PKGBUILD file. +/// For more information about the format of this file, see +/// <https://wiki.archlinux.org/title/PKGBUILD> +fn generate_pkgbuild_file( + config: &Config, + arch: &str, + dest_dir: &Path, + package_path: &Path, +) -> crate::Result<()> { + let pkgbuild_path = dest_dir.with_file_name("PKGBUILD"); + let mut file = util::create_file(&pkgbuild_path)?; + + if let Some(authors) = &config.authors { + writeln!(file, "# Maintainer: {}", authors.join(", "))?; + } + writeln!(file, "pkgname={}-bin", AsKebabCase(&config.product_name))?; + writeln!(file, "pkgver={}", config.version)?; + writeln!(file, "pkgrel=1")?; + writeln!(file, "epoch=")?; + writeln!( + file, + "pkgdesc=\"{}\"", + config.description.as_deref().unwrap_or("") + )?; + writeln!(file, "arch=('{}')", arch)?; + + if let Some(homepage) = &config.homepage { + writeln!(file, "url=\"{}\"", homepage)?; + } + + let dependencies = config + .pacman() + .cloned() + .and_then(|d| d.depends) + .unwrap_or_default(); + writeln!(file, "depends=({})", dependencies.join(" \n"))?; + + let provides = config + .pacman() + .cloned() + .and_then(|d| d.provides) + .unwrap_or_default(); + writeln!(file, "provides=({})", provides.join(" \n"))?; + + let conflicts = config + .pacman() + .cloned() + .and_then(|d| d.conflicts) + .unwrap_or_default(); + writeln!(file, "conflicts=({})", conflicts.join(" \n"))?; + + let replaces = config + .pacman() + .cloned() + .and_then(|d| d.replaces) + .unwrap_or_default(); + writeln!(file, "replaces=({})", replaces.join(" \n"))?; + + writeln!(file, "options=(!lto)")?; + let source = config + .pacman() + .cloned() + .and_then(|d| d.source) + .unwrap_or_default();
ditto
cargo-packager
github_2023
others
132
crabnebula-dev
amr-crabnebula
@@ -52,6 +52,77 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { tracing::debug!("Copying frameworks"); let framework_paths = copy_frameworks_to_bundle(&contents_directory, config)?; + + // All dylib files and native executables should be signed manually + // It is highly discouraged by Apple to use the --deep codesign parameter in larger projects. + // https://developer.apple.com/forums/thread/129980 + for framework_path in &framework_paths { + if let Some(framework_path) = framework_path.to_str() { + // Find all files in the current framework folder + let constructed_glob = format!("{}/**/*", framework_path); + let files = match glob::glob(&constructed_glob) { + Ok(res) => res, + Err(err) => { + tracing::warn!("Could not construct a glob for {}: {}, please make sure your path contains no *", framework_path, err); + tracing::warn!("This path will not be scanned for dylibs!");
Let's merge these into a single `warn!` call
cargo-packager
github_2023
others
132
crabnebula-dev
amr-crabnebula
@@ -52,6 +52,77 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { tracing::debug!("Copying frameworks"); let framework_paths = copy_frameworks_to_bundle(&contents_directory, config)?; + + // All dylib files and native executables should be signed manually + // It is highly discouraged by Apple to use the --deep codesign parameter in larger projects. + // https://developer.apple.com/forums/thread/129980 + for framework_path in &framework_paths { + if let Some(framework_path) = framework_path.to_str() { + // Find all files in the current framework folder + let constructed_glob = format!("{}/**/*", framework_path); + let files = match glob::glob(&constructed_glob) { + Ok(res) => res, + Err(err) => { + tracing::warn!("Could not construct a glob for {}: {}, please make sure your path contains no *", framework_path, err); + tracing::warn!("This path will not be scanned for dylibs!"); + continue; + } + }; + + let files = files.filter_map(|p| match p { + Ok(v) => Some(v), + Err(err) => { + tracing::warn!( + "Error while globbing for Mach-O files in {}: {}", + framework_path, + err + ); + None + } + });
We can just use flatten, don't think we need log these errors, we can just skip them ```suggestion let files = files.flatten(); ```
cargo-packager
github_2023
others
132
crabnebula-dev
amr-crabnebula
@@ -52,6 +52,77 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { tracing::debug!("Copying frameworks"); let framework_paths = copy_frameworks_to_bundle(&contents_directory, config)?; + + // All dylib files and native executables should be signed manually + // It is highly discouraged by Apple to use the --deep codesign parameter in larger projects. + // https://developer.apple.com/forums/thread/129980 + for framework_path in &framework_paths { + if let Some(framework_path) = framework_path.to_str() { + // Find all files in the current framework folder + let constructed_glob = format!("{}/**/*", framework_path); + let files = match glob::glob(&constructed_glob) { + Ok(res) => res, + Err(err) => { + tracing::warn!("Could not construct a glob for {}: {}, please make sure your path contains no *", framework_path, err); + tracing::warn!("This path will not be scanned for dylibs!"); + continue; + } + }; + + let files = files.filter_map(|p| match p { + Ok(v) => Some(v), + Err(err) => { + tracing::warn!( + "Error while globbing for Mach-O files in {}: {}", + framework_path, + err + ); + None + } + }); + + // Filter all files for Mach-O headers. This will target all .dylib and native executable files + for file in files { + let Some(file) = file.to_str() else { + tracing::warn!("Failed to convert {} to a valid UTF-8 string, this path will not be scanned for Mach-O header!", file.display()); + continue; + };
this is not needed, since `fs::metadata` can accept `PathBuf` just fine
cargo-packager
github_2023
others
132
crabnebula-dev
amr-crabnebula
@@ -52,6 +52,77 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { tracing::debug!("Copying frameworks"); let framework_paths = copy_frameworks_to_bundle(&contents_directory, config)?; + + // All dylib files and native executables should be signed manually + // It is highly discouraged by Apple to use the --deep codesign parameter in larger projects. + // https://developer.apple.com/forums/thread/129980 + for framework_path in &framework_paths { + if let Some(framework_path) = framework_path.to_str() { + // Find all files in the current framework folder + let constructed_glob = format!("{}/**/*", framework_path); + let files = match glob::glob(&constructed_glob) { + Ok(res) => res, + Err(err) => { + tracing::warn!("Could not construct a glob for {}: {}, please make sure your path contains no *", framework_path, err); + tracing::warn!("This path will not be scanned for dylibs!"); + continue; + } + }; + + let files = files.filter_map(|p| match p { + Ok(v) => Some(v), + Err(err) => { + tracing::warn!( + "Error while globbing for Mach-O files in {}: {}", + framework_path, + err + ); + None + } + }); + + // Filter all files for Mach-O headers. This will target all .dylib and native executable files + for file in files { + let Some(file) = file.to_str() else { + tracing::warn!("Failed to convert {} to a valid UTF-8 string, this path will not be scanned for Mach-O header!", file.display()); + continue; + }; + + let Ok(metadata) = std::fs::metadata(file) else {
we should match here and append the error to the log message ```rs let metadata = match std::fs::metadata(file) { Ok(f) => f, Err(err) => { tracing::warn!("Failed to get metadata for {}: {err}, this file will not be scanned for Mach-O header!", file); continue; } }; ```
cargo-packager
github_2023
others
132
crabnebula-dev
amr-crabnebula
@@ -52,6 +52,77 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { tracing::debug!("Copying frameworks"); let framework_paths = copy_frameworks_to_bundle(&contents_directory, config)?; + + // All dylib files and native executables should be signed manually + // It is highly discouraged by Apple to use the --deep codesign parameter in larger projects. + // https://developer.apple.com/forums/thread/129980 + for framework_path in &framework_paths { + if let Some(framework_path) = framework_path.to_str() { + // Find all files in the current framework folder + let constructed_glob = format!("{}/**/*", framework_path); + let files = match glob::glob(&constructed_glob) { + Ok(res) => res, + Err(err) => { + tracing::warn!("Could not construct a glob for {}: {}, please make sure your path contains no *", framework_path, err); + tracing::warn!("This path will not be scanned for dylibs!"); + continue; + } + }; + + let files = files.filter_map(|p| match p { + Ok(v) => Some(v), + Err(err) => { + tracing::warn!( + "Error while globbing for Mach-O files in {}: {}", + framework_path, + err + ); + None + } + }); + + // Filter all files for Mach-O headers. This will target all .dylib and native executable files + for file in files { + let Some(file) = file.to_str() else { + tracing::warn!("Failed to convert {} to a valid UTF-8 string, this path will not be scanned for Mach-O header!", file.display()); + continue; + }; + + let Ok(metadata) = std::fs::metadata(file) else { + tracing::warn!("Failed to get metadata for {}, this file will not be scanned for Mach-O header!", file); + continue; + }; + + if !metadata.is_file() { + continue; + } + + let Ok(mut open_file) = std::fs::File::open(file) else { + tracing::warn!("Failed to open {} for reading, this file will not be scanned for Mach-O header!", file); + continue; + };
same here
cargo-packager
github_2023
others
132
crabnebula-dev
amr-crabnebula
@@ -52,6 +52,77 @@ pub(crate) fn package(ctx: &Context) -> crate::Result<Vec<PathBuf>> { tracing::debug!("Copying frameworks"); let framework_paths = copy_frameworks_to_bundle(&contents_directory, config)?; + + // All dylib files and native executables should be signed manually + // It is highly discouraged by Apple to use the --deep codesign parameter in larger projects. + // https://developer.apple.com/forums/thread/129980 + for framework_path in &framework_paths { + if let Some(framework_path) = framework_path.to_str() { + // Find all files in the current framework folder + let constructed_glob = format!("{}/**/*", framework_path); + let files = match glob::glob(&constructed_glob) { + Ok(res) => res, + Err(err) => { + tracing::warn!("Could not construct a glob for {}: {}, please make sure your path contains no *", framework_path, err); + tracing::warn!("This path will not be scanned for dylibs!"); + continue; + } + }; + + let files = files.filter_map(|p| match p { + Ok(v) => Some(v), + Err(err) => { + tracing::warn!( + "Error while globbing for Mach-O files in {}: {}", + framework_path, + err + ); + None + } + }); + + // Filter all files for Mach-O headers. This will target all .dylib and native executable files + for file in files { + let Some(file) = file.to_str() else { + tracing::warn!("Failed to convert {} to a valid UTF-8 string, this path will not be scanned for Mach-O header!", file.display()); + continue; + }; + + let Ok(metadata) = std::fs::metadata(file) else { + tracing::warn!("Failed to get metadata for {}, this file will not be scanned for Mach-O header!", file); + continue; + }; + + if !metadata.is_file() { + continue; + } + + let Ok(mut open_file) = std::fs::File::open(file) else { + tracing::warn!("Failed to open {} for reading, this file will not be scanned for Mach-O header!", file); + continue; + }; + + let mut buffer = [0; 4]; + std::io::Read::read_exact(&mut open_file, &mut buffer)?; + + // Mach-O magic numbers + let magic_numbers = [0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcefaedfe, 0xcffaedfe];
let's use a const here ```suggestion const MACH_O_MAGIC_NUMBERS: [u32; 5] = [0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcefaedfe, 0xcffaedfe]; ```