cli: Anchor registry publishing (#570)

This commit is contained in:
Armani Ferrante 2021-08-08 02:11:48 -07:00 committed by GitHub
parent 098c2a0048
commit 3248481288
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 989 additions and 307 deletions

View File

@ -11,6 +11,18 @@ incremented for features.
## [Unreleased]
### Features
* cli: Adds a [registry] section in the Anchor toml ([#570](https://github.com/project-serum/anchor/pull/570)).
* cli: Adds the anchor login <api-token> command ([#570](https://github.com/project-serum/anchor/pull/570)).
* cli: Adds the anchor publish <package> command ([#570](https://github.com/project-serum/anchor/pull/570)).
* cli: Adds a root level anchor_version field to the Anchor.toml for specifying the cli version to build with for verifiable build ([#570](https://github.com/project-serum/anchor/pull/570)).
### Breaking
* cli: `[clusters.<network>]` Anchor.toml section has been renamed to `[programs.<network>]` ([#570](https://github.com/project-serum/anchor/pull/570)).
* cli: `[workspace]` member and exclude arrays must now be filepaths relative to the workpsace root ([#570](https://github.com/project-serum/anchor/pull/570)).
## [0.12.0] - 2021-08-03
### Features

76
Cargo.lock generated
View File

@ -140,11 +140,14 @@ dependencies = [
"anchor-lang",
"anchor-syn",
"anyhow",
"cargo_toml",
"clap 3.0.0-beta.2",
"dirs",
"flate2",
"heck",
"pathdiff",
"rand 0.7.3",
"reqwest",
"serde",
"serde_json",
"serum-common",
@ -153,6 +156,8 @@ dependencies = [
"solana-program",
"solana-sdk",
"syn 1.0.67",
"tar",
"tokio 1.4.0",
"toml",
]
@ -549,6 +554,17 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "cargo_toml"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3596addfb02dcdc06f5252ddda9f3785f9230f5827fb4284645240fa05ad92"
dependencies = [
"serde",
"serde_derive",
"toml",
]
[[package]]
name = "cc"
version = "1.0.68"
@ -1542,6 +1558,19 @@ dependencies = [
"webpki",
]
[[package]]
name = "hyper-tls"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905"
dependencies = [
"bytes 1.0.1",
"hyper",
"native-tls",
"tokio 1.4.0",
"tokio-native-tls",
]
[[package]]
name = "idna"
version = "0.2.2"
@ -1827,6 +1856,16 @@ version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
[[package]]
name = "mime_guess"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2684d4c2e97d99848d30b324b00c8fcc7e5c897b7cbb5819b09e7c90e8baf212"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "miniz_oxide"
version = "0.4.4"
@ -2185,6 +2224,12 @@ dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "pathdiff"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877630b3de15c0b64cc52f659345724fbf6bdad9bd9566699fc53688f3c34a34"
[[package]]
name = "pbkdf2"
version = "0.4.0"
@ -2524,9 +2569,9 @@ dependencies = [
[[package]]
name = "reqwest"
version = "0.11.2"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf12057f289428dbf5c591c74bf10392e4a8003f993405a902f20117019022d4"
checksum = "246e9f61b9bb77df069a947682be06e31ac43ea37862e244a69f177694ea6d22"
dependencies = [
"base64 0.13.0",
"bytes 1.0.1",
@ -2537,11 +2582,14 @@ dependencies = [
"http-body",
"hyper",
"hyper-rustls",
"hyper-tls",
"ipnet",
"js-sys",
"lazy_static",
"log",
"mime",
"mime_guess",
"native-tls",
"percent-encoding",
"pin-project-lite",
"rustls",
@ -2549,6 +2597,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"tokio 1.4.0",
"tokio-native-tls",
"tokio-rustls",
"url",
"wasm-bindgen",
@ -3592,9 +3641,9 @@ dependencies = [
[[package]]
name = "tar"
version = "0.4.33"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0bcfbd6a598361fda270d82469fff3d65089dc33e175c9a131f7b4cd395f228"
checksum = "7d779dc6aeff029314570f666ec83f19df7280bb36ef338442cfa8c604021b80"
dependencies = [
"filetime",
"libc",
@ -3832,6 +3881,16 @@ dependencies = [
"syn 1.0.67",
]
[[package]]
name = "tokio-native-tls"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b"
dependencies = [
"native-tls",
"tokio 1.4.0",
]
[[package]]
name = "tokio-reactor"
version = "0.1.12"
@ -4035,6 +4094,15 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c"
[[package]]
name = "unicase"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
dependencies = [
"version_check",
]
[[package]]
name = "unicode-bidi"
version = "0.3.4"

View File

@ -6,7 +6,7 @@ edition = "2018"
[[bin]]
name = "anchor"
path = "src/main.rs"
path = "src/bin/main.rs"
[features]
dev = []
@ -31,3 +31,8 @@ dirs = "3.0"
heck = "0.3.1"
flate2 = "1.0.19"
rand = "0.7.3"
tar = "0.4.35"
reqwest = { version = "0.11.4", features = ["multipart", "blocking"] }
tokio = "1.0"
pathdiff = "0.2.0"
cargo_toml = "0.9.2"

7
cli/src/bin/main.rs Normal file
View File

@ -0,0 +1,7 @@
use anchor_cli::Opts;
use anyhow::Result;
use clap::Clap;
fn main() -> Result<()> {
anchor_cli::entry(Opts::parse())
}

View File

@ -1,7 +1,7 @@
use crate::ConfigOverride;
use anchor_client::Cluster;
use anchor_syn::idl::Idl;
use anyhow::{anyhow, Error, Result};
use clap::Clap;
use serde::{Deserialize, Serialize};
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::Keypair;
@ -13,13 +13,138 @@ use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
#[derive(Default, Debug, Clap)]
pub struct ConfigOverride {
/// Cluster override.
#[clap(global = true, long = "provider.cluster")]
pub cluster: Option<Cluster>,
/// Wallet override.
#[clap(global = true, long = "provider.wallet")]
pub wallet: Option<WalletPath>,
}
pub struct WithPath<T> {
inner: T,
path: PathBuf,
}
impl<T> WithPath<T> {
pub fn new(inner: T, path: PathBuf) -> Self {
Self { inner, path }
}
pub fn path(&self) -> &PathBuf {
&self.path
}
pub fn into_inner(self) -> T {
self.inner
}
}
impl<T> std::convert::AsRef<T> for WithPath<T> {
fn as_ref(&self) -> &T {
&self.inner
}
}
impl WithPath<Config> {
pub fn get_program_list(&self) -> Result<Vec<PathBuf>> {
// Canonicalize the workspace filepaths to compare with relative paths.
let (members, exclude) = self.canonicalize_workspace()?;
// Get all candidate programs.
//
// If [workspace.members] exists, then use that.
// Otherwise, default to `programs/*`.
let program_paths: Vec<PathBuf> = {
if members.is_empty() {
let path = self.path().parent().unwrap().join("programs");
fs::read_dir(path)?
.map(|dir| dir.map(|d| d.path().canonicalize().unwrap()))
.collect::<Vec<Result<PathBuf, std::io::Error>>>()
.into_iter()
.collect::<Result<Vec<PathBuf>, std::io::Error>>()?
} else {
members
}
};
// Filter out everything part of the exclude array.
Ok(program_paths
.into_iter()
.filter(|m| !exclude.contains(m))
.collect())
}
// TODO: this should read idl dir instead of parsing source.
pub fn read_all_programs(&self) -> Result<Vec<Program>> {
let mut r = vec![];
for path in self.get_program_list()? {
let idl = anchor_syn::idl::file::parse(path.join("src/lib.rs"))?;
let lib_name = extract_lib_name(&path.join("Cargo.toml"))?;
r.push(Program {
lib_name,
path,
idl,
});
}
Ok(r)
}
pub fn canonicalize_workspace(&self) -> Result<(Vec<PathBuf>, Vec<PathBuf>)> {
let members = self
.workspace
.members
.iter()
.map(|m| PathBuf::from(m).canonicalize().unwrap())
.collect();
let exclude = self
.workspace
.exclude
.iter()
.map(|m| PathBuf::from(m).canonicalize().unwrap())
.collect();
Ok((members, exclude))
}
}
impl<T> std::ops::Deref for WithPath<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> std::ops::DerefMut for WithPath<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
#[derive(Debug, Default)]
pub struct Config {
pub anchor_version: Option<String>,
pub solana_version: Option<String>,
pub registry: RegistryConfig,
pub provider: ProviderConfig,
pub clusters: ClustersConfig,
pub programs: ProgramsConfig,
pub scripts: ScriptsConfig,
pub test: Option<Test>,
pub workspace: WorkspaceConfig,
pub test: Option<Test>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RegistryConfig {
pub url: String,
}
impl Default for RegistryConfig {
fn default() -> Self {
Self {
url: "https://anchor.projectserum.com".to_string(),
}
}
}
#[derive(Debug, Default)]
@ -30,7 +155,7 @@ pub struct ProviderConfig {
pub type ScriptsConfig = BTreeMap<String, String>;
pub type ClustersConfig = BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>;
pub type ProgramsConfig = BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>;
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct WorkspaceConfig {
@ -41,11 +166,19 @@ pub struct WorkspaceConfig {
}
impl Config {
pub fn docker(&self) -> String {
let ver = self
.anchor_version
.clone()
.unwrap_or_else(|| crate::DOCKER_BUILDER_VERSION.to_string());
format!("projectserum/build:v{}", ver)
}
pub fn discover(
cfg_override: &ConfigOverride,
) -> Result<Option<(Self, PathBuf, Option<PathBuf>)>> {
) -> Result<Option<(WithPath<Config>, Option<PathBuf>)>> {
Config::_discover().map(|opt| {
opt.map(|(mut cfg, cfg_path, cargo_toml)| {
opt.map(|(mut cfg, cargo_toml)| {
if let Some(cluster) = cfg_override.cluster.clone() {
cfg.provider.cluster = cluster;
}
@ -53,13 +186,13 @@ impl Config {
if let Some(wallet) = cfg_override.wallet.clone() {
cfg.provider.wallet = wallet;
}
(cfg, cfg_path, cargo_toml)
(cfg, cargo_toml)
})
})
}
// Searches all parent directories for an Anchor.toml file.
fn _discover() -> Result<Option<(Self, PathBuf, Option<PathBuf>)>> {
fn _discover() -> Result<Option<(WithPath<Config>, Option<PathBuf>)>> {
// Set to true if we ever see a Cargo.toml file when traversing the
// parent directories.
let mut cargo_toml = None;
@ -87,12 +220,17 @@ impl Config {
}
}
if let Some((cfg, parent)) = anchor_toml {
return Ok(Some((cfg, parent, cargo_toml)));
// Set the Cargo.toml if it's for a single package, i.e., not the
// root workspace Cargo.toml.
if cargo_toml.is_none() && cargo_toml_level.is_some() {
let toml = cargo_toml::Manifest::from_path(cargo_toml_level.as_ref().unwrap())?;
if toml.workspace.is_none() {
cargo_toml = cargo_toml_level;
}
}
if cargo_toml.is_none() {
cargo_toml = cargo_toml_level;
if let Some((cfg, parent)) = anchor_toml {
return Ok(Some((WithPath::new(cfg, parent), cargo_toml)));
}
cwd_opt = cwd.parent();
@ -105,61 +243,17 @@ impl Config {
solana_sdk::signature::read_keypair_file(&self.provider.wallet.to_string())
.map_err(|_| anyhow!("Unable to read keypair file"))
}
pub fn get_program_list(&self, path: PathBuf) -> Result<Vec<PathBuf>> {
let mut programs = vec![];
for f in fs::read_dir(path)? {
let path = f?.path();
let program = path
.components()
.last()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.expect("failed to get program from path");
match (
self.workspace.members.is_empty(),
self.workspace.exclude.is_empty(),
) {
(true, true) => programs.push(path),
(true, false) => {
if !self.workspace.exclude.contains(&program) {
programs.push(path);
}
}
(false, _) => {
if self.workspace.members.contains(&program) {
programs.push(path);
}
}
}
}
Ok(programs)
}
// TODO: this should read idl dir instead of parsing source.
pub fn read_all_programs(&self) -> Result<Vec<Program>> {
let mut r = vec![];
for path in self.get_program_list("programs".into())? {
let idl = anchor_syn::idl::file::parse(path.join("src/lib.rs"))?;
let lib_name = extract_lib_name(&path.join("Cargo.toml"))?;
r.push(Program {
lib_name,
path,
idl,
});
}
Ok(r)
}
}
// Pubkey serializes as a byte array so use this type a hack to serialize
// into base 58 strings.
#[derive(Debug, Serialize, Deserialize)]
struct _Config {
anchor_version: Option<String>,
solana_version: Option<String>,
registry: Option<RegistryConfig>,
provider: Provider,
test: Option<Test>,
scripts: Option<ScriptsConfig>,
clusters: Option<BTreeMap<String, BTreeMap<String, serde_json::Value>>>,
programs: Option<BTreeMap<String, BTreeMap<String, serde_json::Value>>>,
workspace: Option<WorkspaceConfig>,
}
@ -171,8 +265,8 @@ struct Provider {
impl ToString for Config {
fn to_string(&self) -> String {
let clusters = {
let c = ser_clusters(&self.clusters);
let programs = {
let c = ser_programs(&self.programs);
if c.is_empty() {
None
} else {
@ -180,6 +274,9 @@ impl ToString for Config {
}
};
let cfg = _Config {
anchor_version: self.anchor_version.clone(),
solana_version: self.solana_version.clone(),
registry: Some(self.registry.clone()),
provider: Provider {
cluster: format!("{}", self.provider.cluster),
wallet: self.provider.wallet.to_string(),
@ -189,7 +286,7 @@ impl ToString for Config {
true => None,
false => Some(self.scripts.clone()),
},
clusters,
programs,
workspace: (!self.workspace.members.is_empty() || !self.workspace.exclude.is_empty())
.then(|| self.workspace.clone()),
};
@ -205,34 +302,25 @@ impl FromStr for Config {
let cfg: _Config = toml::from_str(s)
.map_err(|e| anyhow::format_err!("Unable to deserialize config: {}", e.to_string()))?;
Ok(Config {
anchor_version: cfg.anchor_version,
solana_version: cfg.solana_version,
registry: cfg.registry.unwrap_or_default(),
provider: ProviderConfig {
cluster: cfg.provider.cluster.parse()?,
wallet: shellexpand::tilde(&cfg.provider.wallet).parse()?,
},
scripts: cfg.scripts.unwrap_or_else(BTreeMap::new),
test: cfg.test,
clusters: cfg.clusters.map_or(Ok(BTreeMap::new()), deser_clusters)?,
workspace: cfg.workspace.map(|workspace| {
let (members, exclude) = match (workspace.members.is_empty(), workspace.exclude.is_empty()) {
(true, true) => (vec![], vec![]),
(true, false) => (vec![], workspace.exclude),
(false, is_empty) => {
if !is_empty {
println!("Fields `members` and `exclude` in `[workspace]` section are not compatible, only `members` will be used.");
}
(workspace.members, vec![])
}
};
WorkspaceConfig { members, exclude }
}).unwrap_or_default()
programs: cfg.programs.map_or(Ok(BTreeMap::new()), deser_programs)?,
workspace: cfg.workspace.unwrap_or_default(),
})
}
}
fn ser_clusters(
clusters: &BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>,
fn ser_programs(
programs: &BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>,
) -> BTreeMap<String, BTreeMap<String, serde_json::Value>> {
clusters
programs
.iter()
.map(|(cluster, programs)| {
let cluster = cluster.to_string();
@ -249,11 +337,10 @@ fn ser_clusters(
})
.collect::<BTreeMap<String, BTreeMap<String, serde_json::Value>>>()
}
fn deser_clusters(
clusters: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
fn deser_programs(
programs: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
) -> Result<BTreeMap<Cluster, BTreeMap<String, ProgramDeployment>>> {
clusters
programs
.iter()
.map(|(cluster, programs)| {
let cluster: Cluster = cluster.parse()?;
@ -265,6 +352,7 @@ fn deser_clusters(
ProgramDeployment::try_from(match &program_id {
serde_json::Value::String(address) => _ProgramDeployment {
address: address.parse()?,
path: None,
idl: None,
},
serde_json::Value::Object(_) => {
@ -294,25 +382,15 @@ pub struct GenesisEntry {
pub program: String,
}
pub fn extract_lib_name(path: impl AsRef<Path>) -> Result<String> {
let mut toml = File::open(path)?;
let mut contents = String::new();
toml.read_to_string(&mut contents)?;
let cargo_toml: toml::Value = contents.parse()?;
match cargo_toml {
toml::Value::Table(t) => match t.get("lib") {
None => Err(anyhow!("lib not found in Cargo.toml")),
Some(lib) => match lib
.get("name")
.ok_or_else(|| anyhow!("lib name not found in Cargo.toml"))?
{
toml::Value::String(n) => Ok(n.to_string()),
_ => Err(anyhow!("lib name must be a string")),
},
},
_ => Err(anyhow!("Invalid Cargo.toml")),
pub fn extract_lib_name(cargo_toml: impl AsRef<Path>) -> Result<String> {
let cargo_toml = cargo_toml::Manifest::from_path(cargo_toml)?;
if cargo_toml.lib.is_some() && cargo_toml.lib.as_ref().unwrap().name.is_some() {
Ok(cargo_toml.lib.unwrap().name.unwrap())
} else {
Ok(cargo_toml
.package
.ok_or_else(|| anyhow!("Package section not provided"))?
.name)
}
}
@ -320,7 +398,7 @@ pub fn extract_lib_name(path: impl AsRef<Path>) -> Result<String> {
pub struct Program {
pub lib_name: String,
pub path: PathBuf,
pub idl: Idl,
pub idl: Option<Idl>,
}
impl Program {
@ -343,6 +421,7 @@ impl Program {
#[derive(Debug, Default)]
pub struct ProgramDeployment {
pub address: Pubkey,
pub path: Option<String>,
pub idl: Option<String>,
}
@ -351,6 +430,7 @@ impl TryFrom<_ProgramDeployment> for ProgramDeployment {
fn try_from(pd: _ProgramDeployment) -> Result<Self, Self::Error> {
Ok(ProgramDeployment {
address: pd.address.parse()?,
path: pd.path,
idl: pd.idl,
})
}
@ -359,6 +439,7 @@ impl TryFrom<_ProgramDeployment> for ProgramDeployment {
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct _ProgramDeployment {
pub address: String,
pub path: Option<String>,
pub idl: Option<String>,
}
@ -366,6 +447,7 @@ impl From<&ProgramDeployment> for _ProgramDeployment {
fn from(pd: &ProgramDeployment) -> Self {
Self {
address: pd.address.to_string(),
path: pd.path.clone(),
idl: pd.idl.clone(),
}
}
@ -377,4 +459,40 @@ pub struct ProgramWorkspace {
pub idl: Idl,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AnchorPackage {
pub name: String,
pub address: String,
pub path: String,
pub idl: Option<String>,
}
impl AnchorPackage {
pub fn from(name: String, cfg: &WithPath<Config>) -> Result<Self> {
let cluster = &cfg.provider.cluster;
if cluster != &Cluster::Mainnet {
return Err(anyhow!("Publishing requires the mainnet cluster"));
}
let program_details = cfg
.programs
.get(cluster)
.ok_or_else(|| anyhow!("Program not provided in Anchor.toml"))?
.get(&name)
.ok_or_else(|| anyhow!("Program not provided in Anchor.toml"))?;
let path = program_details
.path
.clone()
// TODO: use a default path if one isn't provided?
.ok_or_else(|| anyhow!("Path to program binary not provided"))?;
let idl = program_details.idl.clone();
let address = program_details.address.to_string();
Ok(Self {
name,
path,
address,
idl,
})
}
}
serum_common::home_path!(WalletPath, ".config/solana/id.json");

File diff suppressed because it is too large Load Diff

View File

@ -11,6 +11,15 @@ members = [
"#
}
pub fn credentials(token: &str) -> String {
format!(
r#"[registry]
token = "{}"
"#,
token
)
}
pub fn cargo_toml(name: &str) -> String {
format!(
r#"[package]

View File

@ -2,7 +2,7 @@
cluster = "localnet"
wallet = "~/.config/solana/id.json"
[clusters.localnet]
[programs.localnet]
registry = { address = "GrAkKfEpTKQuVHG2Y97Y2FF4i7y7Q5AHLK94JBy7Y5yv", idl = "./deps/stake/target/idl/registry.json" }
lockup = { address = "6ebQNeTPZ1j7k3TtkCCtEPRvG7GQsucQrZ7sSEDQi9Ks", idl = "./deps/stake/target/idl/lockup.json" }

View File

@ -7,7 +7,7 @@ address = "FtMNMKp9DZHKWUyVAsj3Q5QV8ow4P3fUPP7ZrWEQJzKr"
program = "./target/deploy/misc.so"
[workspace]
exclude = ["shared"]
exclude = ["programs/shared"]
[scripts]
test = "mocha -t 1000000 tests/"

View File

@ -3,8 +3,7 @@ cluster = "localnet"
wallet = "~/.config/solana/id.json"
[workspace]
members = ["typescript"]
exclude = ["typescript"]
members = ["programs/typescript"]
[scripts]
test = "ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"

View File

@ -3,7 +3,7 @@ cluster = "localnet"
wallet = "~/.config/solana/id.json"
[workspace]
members = ["zero-copy"]
members = ["programs/zero-copy"]
[scripts]
test = "mocha -t 1000000 tests/"

View File

@ -13,10 +13,14 @@ const DERIVE_NAME: &str = "Accounts";
const ERROR_CODE_OFFSET: u32 = 300;
// Parse an entire interface file.
pub fn parse(filename: impl AsRef<Path>) -> Result<Idl> {
pub fn parse(filename: impl AsRef<Path>) -> Result<Option<Idl>> {
let ctx = CrateContext::parse(filename)?;
let p = program::parse(parse_program_mod(&ctx))?;
let program_mod = match parse_program_mod(&ctx) {
None => return Ok(None),
Some(m) => m,
};
let p = program::parse(program_mod)?;
let accs = parse_account_derives(&ctx);
@ -218,7 +222,7 @@ pub fn parse(filename: impl AsRef<Path>) -> Result<Idl> {
}
}
Ok(Idl {
Ok(Some(Idl {
version: "0.0.0".to_string(),
name: p.name.to_string(),
state,
@ -232,11 +236,11 @@ pub fn parse(filename: impl AsRef<Path>) -> Result<Idl> {
},
errors: error_codes,
metadata: None,
})
}))
}
// Parse the main program mod.
fn parse_program_mod(ctx: &CrateContext) -> syn::ItemMod {
fn parse_program_mod(ctx: &CrateContext) -> Option<syn::ItemMod> {
let root = ctx.root_module();
let mods = root
.items()
@ -256,9 +260,9 @@ fn parse_program_mod(ctx: &CrateContext) -> syn::ItemMod {
})
.collect::<Vec<_>>();
if mods.len() != 1 {
panic!("Did not find program attribute");
return None;
}
mods[0].clone()
Some(mods[0].clone())
}
fn parse_error_enum(ctx: &CrateContext) -> Option<syn::ItemEnum> {

View File

@ -67,10 +67,10 @@ const workspace = new Proxy({} as any, {
fs.readFileSync(path.join(projectRoot, "Anchor.toml"), "utf-8")
);
const clusterId = anchorToml.provider.cluster;
if (anchorToml.clusters && anchorToml.clusters[clusterId]) {
if (anchorToml.programs && anchorToml.programs[clusterId]) {
attachWorkspaceOverride(
workspaceCache,
anchorToml.clusters[clusterId],
anchorToml.programs[clusterId],
idlMap
);
}